From 681a56a741c14c46e0320c750334f1d169c65c28 Mon Sep 17 00:00:00 2001 From: printempw Date: Sun, 4 Sep 2016 15:35:12 +0800 Subject: [PATCH] use validator of laravel instead of Validate class --- app/Http/Controllers/AdminController.php | 188 ++++++++++-------- app/Http/Controllers/AuthController.php | 9 +- app/Http/Controllers/ClosetController.php | 50 +++-- app/Http/Controllers/Controller.php | 3 +- app/Http/Controllers/HomeController.php | 7 +- app/Http/Controllers/PlayerController.php | 119 +++++------ app/Http/Controllers/SkinlibController.php | 182 ++++++++--------- app/Http/Controllers/TextureController.php | 65 +++--- app/Http/Controllers/UserController.php | 155 +++++++++------ app/Http/Middleware/CheckAuthenticated.php | 8 +- app/Http/routes.php | 1 + app/Models/Player.php | 50 +++-- app/Providers/AppServiceProvider.php | 20 ++ .../ResponseMacroServiceProvider.php | 4 + app/Services/Validate.php | 65 ------ setup/bootstrap.php | 23 +++ setup/index.php | 16 +- 17 files changed, 503 insertions(+), 462 deletions(-) delete mode 100644 app/Services/Validate.php diff --git a/app/Http/Controllers/AdminController.php b/app/Http/Controllers/AdminController.php index 8e4464b9..aabbd672 100644 --- a/app/Http/Controllers/AdminController.php +++ b/app/Http/Controllers/AdminController.php @@ -2,18 +2,17 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; -use App\Models\User; -use App\Models\UserModel; -use App\Models\Player; -use App\Models\PlayerModel; -use App\Models\Texture; -use App\Exceptions\PrettyPageException; -use Validate; -use Utils; use View; +use Utils; +use App\Models\User; +use App\Models\Player; +use App\Models\Texture; +use App\Models\UserModel; +use App\Models\PlayerModel; +use Illuminate\Http\Request; +use App\Exceptions\PrettyPageException; -class AdminController extends BaseController +class AdminController extends Controller { public function index() @@ -36,12 +35,17 @@ class AdminController extends BaseController return view('admin.options'); } - public function update() + /** + * Handle Upload Checking & Downloading + * + * @param Request $request + * @return void + */ + public function update(Request $request) { - $action = Utils::getValue('action', $_GET); - - if ($action == "check") { + if ($request->action == "check") { $updater = new \Updater(\App::version()); + if ($updater->newVersionAvailable()) { View::json([ 'new_version_available' => true, @@ -53,20 +57,24 @@ class AdminController extends BaseController 'latest_version' => $updater->current_version ]); } - } elseif ($action == "download") { + } elseif ($request->action == "download") { return view('admin.download'); } else { return view('admin.update'); } } - public function users() + /** + * Show Manage Page of Users. + * + * @param Request $request + * @return \Illuminate\Http\Response + */ + public function users(Request $request) { - $page = isset($_GET['page']) ? $_GET['page'] : 1; - - $filter = isset($_GET['filter']) ? $_GET['filter'] : ""; - - $q = isset($_GET['q']) ? $_GET['q'] : ""; + $page = $request->input('page', 1); + $filter = $request->input('filter', ''); + $q = $request->input('q', ''); if ($filter == "") { $users = UserModel::orderBy('uid'); @@ -79,21 +87,24 @@ class AdminController extends BaseController $total_pages = ceil($users->count() / 30); $users = $users->skip(($page - 1) * 30)->take(30)->get(); - return View::make('admin.users')->with('users', $users) - ->with('filter', $filter) - ->with('q', $q) - ->with('page', $page) - ->with('total_pages', $total_pages) - ->render(); + return view('admin.users')->with('users', $users) + ->with('filter', $filter) + ->with('q', $q) + ->with('page', $page) + ->with('total_pages', $total_pages); } - public function players() + /** + * Show Manage Page of Players. + * + * @param Request $request + * @return \Illuminate\Http\Response + */ + public function players(Request $request) { - $page = isset($_GET['page']) ? $_GET['page'] : 1; - - $filter = isset($_GET['filter']) ? $_GET['filter'] : ""; - - $q = isset($_GET['q']) ? $_GET['q'] : ""; + $page = $request->input('page', 1); + $filter = $request->input('filter', ''); + $q = $request->input('q', ''); if ($filter == "") { $players = PlayerModel::orderBy('uid'); @@ -106,31 +117,35 @@ class AdminController extends BaseController $total_pages = ceil($players->count() / 30); $players = $players->skip(($page - 1) * 30)->take(30)->get(); - return View::make('admin.players')->with('players', $players) - ->with('filter', $filter) - ->with('q', $q) - ->with('page', $page) - ->with('total_pages', $total_pages) - ->render(); + return view('admin.players')->with('players', $players) + ->with('filter', $filter) + ->with('q', $q) + ->with('page', $page) + ->with('total_pages', $total_pages); } /** * Handle ajax request from /admin/users + * + * @param Request $request + * @return void */ - public function userAjaxHandler() + public function userAjaxHandler(Request $request) { - $action = isset($_GET['action']) ? $_GET['action'] : ""; + $action = $request->input('action'); if ($action == "color") { - Validate::checkPost(['color_scheme']); + $this->validate($request, [ + 'color_scheme' => 'required' + ]); - $color_scheme = str_replace('_', '-', $_POST['color_scheme']); + $color_scheme = str_replace('_', '-', $request->input('color_scheme')); \Option::set('color_scheme', $color_scheme); View::json('修改配色成功', 0); } - $user = new User(Utils::getValue('uid', $_POST)); + $user = new User($request->input('uid')); // current user $cur_user = new User(session('uid')); @@ -138,37 +153,36 @@ class AdminController extends BaseController View::json('用户不存在', 1); if ($action == "email") { - Validate::checkPost(['email']); + $this->validate($request, [ + 'email' => 'required|email' + ]); - if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - View::json('邮箱格式错误', 3); - } - - if ($user->setEmail($_POST['email'])) + if ($user->setEmail($request->input('email'))) View::json('邮箱修改成功', 0); } elseif ($action == "nickname") { - Validate::checkPost(['nickname']); + $this->validate($request, [ + 'nickname' => 'required|nickname' + ]); - if (Utils::convertString($_POST['nickname']) != $_POST['nickname']) - View::json('无效的昵称。昵称中包含了奇怪的字符。', 1); - - if ($user->setNickName($_POST['nickname'])) - View::json('昵称已成功设置为 '.$_POST['nickname'], 0); + if ($user->setNickName($request->input('nickname'))) + View::json('昵称已成功设置为 '.$request->input('nickname'), 0); } elseif ($action == "password") { - Validate::checkPost(['password']); + $this->validate($request, [ + 'password' => 'required|min:8|max:16' + ]); - if (\Validate::password($_POST['password'])) { - if ($user->changePasswd($_POST['password'])) - View::json('密码修改成功', 0); - } + if ($user->changePasswd($request->input('password'))) + View::json('密码修改成功', 0); } elseif ($action == "score") { - Validate::checkPost(['score']); + $this->validate($request, [ + 'score' => 'required|integer' + ]); - if ($user->setScore($_POST['score'])) - View::json('积分修改成功', 0); + if ($user->setScore($request->input('score'))) + View::json('积分修改成功', 0); } elseif ($action == "ban") { if ($user->getPermission() == "1") { @@ -217,50 +231,48 @@ class AdminController extends BaseController /** * Handle ajax request from /admin/players */ - public function playerAjaxHandler() + public function playerAjaxHandler(Request $request) { $action = isset($_GET['action']) ? $_GET['action'] : ""; // exception will be throw by model if player is not existent - $player = new Player(Utils::getValue('pid', $_POST)); + $player = new Player($request->input('pid')); if ($action == "preference") { - Validate::checkPost(['preference']); + $this->validate($request, [ + 'preference' => 'required|preference' + ]); - if ($_POST['preference'] != "default" && $_POST['preference'] != "slim") - View::json('无效的参数', 0); - - if ($player->setPreference($_POST['preference'])) - View::json('角色 '.$player->player_name.' 的优先模型已更改至 '.$_POST['preference'], 0); + if ($player->setPreference($request->input('preference'))) + View::json('角色 '.$player->player_name.' 的优先模型已更改至 '.$request->input('preference'), 0); } elseif ($action == "texture") { - Validate::checkPost(['model', 'tid']); + $this->validate($request, [ + 'model' => 'required|model', + 'tid' => 'required|integer' + ]); - if ($_POST['model'] != "steve" && $_POST['model'] != "alex" && $_POST['model'] != "cape") - View::json('无效的参数', 0); + if (!Texture::find($request->tid)) + View::json("材质 tid.{$request->tid} 不存在", 1); - if (!(is_numeric($_POST['tid']) && Texture::find($_POST['tid']))) - View::json('材质 tid.'.$_POST['tid'].' 不存在', 1); - - if ($player->setTexture(['tid_'.$_POST['model'] => $_POST['tid']])) - View::json('角色 '.$player->player_name.' 的材质修改成功', 0); + if ($player->setTexture(['tid_'.$request->model => $request->tid])) + View::json("角色 {$player->player_name} 的材质修改成功", 0); } elseif ($action == "owner") { - Validate::checkPost(['uid']); + $this->validate($request, [ + 'tid' => 'required|integer' + ]); - if (!is_numeric($_POST['uid'])) - View::json('无效的参数', 0); - - $user = new User($_POST['uid']); + $user = new User($request->input('uid')); if (!$user->is_registered) View::json('不存在的用户', 1); - if ($player->setOwner($_POST['uid'])) - View::json('角色 '.$player->player_name.' 已成功让渡至 '.$user->getNickName(), 0); + if ($player->setOwner($request->input('uid'))) + View::json("角色 $player->player_name 已成功让渡至 ".$user->getNickName(), 0); } elseif ($action == "delete") { - if (PlayerModel::where('pid', $_POST['pid'])->delete()) + if (PlayerModel::where('pid', $request->input('pid'))->delete()) View::json('角色已被成功删除', 0); } else { View::json('非法参数', 1); diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index d4046ac9..47f01ba1 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -2,16 +2,15 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; -use App\Models\User; -use App\Models\UserModel; -use App\Exceptions\PrettyPageException; use Mail; use View; use Utils; use Option; -use Http; use Session; +use App\Models\User; +use App\Models\UserModel; +use Illuminate\Http\Request; +use App\Exceptions\PrettyPageException; class AuthController extends Controller { diff --git a/app/Http/Controllers/ClosetController.php b/app/Http/Controllers/ClosetController.php index 425dd207..5e88ce42 100644 --- a/app/Http/Controllers/ClosetController.php +++ b/app/Http/Controllers/ClosetController.php @@ -2,17 +2,22 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; -use App\Models\User; -use App\Models\Texture; -use App\Models\Closet; -use App\Models\ClosetModel; -use App\Exceptions\PrettyPageException; use View; use Option; +use App\Models\User; +use App\Models\Closet; +use App\Models\Texture; +use App\Models\ClosetModel; +use Illuminate\Http\Request; +use App\Exceptions\PrettyPageException; -class ClosetController extends BaseController +class ClosetController extends Controller { + /** + * Instance of Closet. + * + * @var \App\Models\Closet + */ private $closet; public function __construct() @@ -20,11 +25,10 @@ class ClosetController extends BaseController $this->closet = new Closet(session('uid')); } - public function index() + public function index(Request $request) { - $category = isset($_GET['category']) ? $_GET['category'] : "skin"; - - $page = isset($_GET['page']) ? $_GET['page'] : 1; + $category = $request->input('category', 'skin'); + $page = $request->input('page', 1); $items = array_slice($this->closet->getItems($category), ($page-1)*6, 6); @@ -43,26 +47,30 @@ class ClosetController extends BaseController View::json($this->closet->getItems()); } - public function add() + public function add(Request $request) { - \Validate::checkPost(['tid', 'name']); + $this->validate($request, [ + 'tid' => 'required|integer', + 'name' => 'required|nickname', + ]); - if ($this->closet->add($_POST['tid'], $_POST['name'])) { - $t = Texture::find($_POST['tid']); + if ($this->closet->add($request->tid, $request->name)) { + $t = Texture::find($request->tid); $t->likes += 1; $t->save(); - View::json('材质 '.$_POST['name'].' 收藏成功~', 0); + View::json('材质 '.$request->input('name').' 收藏成功~', 0); } } - public function remove() + public function remove(Request $request) { - if (!is_numeric(\Utils::getValue('tid', $_POST))) - View::json('非法参数', 1); + $this->validate($request, [ + 'tid' => 'required|integer' + ]); - if ($this->closet->remove($_POST['tid'])) { - $t = Texture::find($_POST['tid']); + if ($this->closet->remove($request->tid)) { + $t = Texture::find($request->tid); $t->likes = $t->likes - 1; $t->save(); diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index fe45b556..51994e1d 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -16,6 +16,7 @@ class Controller extends BaseController */ protected function formatValidationErrors(Validator $validator) { - return $validator->errors()->all(); + //return $validator->errors()->all(); + dd($validator->errors()->all()); } } diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 90a5537e..e6d9ccf8 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -2,11 +2,10 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; use App\Models\User; use Session; -class HomeController extends BaseController +class HomeController extends Controller { public function index() @@ -24,9 +23,9 @@ class HomeController extends BaseController } } - $user = session()->has('uid') ? new User(session('uid')) : null; + $user = Session::has('uid') ? new User(session('uid')) : null; - echo \View::make('index')->with('user', $user); + return view('index')->with('user', $user); } } diff --git a/app/Http/Controllers/PlayerController.php b/app/Http/Controllers/PlayerController.php index c447c62d..d0180246 100644 --- a/app/Http/Controllers/PlayerController.php +++ b/app/Http/Controllers/PlayerController.php @@ -2,53 +2,54 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; -use App\Events\PlayerWasAdded; -use App\Models\User; -use App\Models\Player; -use App\Models\PlayerModel; -use App\Models\Texture; -use App\Exceptions\PrettyPageException; -use Validate; +use View; use Event; use Utils; use Option; -use View; +use App\Models\User; +use App\Models\Player; +use App\Models\Texture; +use App\Models\PlayerModel; +use Illuminate\Http\Request; +use App\Events\PlayerWasAdded; +use App\Exceptions\PrettyPageException; -class PlayerController extends BaseController +class PlayerController extends Controller { - private $player = null; + /** + * User Instance. + * + * @var \App\Models\User + */ + private $user; - private $user = null; + /** + * Player Instance. + * + * @var \App\Models\Player + */ + private $player; - public function __construct() + public function __construct(Request $request) { $this->user = new User(session('uid')); - if (isset($_POST['pid'])) { - $this->player = new Player($_POST['pid']); - if (!$this->player) - abort(404, '角色不存在'); - } + if ($request->has('pid')) + $this->player = new Player($request->pid); } public function index() { - return View::make('user.player')->with('players', $this->user->getPlayers()->toArray())->with('user', $this->user); + return view('user.player')->with('players', $this->user->getPlayers()->toArray())->with('user', $this->user); } - public function add() + public function add(Request $request) { - $player_name = $_POST['player_name']; + $this->validate($request, [ + 'player_name' => 'required|'.(Option::get('allow_chinese_playername') == "1") ? 'pname_chinese' : 'player_name' + ]); - if (!isset($player_name)) - View::json('你还没有填写要添加的角色名哦', 1); - - if (!Validate::playerName($player_name)) - { - $msg = "无效的角色名。角色名只能包含" . ((Option::get('allow_chinese_playername') == "1") ? "汉字、" : "")."字母、数字以及下划线"; - View::json($msg, 2); - } + $player_name = $request->input('player_name'); if (!PlayerModel::where('player_name', $player_name)->get()->isEmpty()) View::json('该角色名已经被其他人注册掉啦', 6); @@ -67,18 +68,18 @@ class PlayerController extends BaseController $this->user->setScore(Option::get('score_per_player'), 'minus'); - View::json('成功添加了角色 '.$player_name.'', 0); - + View::json("成功添加了角色 $player_name", 0); } - public function delete() + public function delete(Request $request) { - $player_name = $this->player->model->player_name; - $this->player->model->delete(); + $player_name = $this->player->player_name; - $this->user->setScore(Option::get('score_per_player'), 'plus'); + if ($this->player->delete()) { + $this->user->setScore(Option::get('score_per_player'), 'plus'); - View::json('角色 '.$player_name.' 已被删除', 0); + View::json("角色 $player_name 已被删除", 0); + } } public function show() @@ -86,18 +87,13 @@ class PlayerController extends BaseController return json_encode($this->player->model->toArray(), JSON_NUMERIC_CHECK); } - public function rename() + public function rename(Request $request) { - $new_player_name = Utils::getValue('new_player_name', $_POST); + $this->validate($request, [ + 'new_player_name' => 'required|'.(Option::get('allow_chinese_playername') == "1") ? 'pname_chinese' : 'player_name' + ]); - if (!$new_player_name) - View::json('非法参数', 1); - - if (!Validate::playerName($new_player_name)) - { - $msg = "无效的角色名。角色名只能包含" . ((Option::get('allow_chinese_playername') == "1") ? "汉字、" : "")."字母、数字以及下划线"; - View::json($msg, 2); - } + $new_player_name = $request->input('new_player_name'); if (!PlayerModel::where('player_name', $new_player_name)->get()->isEmpty()) View::json('此角色名已被他人使用,换一个吧~', 6); @@ -111,43 +107,38 @@ class PlayerController extends BaseController /** * A wrapper of Player::setTexture() */ - public function setTexture() + public function setTexture(Request $request) { - $tid = Utils::getValue('tid', $_POST); - - if (!is_numeric($tid)) - View::json('非法参数', 1); + $this->validate($request, [ + 'tid' => 'required|integer' + ]); if (!($texture = Texture::find($tid))) - View::json('Unexistent texture.', 6); + View::json('材质不存在', 6); $field_name = "tid_".$texture->type; $this->player->setTexture([$field_name => $tid]); - View::json('材质已成功应用至角色 '.$this->player->model->player_name.'', 0); + View::json('材质已成功应用至角色 '.$this->player->player_name, 0); } - - public function clearTexture() { $this->player->clearTexture(); - View::json('角色 '.$this->player->model->player_name.' 的材质已被成功重置', 0); + View::json('角色 '.$this->player->player_name.' 的材质已被成功重置', 0); } - public function setPreference() + public function setPreference(Request $request) { - if (!isset($_POST['preference']) || - ($_POST['preference'] != "default" && $_POST['preference'] != "slim")) - { - View::json('非法参数', 1); - } + $this->validate($request, [ + 'preference' => 'required|preference' + ]); - $this->player->setPreference($_POST['preference']); + $this->player->setPreference($request->preference); - View::json('角色 '.$this->player->player_name.' 的优先模型已更改至 '.$_POST['preference'], 0); + View::json('角色 '.$this->player->player_name.' 的优先模型已更改至 '.$request->preference, 0); } } diff --git a/app/Http/Controllers/SkinlibController.php b/app/Http/Controllers/SkinlibController.php index 473d39e5..f4dd1750 100644 --- a/app/Http/Controllers/SkinlibController.php +++ b/app/Http/Controllers/SkinlibController.php @@ -2,33 +2,33 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; +use View; +use Utils; +use Option; +use Storage; +use Session; use App\Models\User; use App\Models\Texture; +use Illuminate\Http\Request; use App\Exceptions\PrettyPageException; -use Validate; -use Option; -use Utils; -use View; -use Http; -class SkinlibController extends BaseController +class SkinlibController extends Controller { private $user = null; - function __construct() + public function __construct() { - $this->user = session()->has('uid') ? new User(session('uid')) : null; + $this->user = Session::has('uid') ? new User(session('uid')) : null; } - public function index() + public function index(Request $request) { - $filter = isset($_GET['filter']) ? $_GET['filter'] : "skin"; - $sort = isset($_GET['sort']) ? $_GET['sort'] : "time"; - $sort_by = ($sort == "time") ? "upload_at" : $sort; - $uid = isset($_GET['uid']) ? $_GET['uid'] : 0; + $filter = $request->input('filter', 'skin'); + $sort = $request->input('sort', 'time'); + $uid = $request->input('uid', 0); + $page = $request->input('page', 1); - $page = isset($_GET['page']) ? $_GET['page'] : 1; + $sort_by = ($sort == "time") ? "upload_at" : $sort; if ($filter == "skin") { $textures = Texture::where(function($query) { @@ -55,28 +55,26 @@ class SkinlibController extends BaseController $textures = $textures->skip(($page - 1) * 20)->take(20)->get(); - echo View::make('skinlib.index')->with('user', $this->user) - ->with('sort', $sort) - ->with('filter', $filter) - ->with('textures', $textures) - ->with('page', $page) - ->with('total_pages', $total_pages) - ->render(); + return view('skinlib.index')->with('user', $this->user) + ->with('sort', $sort) + ->with('filter', $filter) + ->with('textures', $textures) + ->with('page', $page) + ->with('total_pages', $total_pages); } - public function search() + public function search(Request $request) { - $q = isset($_GET['q']) ? $_GET['q'] : ""; + $q = $request->input('q', ''); + $filter = $request->input('filter', 'skin'); + $sort = $request->input('sort', 'time'); - $filter = isset($_GET['filter']) ? $_GET['filter'] : "skin"; - - $sort = isset($_GET['sort']) ? $_GET['sort'] : "time"; $sort_by = ($sort == "time") ? "upload_at" : $sort; if ($filter == "skin") { $textures = Texture::like('name', $q)->where(function($query) use ($q) { $query->where('public', '=', '1') - ->where('type', '=', 'steve') + ->where('type', '=', 'steve') ->orWhere('type', '=', 'alex'); })->orderBy($sort_by, 'desc')->get(); } else { @@ -86,21 +84,22 @@ class SkinlibController extends BaseController ->orderBy($sort_by, 'desc')->get(); } - echo View::make('skinlib.search')->with('user', $this->user) - ->with('sort', $sort) - ->with('filter', $filter) - ->with('q', $q) - ->with('textures', $textures)->render(); + return view('skinlib.search')->with('user', $this->user) + ->with('sort', $sort) + ->with('filter', $filter) + ->with('q', $q) + ->with('textures', $textures); } - public function show() + public function show(Request $request) { - if (!isset($_GET['tid'])) - abort(404, 'No specified tid.'); + $this->validate($request, [ + 'tid' => 'required|integer' + ]); $texture = Texture::find($_GET['tid']); - if (!$texture || $texture && !\Storage::disk('textures')->has($texture->hash)) { + if (!$texture || $texture && !Storage::disk('textures')->has($texture->hash)) { if (Option::get('auto_del_invalid_texture') == "1") { if ($texture) $texture->delete(); @@ -115,30 +114,30 @@ class SkinlibController extends BaseController abort(404, '请求的材质已经设为隐私,仅上传者和管理员可查看'); } - echo View::make('skinlib.show')->with('texture', $texture)->with('with_out_filter', true)->with('user', $this->user)->render(); + return view('skinlib.show')->with('texture', $texture)->with('with_out_filter', true)->with('user', $this->user); } public function info($tid) { - echo json_encode(Texture::find($tid)->toArray()); + View::json(Texture::find($tid)->toArray()); } public function upload() { - echo View::make('skinlib.upload')->with('user', $this->user)->with('with_out_filter', true)->render(); + return view('skinlib.upload')->with('user', $this->user)->with('with_out_filter', true); } - public function handleUpload() + public function handleUpload(Request $request) { - $this->checkUpload(isset($_POST['type']) ? $_POST['type'] : ""); + $this->checkUpload($request); $t = new Texture(); - $t->name = $_POST['name']; - $t->type = $_POST['type']; + $t->name = $request->input('name'); + $t->type = $request->input('type'); $t->likes = 1; $t->hash = Utils::upload($_FILES['file']); $t->size = ceil($_FILES['file']['size'] / 1024); - $t->public = ($_POST['public'] == 'true') ? "1" : "0"; + $t->public = ($request->input('public') == 'true') ? "1" : "0"; $t->uploader = $this->user->uid; $t->upload_at = Utils::getTimeFormatted(); @@ -168,27 +167,25 @@ class SkinlibController extends BaseController if ($this->user->closet->add($t->tid, $t->name)) { View::json([ 'errno' => 0, - 'msg' => '材质 '.$_POST['name'].' 上传成功', + 'msg' => '材质 '.$request->input('name').' 上传成功', 'tid' => $t->tid ]); } } - public function delete() + public function delete(Request $request) { - Validate::checkPost(['tid']); - - $result = Texture::find($_POST['tid']); + $result = Texture::find($request->tid); if (!$result) - View::json('Unexistent texture.', 1); + View::json('材质不存在', 1); if ($result->uploader != $this->user->uid && !$this->user->is_admin) View::json('你不是这个材质的上传者哦', 1); // check if file occupied if (Texture::where('hash', $result['hash'])->count() == 1) - \Storage::delete($result['hash']); + Storage::delete($result['hash']); $this->user->setScore($result->size * Option::get('score_per_storage'), 'plus'); @@ -196,11 +193,12 @@ class SkinlibController extends BaseController View::json('材质已被成功删除', 0); } - public function privacy($tid) + public function privacy($tid, Request $request) { - $t = Texture::find($tid); + $t = Texture::find($request->tid); - if (!$t) View::json('Unexistent texture.', 1); + if (!$t) + View::json('材质不存在', 1); if ($t->uploader != $this->user->uid && !$this->user->is_admin) View::json('你不是这个材质的上传者哦', 1); @@ -214,62 +212,58 @@ class SkinlibController extends BaseController } } - public function rename() { - Validate::checkPost(['tid', 'new_name']); - Validate::textureName($_POST['new_name']); + public function rename(Request $request) { + $this->validate($request, [ + 'tid' => 'required|integer', + 'new_name' => 'required|no_special_chars' + ]); - $t = Texture::find($_POST['tid']); + $t = Texture::find($request->input('tid')); - if (!$t) View::json('材质不存在', 1); + if (!$t) + View::json('材质不存在', 1); if ($t->uploader != $this->user->uid && !$this->user->is_admin) View::json('你不是这个材质的上传者哦', 1); - $t->name = $_POST['new_name']; + $t->name = $request->input('new_name'); if ($t->save()) { - View::json('材质名称已被成功设置为'.$_POST['new_name'], 0); + View::json('材质名称已被成功设置为'.$request->input('new_name'), 0); } } - private function checkUpload($type) + /** + * Check Uploaded Files + * + * @param Request $request + * @return void + */ + private function checkUpload(Request $request) { - Validate::textureName(Utils::getValue('name', $_POST)); + $this->validate($request, [ + 'name' => 'required|no_special_chars', + 'file' => 'required|mimes:png|max:10240', + 'public' => 'required' + ]); - if (!Utils::getValue('file', $_FILES)) - View::json('你还没有选择任何文件哟', 1); + // if error occured while uploading file + if ($_FILES['file']["error"] > 0) + View::json($_FILES['file']["error"], 1); - if (!isset($_POST['public']) || ($_POST['public'] != 0 && $_POST['public'] != 1)) - View::json('非法参数', 1); - - if ($_FILES['file']['type'] == "image/png" || $_FILES['file']['type'] == "image/x-png") - { - // if error occured while uploading file - if ($_FILES['file']["error"] > 0) - View::json($_FILES['file']["error"], 1); - - $size = getimagesize($_FILES['file']["tmp_name"]); - $ratio = $size[0] / $size[1]; - - if ($type == "steve" || $type == "alex") { - if ($ratio != 2 && $ratio != 1) - View::json("不是有效的皮肤文件(宽 {$size[0]},高 {$size[1]})", 1); - } elseif ($type == "cape") { - if ($ratio != 2) - View::json("不是有效的披风文件(宽 {$size[0]},高 {$size[1]})", 1); - } else { - View::json('非法参数', 1); - } + $type = $request->input('type'); + $size = getimagesize($_FILES['file']["tmp_name"]); + $ratio = $size[0] / $size[1]; + if ($type == "steve" || $type == "alex") { + if ($ratio != 2 && $ratio != 1) + View::json("不是有效的皮肤文件(宽 {$size[0]},高 {$size[1]})", 1); + } elseif ($type == "cape") { + if ($ratio != 2) + View::json("不是有效的披风文件(宽 {$size[0]},高 {$size[1]})", 1); } else { - if (Utils::getValue('file', $_FILES)) { - View::json('文件格式不对哦', 1); - } else { - View::json('No file selected.', 1); - } + View::json('非法参数', 1); } - - return true; } } diff --git a/app/Http/Controllers/TextureController.php b/app/Http/Controllers/TextureController.php index 6c612a14..3b9748bb 100644 --- a/app/Http/Controllers/TextureController.php +++ b/app/Http/Controllers/TextureController.php @@ -2,23 +2,28 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; -use App\Exceptions\PrettyPageException; -use App\Events\GetAvatarPreview; -use App\Events\GetSkinPreview; -use App\Models\Texture; -use App\Models\Player; -use App\Models\User; -use Minecraft; -use Response; -use Storage; -use Option; use Event; -use Http; +use Option; +use Storage; +use Response; +use Minecraft; +use App\Models\User; +use App\Models\Player; +use App\Models\Texture; +use Illuminate\Http\Request; +use App\Events\GetSkinPreview; +use App\Events\GetAvatarPreview; +use App\Exceptions\PrettyPageException; -class TextureController extends BaseController +class TextureController extends Controller { - + /** + * Return Player Profile formatted in JSON. + * + * @param string $player_name + * @param string $api + * @return \Illuminate\Http\Response + */ public function json($player_name, $api = "") { $player = new Player(0, $player_name); @@ -27,16 +32,11 @@ class TextureController extends BaseController abort(404, '该角色拥有者已被本站封禁。'); if ($api == "csl") { - return response($player->getJsonProfile(Player::CSL_API)) - ->header('Content-type', 'application/json'); + return Response::rawJson($player->getJsonProfile(Player::CSL_API)); } else if ($api == "usm") { - return response($player->getJsonProfile(Player::USM_API)) - ->header('Content-type', 'application/json'); - } else if ($api == "") { - return response($player->getJsonProfile(Option::get('api_type'))) - ->header('Content-type', 'application/json'); + return Response::rawJson($player->getJsonProfile(Player::USM_API)); } else { - abort(404, '不支持的 API_TYPE。'); + return Response::rawJson($player->getJsonProfile(Option::get('api_type'))); } } @@ -47,8 +47,7 @@ class TextureController extends BaseController public function texture($hash) { if (Storage::disk('textures')->has($hash)) { - return response(Storage::disk('textures')->get($hash)) - ->header('Content-Type', 'image/png'); + return Response::png(Storage::disk('textures')->get($hash)); } else { abort(404); } @@ -60,8 +59,6 @@ class TextureController extends BaseController public function skin($player_name, $model = "") { - $player_name = Option::get('allow_chinese_playername') ? $GLOBALS['player_name'] : $player_name; - $player = new Player(0, $player_name); if ($player->is_banned) @@ -70,21 +67,25 @@ class TextureController extends BaseController if (!$this->checkCache($player_name)) { $model_preference = ($player->getPreference() == "default") ? "steve" : "alex"; $model = ($model == "") ? $model_preference : $model; + return $player->getBinaryTexture($model); } } + public function skinWithModel($model, $player_name) + { + return $this->skin($player_name, $model); + } + public function cape($player_name) { - $player_name = Option::get('allow_chinese_playername') ? $GLOBALS['player_name'] : $player_name; - $player = new Player(0, $player_name); if ($player->is_banned) abort(404, '该角色拥有者已被本站封禁。'); if (!$this->checkCache($player_name)) { - echo $player->getBinaryTexture('cape'); + return $player->getBinaryTexture('cape'); } } @@ -104,7 +105,7 @@ class TextureController extends BaseController } else { $filename = BASE_DIR."/storage/textures/{$t->hash}"; - $png = \Minecraft::generateAvatarFromSkin($filename, $size); + $png = Minecraft::generateAvatarFromSkin($filename, $size); imagepng($png); imagedestroy($png); @@ -140,11 +141,11 @@ class TextureController extends BaseController $filename = BASE_DIR."/storage/textures/{$t->hash}"; if ($t->type == "cape") { - $png = \Minecraft::generatePreviewFromCape($filename, $size); + $png = Minecraft::generatePreviewFromCape($filename, $size); imagepng($png); imagedestroy($png); } else { - $png = \Minecraft::generatePreviewFromSkin($filename, $size); + $png = Minecraft::generatePreviewFromSkin($filename, $size); imagepng($png); imagedestroy($png); } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 793dd11d..a79911be 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -2,19 +2,19 @@ namespace App\Http\Controllers; -use Illuminate\Routing\Controller as BaseController; +use View; +use Utils; use App\Models\User; use App\Models\Texture; +use Illuminate\Http\Request; use App\Exceptions\PrettyPageException; -use Utils; -use View; -class UserController extends BaseController +class UserController extends Controller { private $action = ""; private $user = null; - function __construct() + public function __construct() { $this->action = isset($_GET['action']) ? $_GET['action'] : ""; $this->user = new User(session('uid')); @@ -22,15 +22,20 @@ class UserController extends BaseController public function index() { - return View::make('user.index')->with('user', $this->user)->render(); + return view('user.index')->with('user', $this->user); } + /** + * Handle User Signing + * + * @return void + */ public function sign() { if ($aquired_score = $this->user->sign()) { View::json([ 'errno' => 0, - 'msg' => '签到成功,获得了 '.$aquired_score.' 积分~', + 'msg' => "签到成功,获得了 $aquired_score 积分~", 'score' => $this->user->getScore(), 'remaining_time' => $this->user->canSign(true) ]); @@ -41,82 +46,108 @@ class UserController extends BaseController public function profile() { - return View::make('user.profile')->with('user', $this->user); + return view('user.profile')->with('user', $this->user); } - public function handleProfile() + /** + * Handle Changing Profile + * + * @param Request $request + * @return void + */ + public function handleProfile(Request $request) { - // handle changing nickname - if ($this->action == "nickname") { - if (!isset($_POST['new_nickname'])) View::json('非法参数', 1); + switch ($this->action) { + case 'nickname': + $this->validate($request, [ + 'new_nickname' => 'required|nickname|max:255' + ]); - if (Utils::convertString($_POST['new_nickname']) != $_POST['new_nickname']) - View::json('无效的昵称。昵称中包含了奇怪的字符。', 1); + $nickname = $request->input('new_nickname'); - if ($this->user->setNickName($_POST['new_nickname'])) - View::json('昵称已成功设置为 '.$_POST['new_nickname'], 0); - // handle changing password - } elseif ($this->action == "password") { - if (!(isset($_POST['current_password']) && isset($_POST['new_password']))) - View::json('非法参数', 1); + if ($this->user->setNickName($nickname)) + View::json("昵称已成功设置为 $nickname", 0); - if (!$this->user->checkPasswd($_POST['current_password'])) - View::json('原密码错误', 1); + break; - if (\Validate::password($_POST['new_password'])) { - if ($this->user->changePasswd($_POST['new_password'])) + case 'password': + $this->validate($request, [ + 'current_password' => 'required|min:8|max:16', + 'new_password' => 'required|min:8|max:16' + ]); + + if (!$this->user->checkPasswd($request->input('current_password'))) + View::json('原密码错误', 1); + + if ($this->user->changePasswd($request->input('new_password'))) View::json('密码修改成功,请重新登录', 0); - } - // handle changing email - } elseif ($this->action == "email") { - if (!(isset($_POST['new_email']) && isset($_POST['password']))) + + break; + + case 'email': + $this->validate($request, [ + 'new_email' => 'required|email', + 'password' => 'required|min:8|max:16' + ]); + + if (!$this->user->checkPasswd($request->input('password'))) + View::json('密码错误', 1); + + if ($this->user->setEmail($request->input('new_email'))) + View::json('邮箱修改成功,请重新登录', 0); + + break; + + case 'delete': + $this->validate($request, [ + 'password' => 'required|min:8|max:16' + ]); + + if (!$this->user->checkPasswd($request->input('password'))) + View::json('密码错误', 1); + + if ($this->user->delete()) { + setcookie('uid', '', time() - 3600, '/'); + setcookie('token', '', time() - 3600, '/'); + + Session::flush(); + Session::save(); + + View::json('账号已被成功删除', 0); + } + + break; + + default: View::json('非法参数', 1); - - if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) { - View::json('邮箱格式错误', 3); - } - - if (!$this->user->checkPasswd($_POST['password'])) - View::json('密码错误', 1); - - if ($this->user->setEmail($_POST['new_email'])) - View::json('邮箱修改成功,请重新登录', 0); - - // handle deleting account - } elseif ($this->action == "delete") { - if (!isset($_POST['password'])) - View::json('非法参数', 1); - - if (!$this->user->checkPasswd($_POST['password'])) - View::json('密码错误', 1); - - if ($this->user->delete()) { - setcookie('uid', '', time() - 3600, '/'); - setcookie('token', '', time() - 3600, '/'); - Session::flush(); - Session::save(); - - View::json('账号已被成功删除', 0); - } + break; } } public function config() { - return View::make('user.config')->with('user', $this->user); + return view('user.config')->with('user', $this->user); } - public function setAvatar() + /** + * Set Avatar for User + * + * @param Request $request + */ + public function setAvatar(Request $request) { - if (!isset($_POST['tid'])) - View::json('Empty tid.', 1); + $this->validate($request, [ + 'tid' => 'required|integer' + ]); + + $result = Texture::find($request->input('tid')); - $result = Texture::find($_POST['tid']); if ($result) { - if ($result->type == "cape") View::json('披风可不能设置为头像哦~', 1); + if ($result->type == "cape") + View::json('披风可不能设置为头像哦~', 1); - if ((new User(session('uid')))->setAvatar($_POST['tid'])) { + if ($this->user->setAvatar($request->input('tid'))) { View::json('设置成功!', 0); } } else { diff --git a/app/Http/Middleware/CheckAuthenticated.php b/app/Http/Middleware/CheckAuthenticated.php index f804b983..ec4d56c9 100644 --- a/app/Http/Middleware/CheckAuthenticated.php +++ b/app/Http/Middleware/CheckAuthenticated.php @@ -32,10 +32,10 @@ class CheckAuthenticated // ask for filling email if ($user->email == "") { - if (isset($_POST['email'])) { - if (\Validate::email($_POST['email'])) { - if (UserModel::where('email', $_POST['email'])->get()->isEmpty()) { - $user->setEmail($_POST['email']); + if (isset($request->email)) { + if (filter_var($request->email, FILTER_VALIDATE_EMAIL)) { + if (UserModel::where('email', $request->email)->get()->isEmpty()) { + $user->setEmail($request->email); // refresh token Session::put('token', $user->getToken(true)); setcookie('token', session('token'), time() + 3600, '/'); diff --git a/app/Http/routes.php b/app/Http/routes.php index c89e4b7b..a543a534 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -118,6 +118,7 @@ Route::group(['middleware' => 'App\Http\Middleware\CheckPlayer Route::get('/{api}/{player_name}.json', 'TextureController@jsonWithApi')->where('api', 'usm|csl'); // Legacy links Route::get('/skin/{player_name}.png', 'TextureController@skin'); + Route::get('/skin/{model}/{pname}.png', 'TextureController@skinWithModel'); Route::get('/cape/{player_name}.png', 'TextureController@cape'); }); diff --git a/app/Models/Player.php b/app/Models/Player.php index 8582372b..08554a4b 100644 --- a/app/Models/Player.php +++ b/app/Models/Player.php @@ -2,21 +2,29 @@ namespace App\Models; -use App\Exceptions\PrettyPageException; -use App\Events\PlayerProfileUpdated; -use App\Events\GetPlayerJson; +use View; use Event; use Utils; -use View; +use App\Events\GetPlayerJson; +use App\Events\PlayerWasDeleted; +use App\Events\PlayerProfileUpdated; +use App\Exceptions\PrettyPageException; class Player { - public $pid = ""; - public $player_name = ""; + public $pid; + public $player_name; - public $is_banned = false; + public $is_banned = false; - public $model = null; + public $model; + + /** + * User Instance. + * + * @var \App\Models\User + */ + private $owner; const CSL_API = 0; const USM_API = 1; @@ -44,7 +52,9 @@ class Player $this->player_name = $this->model->player_name; - if ((new User($this->model->uid))->getPermission() == "-1") + $this->owner = new User($this->model->uid); + + if ($this->owner->getPermission() == "-1") $this->is_banned = true; } @@ -113,7 +123,8 @@ class Player * Set preferred model * @param string $type, 'slim' or 'default' */ - public function setPreference($type) { + public function setPreference($type) + { $this->model->update([ 'preference' => $type, 'last_modified' => Utils::getTimeFormatted() @@ -122,7 +133,8 @@ class Player return Event::fire(new PlayerProfileUpdated($this)); } - public function getPreference() { + public function getPreference() + { return $this->model['preference']; } @@ -150,7 +162,8 @@ class Player * @param int $api_type Which API to use, 0 for CustomSkinAPI, 1 for UniSkinAPI * @return string User profile in json format */ - public function getJsonProfile($api_type) { + public function getJsonProfile($api_type) + { // Support both CustomSkinLoader API & UniSkinAPI if ($api_type == self::CSL_API || $api_type == self::USM_API) { $responses = Event::fire(new GetPlayerJson($this, $api_type)); @@ -194,7 +207,8 @@ class Player return json_encode($json, JSON_PRETTY_PRINT); } - public function updateLastModified() { + public function updateLastModified() + { // @see http://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql $this->model->update(['last_modified' => Utils::getTimeFormatted()]); return Event::fire(new PlayerProfileUpdated($this)); @@ -204,9 +218,17 @@ class Player * Get last modified time * @return timestamp */ - public function getLastModified() { + public function getLastModified() + { return strtotime($this->model['last_modified']); } + + public function delete() + { + // Event::fire(new PlayerWasDeleted($this)); + + return $this->model->delete(); + } } class PlayerModel extends \Illuminate\Database\Eloquent\Model diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 9a50b5df..dec9c2e5 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -25,6 +25,26 @@ class AppServiceProvider extends ServiceProvider Validator::extend('nickname', function($attribute, $value, $parameters, $validator) { return $value == addslashes(trim($value)); }); + + Validator::extend('no_special_chars', function($attribute, $value, $parameters, $validator) { + return $value == addslashes(trim($value)); + }); + + Validator::extend('playername', function($attribute, $value, $parameters, $validator) { + return preg_match("/^([A-Za-z0-9_]+)$/", $value); + }); + + Validator::extend('pname_chinese', function($attribute, $value, $parameters, $validator) { + return preg_match("/^([A-Za-z0-9\x{4e00}-\x{9fa5}_]+)$/u", $value); + }); + + Validator::extend('preference', function($attribute, $value, $parameters, $validator) { + return preg_match("/^(default|slim)$/", $value); + }); + + Validator::extend('model', function($attribute, $value, $parameters, $validator) { + return preg_match("/^(steve|alex|cape)$/", $value); + }); } /** diff --git a/app/Providers/ResponseMacroServiceProvider.php b/app/Providers/ResponseMacroServiceProvider.php index 2963f4e0..623e38cf 100644 --- a/app/Providers/ResponseMacroServiceProvider.php +++ b/app/Providers/ResponseMacroServiceProvider.php @@ -22,6 +22,10 @@ class ResponseMacroServiceProvider extends ServiceProvider 'Content-type' => 'image/png', ], $header)); }); + + Response::macro('rawJson', function ($src = "", $status = 200, $header = []) { + return Response::make($src)->header('Content-type', 'application/json'); + }); } /** diff --git a/app/Services/Validate.php b/app/Services/Validate.php deleted file mode 100644 index 53287215..00000000 --- a/app/Services/Validate.php +++ /dev/null @@ -1,65 +0,0 @@ - 32 || strlen($texture_name) < 1) { - View::json('无效的材质名称。材质名长度应该小于 32。', 2); - } else if (Utils::convertString($texture_name) != $texture_name) { - View::json('无效的材质名称。材质名称中包含了奇怪的字符。', 2); - } - return true; - } - - public static function password($password, $silent = false) - { - if (strlen($password) > 16 || strlen($password) < 8) { - if ($silent) return false; - View::json('无效的密码。密码长度应该大于 8 并小于 16。', 2); - } else if (Utils::convertString($password) != $password) { - if ($silent) return false; - View::json('无效的密码。密码中包含了奇怪的字符。', 2); - } - return true; - } -} diff --git a/setup/bootstrap.php b/setup/bootstrap.php index fa95f7d8..e9f4b7a9 100644 --- a/setup/bootstrap.php +++ b/setup/bootstrap.php @@ -99,3 +99,26 @@ function redirect_to($url, $msg = "") { } exit; } + +/** + * Check POST values in a simple way + * + * @param array $keys + * @return void + */ +function check_post(Array $keys) { + foreach ($keys as $key) { + if (!isset($_POST[$key])) { + return false; + } + } + return true; +} + +function check_password($password) +{ + if (strlen($password) > 16 || strlen($password) < 8) { + return false; + } + return true; +} diff --git a/setup/index.php b/setup/index.php index dcaa1d34..5a8f1808 100644 --- a/setup/index.php +++ b/setup/index.php @@ -28,28 +28,28 @@ switch ($step) { case 3: // check post - if (Validate::checkPost(['email', 'password', 'confirm-pwd'], true)) + if (check_post(['email', 'password', 'confirm-pwd'], true)) { if ($_POST['password'] != $_POST['confirm-pwd']) - Http::redirect('index.php?step=2', '确认密码不一致'); + redirect_to('index.php?step=2', '确认密码不一致'); $email = $_POST['email']; $password = $_POST['password']; $sitename = isset($_POST['sitename']) ? $_POST['sitename'] : "Blessing Skin Server"; - if (Validate::email($email)) { - if (!Validate::password($password, true)) { - Http::redirect('index.php?step=2', '无效的密码。密码长度应该大于 8 并小于 16。'); + if (filter_var($email, FILTER_VALIDATE_EMAIL)) { + if (!check_password($password)) { + redirect_to('index.php?step=2', '无效的密码。密码长度应该大于 8 并小于 16。'); } else if (Utils::convertString($password) != $password) { - Http::redirect('index.php?step=2', '无效的密码。密码中包含了奇怪的字符。'); + redirect_to('index.php?step=2', '无效的密码。密码中包含了奇怪的字符。'); } } else { - Http::redirect('index.php?step=2', '邮箱格式不正确。'); + redirect_to('index.php?step=2', '邮箱格式不正确。'); } } else { - Http::redirect('index.php?step=2', '表单信息不完整。'); + redirect_to('index.php?step=2', '表单信息不完整。'); } // create tables