diff --git a/.env.example b/.env.example
index 2298d148c..c8a06baa0 100644
--- a/.env.example
+++ b/.env.example
@@ -3,15 +3,20 @@ APP_DISPLAY_NAME="NJUPT Online Judge" #Display Name
APP_ENV=local #Current Environment Name
APP_KEY=base64:6KvSj1hj/VJCNXnHECU16OVbcHk7h20O5TbsyOz5WuA= #App Key
APP_DEBUG=true #Debug Mode
-APP_URL=http://ojsystem.com/
+APP_URL=http://ojsystem.com
+APP_MULTI_DOMAIN=true # Multi Domain Mode, Automatic match APP_URL, note that you still need to set APP_URL for console command proper running
APP_LOCALE=en
APP_BACKUP=false #Enable Scheduling Backup
APP_LOGO="" #URL for site logo
APP_DESC=
+APP_THEME="default" # choose from https://njuptaaa.github.io/docs/#/noj/guide/theme
+APP_ALLOW_OAUTH_TEMP_ACCOUNT=false
+
+FUNC_ENABLE_REGISTER=true
BABEL_MIRROR=https://acm.njupt.edu.cn/babel #The mirror of babel marketplace
-SESSION_DOMAIN=.ojsystem.com
+SESSION_DOMAIN=.ojsystem.com # set null if multi-domain or http 419
LOG_CHANNEL=stack
@@ -52,12 +57,25 @@ BAIDU_SITE_VERIFICATION=""
GOOGLE_ANALYTICS=""
+GITHUB_ENABLE=false
GITHUB_KEY=
GITHUB_SECRET=
-GITHUB_CALLBACK_URL=
+GITHUB_CALLBACK_URL= # should be like http://www.your-noj-website.com/oauth/github/callback
-MOSS_USERID=
+AAUTH_ENABLE=false
+AAUTH_KEY=
+AAUTH_SECRET=
+AAUTH_CALLBACK_URL= # should be like http://www.your-noj-website.com/oauth/aauth/callback
CONTACT_EMAIL="noj@njupt.edu.cn"
CONTACT_QQ="Group 668108264"
CONTACT_TEL=
+
+TERM_SUBJECT_FULL_NAME="NJUPT Online Judge"
+TERM_SUBJECT_NAME="NOJ"
+TERM_STREET="9 Wenyuan Road"
+TERM_CITY="Nanjing"
+TERM_PROVINCE="Jiangsu"
+TERM_STATE="China"
+TERM_ZIP="221000"
+TERM_CONTACT_EMAIL="noj@njupt.edu.cn"
diff --git a/app/Admin/Controllers/AbuseController.php b/app/Admin/Controllers/AbuseController.php
index ea66d8e4d..13e53dd74 100644
--- a/app/Admin/Controllers/AbuseController.php
+++ b/app/Admin/Controllers/AbuseController.php
@@ -2,7 +2,6 @@
namespace App\Admin\Controllers;
-use App\User;
use App\Models\Eloquent\Abuse;
use App\Models\Eloquent\Group;
use App\Models\Eloquent\GroupBanned;
@@ -23,7 +22,7 @@ class AbuseController extends AdminController
*
* @var string
*/
- protected $title = 'Abuses';
+ protected $title='Abuses';
/**
* Make a grid builder.
@@ -32,7 +31,7 @@ class AbuseController extends AdminController
*/
protected function grid()
{
- $grid = new Grid(new Abuse);
+ $grid=new Grid(new Abuse);
$grid->column('id', __('Id'));
$grid->column('title', __('Title'));
@@ -58,7 +57,7 @@ protected function grid()
*/
protected function detail($id)
{
- $show = new Show(Abuse::findOrFail($id));
+ $show=new Show(Abuse::findOrFail($id));
$show->field('id', __('Id'));
$show->field('title', __('Title'));
@@ -81,7 +80,7 @@ protected function detail($id)
*/
protected function form()
{
- $form = new Form(new Abuse);
+ $form=new Form(new Abuse);
$form->text('title', __('Title'));
$form->number('cause', __('Cause'));
@@ -92,23 +91,23 @@ protected function form()
$form->ignore(['created_at']);
- $form->saving(function (Form $form) {
- $abuse = $form->model();
+ $form->saving(function(Form $form) {
+ $abuse=$form->model();
//get gategory and subject id
- $regex = '/^([A-Za-z]+) #(\d+)/';
- $matches = [];
- preg_match($regex,$abuse->title,$matches);
- $category = array_search(strtolower($matches[1]),Abuse::$supportCategory);
- $subject_id = (int)$matches[2];
- switch($abuse->category) {
+ $regex='/^([A-Za-z]+) #(\d+)/';
+ $matches=[];
+ preg_match($regex, $abuse->title, $matches);
+ $category=array_search(strtolower($matches[1]), Abuse::$supportCategory);
+ $subject_id=(int) $matches[2];
+ switch ($abuse->category) {
case 0:
- $gid = $subject_id;
- $group = Group::find($gid);
- if(empty($group)) {
- return ;
+ $gid=$subject_id;
+ $group=Group::find($gid);
+ if (empty($group)) {
+ return;
}
- if($form->audit) {
- $ban_time = request()->created_at;
+ if ($form->audit) {
+ $ban_time=request()->created_at;
sendMessage([
'sender' => 1,
'receiver' => $abuse->user_id,
@@ -128,8 +127,8 @@ protected function form()
'reason' => $abuse->supplement,
'removed_at' => $ban_time
]);
- return ;
- }else{
+ return;
+ } else {
sendMessage([
'sender' => 1,
'receiver' => $abuse->user_id,
@@ -137,11 +136,11 @@ protected function form()
'content' => "Hi, Dear **{$abuse->user->name}**,\n\n We have checked your Abuse report about group **[{$group->name}]({$group->link})**.\n\n However, we regret to say that the information you submitted is not sufficient for us to take action.\n\n Of course, we will continue to follow up the investigation.\n\n Thank you for your contribution to our community environment.\n\n Sincerely, NOJ"
]);
$abuse->delete();
- return ;
+ return;
}
return;
case 1:
- $ban_time = request()->created_at;
+ $ban_time=request()->created_at;
UserBanned::create([
'abuse_id' => $abuse->id,
'user_id' => $subject_id,
@@ -170,15 +169,15 @@ public function edit($id, Content $content)
protected function check_form()
{
- $form = new Form(new Abuse);
- $form->display('id',__('Abuse id'));
+ $form=new Form(new Abuse);
+ $form->display('id', __('Abuse id'));
$form->display('title', __('Title'));
$form->display('cause', __('Cause'));
$form->display('supplement', __('Supplement'));
$form->display('link', __('Group Link'));
$form->display('user_id', __('Submitter'));
- $form->radio('audit','result')->options(['0' => 'Reject', '1'=> 'Pass']);
- $form->datetime('created_at','ban until');
+ $form->radio('audit', 'result')->options(['0' => 'Reject', '1'=> 'Pass']);
+ $form->datetime('created_at', 'ban until');
return $form;
}
diff --git a/app/Admin/Controllers/AnnouncementController.php b/app/Admin/Controllers/AnnouncementController.php
new file mode 100644
index 000000000..2f6200d8e
--- /dev/null
+++ b/app/Admin/Controllers/AnnouncementController.php
@@ -0,0 +1,135 @@
+header(__('admin.announcements.index.header'))
+ ->description(__('admin.announcements.index.description'))
+ ->body($this->grid()->render());
+ }
+
+ /**
+ * Show interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function show($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.announcements.show.header'))
+ ->description(__('admin.announcements.show.description'))
+ ->body($this->detail($id));
+ }
+
+ /**
+ * Edit interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function edit($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.announcements.edit.header'))
+ ->description(__('admin.announcements.edit.description'))
+ ->body($this->form()->edit($id));
+ }
+
+ /**
+ * Create interface.
+ *
+ * @param Content $content
+ * @return Content
+ */
+ public function create(Content $content)
+ {
+ return $content
+ ->header(__('admin.announcements.create.header'))
+ ->description(__('admin.announcements.create.description'))
+ ->body($this->form());
+ }
+
+ /**
+ * Make a grid builder.
+ *
+ * @return Grid
+ */
+ protected function grid()
+ {
+ $grid=new Grid(new Announcement());
+
+ $grid->column('anid', 'ANID');
+ $grid->column('user', __('admin.announcements.user'))->display(function() {
+ return $this->user->name;
+ }); ;
+ $grid->column('title', __('admin.announcements.title'))->editable();
+ $grid->column('created_at', __('admin.created_at'));
+ $grid->column('updated_at', __('admin.updated_at'));
+
+ $grid->filter(function(Grid\Filter $filter) {
+ $filter->like('title', __('admin.announcements.title'));
+ $filter->equal('uid', __('admin.announcements.user'))->select(User::all()->pluck('name', 'id'));
+ });
+
+ return $grid;
+ }
+
+ /**
+ * Make a show builder.
+ *
+ * @param mixed $id
+ * @return Show
+ */
+ protected function detail($id)
+ {
+ $show=new Show(Announcement::findOrFail($id));
+
+ $show->field('anid', 'ANID');
+ $show->field('user.name', __('admin.announcements.user'));
+ $show->field('title', __('admin.announcements.title'));
+ $show->field('content', __('admin.announcements.content'));
+ $show->field('created_at', __('admin.created_at'));
+ $show->field('updated_at', __('admin.updated_at'));
+
+ return $show;
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $form=new Form(new Announcement());
+ $form->text('title', __('admin.announcements.title'))->required();
+ $form->simplemde('content', __('admin.announcements.content'))->help(__('admin.announcements.help.markdown'))->required();
+ $form->select('uid', __('admin.announcements.user'))->options(User::all()->pluck('name', 'id'))->required();
+ return $form;
+ }
+}
diff --git a/app/Admin/Controllers/BabelController.php b/app/Admin/Controllers/BabelController.php
index c5b248a2f..9f5304857 100644
--- a/app/Admin/Controllers/BabelController.php
+++ b/app/Admin/Controllers/BabelController.php
@@ -132,7 +132,7 @@ private static function marketspaceView()
{
$extensionList=ExtensionModel::list();
- if(empty($extensionList)){
+ if (empty($extensionList)) {
return view('admin::babel.empty');
}
@@ -145,7 +145,7 @@ private static function marketspaceDetailView($code)
{
$details=ExtensionModel::remoteDetail($code);
- if(empty($details)){
+ if (empty($details)) {
return view('admin::babel.empty');
}
@@ -158,7 +158,7 @@ private static function executingView($extension)
{
$details=ExtensionModel::remoteDetail($extension);
- if(empty($details)){
+ if (empty($details)) {
return view('admin::babel.empty');
}
@@ -169,15 +169,15 @@ private static function executingView($extension)
private static function executeArtisan($command)
{
- $fp = popen('php "'.base_path('artisan').'" '.$command, "r");
- while($b = fgets($fp, 2048)) {
+ $fp=popen('php "'.base_path('artisan').'" '.$command, "r");
+ while ($b=fgets($fp, 2048)) {
echo str_pad(json_encode([
"ret"=>200,
"desc"=>"Succeed",
"data"=>[
"message"=>$b
]
- ])."\n",4096);
+ ])."\n", 4096);
@ob_flush();
flush();
}
diff --git a/app/Admin/Controllers/CodeTesterController.php b/app/Admin/Controllers/CodeTesterController.php
new file mode 100644
index 000000000..7e6813507
--- /dev/null
+++ b/app/Admin/Controllers/CodeTesterController.php
@@ -0,0 +1,111 @@
+header(__('admin.tester.tester.header'));
+ $content=$content->description(__('admin.tester.tester.description'));
+ if (request()->isMethod('post')) {
+ $content=$content->body($this->run());
+ }
+ return $content->body($this->form());
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $OJ=OJ::where(["ocode"=>"noj"])->get();
+ $box=new Box(__('admin.tester.tester.title'));
+ if (blank($OJ)) {
+ $box->style('danger');
+ $box->content(__('admin.tester.help.installfirst'));
+ return $box;
+ }
+ $oid=$OJ->first()->oid;
+ $box->style('success');
+ $form=new Form();
+ $form->select('oid', __('admin.tester.oj'))->options($OJ->pluck('name', 'oid'))->help(__('admin.tester.help.onlinejudge'))->rules('required');
+ $form->select('pid', __('admin.tester.pid'))->options(Problem::where(["OJ"=>$oid])->get()->sortBy('readable_name')->pluck('readable_name', 'pid'))->rules('required');
+ $form->select('coid', __('admin.tester.coid'))->options(Compiler::where(["oid"=>$oid])->get()->pluck('display_name', 'coid'))->rules('required');
+ $form->textarea('solution', __('admin.tester.solution'))->rows(20)->rules('required');
+ $form->action(route('admin.codetester.tester'));
+ $form->fill([
+ 'oid'=>request()->oid,
+ 'pid'=>request()->pid,
+ 'coid'=>request()->coid,
+ 'solution'=>request()->solution,
+ ]);
+ $form->method('POST');
+ $box->content($form);
+ return $box;
+ }
+
+ /**
+ * Running Test.
+ *
+ * @return Response
+ */
+ protected function run()
+ {
+ $babel=new Babel();
+ request()->validate([
+ 'oid' => 'required|integer',
+ 'pid' => 'required|integer',
+ 'coid' => 'required|integer',
+ 'solution' => 'required',
+ ]);
+ $runner=$babel->testrun([
+ 'name' => 'noj',
+ 'pid' => request()->pid,
+ 'coid' => request()->coid,
+ 'solution' => request()->solution,
+ ]);
+ $verdict=$runner->verdict;
+ $boxRun=new Box(__('admin.tester.tester.run'));
+ $boxRun->style('info');
+ $verdictData=[];
+ foreach ($verdict['data'] as $v) {
+ $verdictData[]=[
+ $v["test_case"],
+ $v["cpu_time"],
+ $v["real_time"],
+ $v["memory"],
+ $v["signal"],
+ $v["exit_code"],
+ $v["error"],
+ $v["result"],
+ ];
+ }
+ $table=new Table(['Test Case', 'CPU Time(ms)', 'Real Time(ms)', 'Memory(byte)', 'Signal', 'Exit Code', 'Error', 'Result'], $verdictData);
+ $output="
Verdict: {$verdict['verdict']}
";
+ if (!blank($verdict['compile_info'])) {
+ $output.="Compiler Info:
".htmlspecialchars($verdict['compile_info'])."
";
+ }
+ $output.=$table->render();
+ $boxRun->content($output);
+ return $boxRun;
+ }
+}
diff --git a/app/Admin/Controllers/ContestController.php b/app/Admin/Controllers/ContestController.php
index 835a0f198..6f848ef1f 100644
--- a/app/Admin/Controllers/ContestController.php
+++ b/app/Admin/Controllers/ContestController.php
@@ -2,8 +2,10 @@
namespace App\Admin\Controllers;
-use App\Models\ContestModel;
-use App\Models\Eloquent\Contest as EloquentContestModel;
+use App\Models\Eloquent\Contest;
+use App\Models\Eloquent\Problem;
+use App\Models\Eloquent\Group;
+use App\Models\Eloquent\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
@@ -80,7 +82,7 @@ public function create(Content $content)
*/
protected function grid()
{
- $grid=new Grid(new EloquentContestModel);
+ $grid=new Grid(new Contest);
$grid->column('cid', "ID")->sortable();
$grid->column("gid", "Group");
$grid->name("Name")->editable();
@@ -121,7 +123,7 @@ protected function grid()
*/
protected function detail($id)
{
- $show=new Show(EloquentContestModel::findOrFail($id));
+ $show=new Show(Contest::findOrFail($id));
return $show;
}
@@ -132,12 +134,81 @@ protected function detail($id)
*/
protected function form()
{
- $form=new Form(new EloquentContestModel);
- $form->model()->makeVisible('password');
+ $form=new Form(new Contest);
$form->tab('Basic', function(Form $form) {
- $form->display('cid');
- // $form->number('gid')->rules('required');
- $form->text('name')->rules('required');
+ $form->select('gid', 'Contest Creator Group')->options(Group::all()->pluck('name', 'gid'))->required();
+ $form->select('assign_uid', 'Contest Assign User')->options(User::all()->pluck('name', 'id'))->required();
+ $form->text('name', 'Contest Name')->required();
+
+ $form->divider();
+
+ $form->select('public', 'Contest Publicity')->options([
+ 0 => "Private",
+ 1 => "Public"
+ ])->when(0, function(Form $form) {
+ $form->switch('practice', 'Practice Contest')->default(false);
+
+ $form->hidden('verified', 'Verified Contest')->default(0);
+ $form->hidden('rated', 'Rated Contest')->default(0);
+ $form->hidden('anticheated', 'AntiCheated Contest')->default(0);
+ $form->hidden('featured', 'Featured Contest')->default(0);
+ })->when(1, function(Form $form) {
+ $form->hidden('practice', 'Practice Contest')->default(0);
+
+ $form->switch('verified', 'Verified Contest')->default(true);
+ $form->switch('rated', 'Rated Contest')->default(false);
+ $form->switch('anticheated', 'AntiCheated Contest')->default(true);
+ $form->switch('featured', 'Featured Contest')->default(true);
+ })->default(0)->required();
+ $form->switch('desktop', 'Enable NOJ Desktop (Experimental)')->default(false);
+ $form->hidden('is_rated', "is_rated")->default(0);
+ $form->hidden('pdf', 'Provide PDF')->default(0);
+
+ $form->divider();
+
+ $form->simplemde('description', 'Contest Description')->required();
+ $form->select('rule', 'Contest Rule')->options([
+ 1 => "ICPC",
+ 2 => "IOI"
+ ])->default(0)->required();
+ $form->datetimeRange('begin_time', 'end_time', 'Contest Time Arrangement')->required();
+
+ $form->divider();
+
+ $form->select('registration', 'Require Registration')->options([
+ 0 => "No",
+ 1 => "Yes"
+ ])->default(0)->required();
+ $form->datetime('registration_due', 'Registration Deadline')->default('1970-01-01 00:00:00');
+ $form->select('registant_type', 'Registrant Type')->options([
+ 0 => "Everyone Can Register",
+ 1 => "Only Same Group Can Register",
+ 2 => "Don't Allow Anyone to Register"
+ ])->default(2);
+
+ $form->divider();
+
+ $form->number('froze_length', 'Forzen Time (Seconds)')->default(0)->required();
+ $form->select('status_visibility', 'Status Visibility')->options([
+ 0 => "Cannot View Any Status",
+ 1 => "Can Only View Own Status",
+ 2 => "Can View Everyone Status"
+ ])->default(1)->required();
+ $form->switch('audit_status', 'Audit Status')->default(true);
+ $form->text('custom_title', 'Custom Navigation Title');
+ $form->image('custom_icon', 'Custom Navigation Icon')->uniqueName()->move("static/img/contest");
+ $form->image('img', 'Contest Focus Image')->uniqueName()->move("static/img/contest");
+ $form->hasMany('problems', 'Contest Problems', function(Form\NestedForm $form) {
+ $form->number('number', 'Problem Numerical Index')->default(1)->required();
+ $ncodeArr=[];
+ foreach (range('A', 'Z') as $alpha) {
+ $ncodeArr[$alpha]=$alpha;
+ }
+ $form->select('ncode', 'Problem Alphabetical Index')->options($ncodeArr)->default("A")->required();
+ $form->select('pid', 'Problem')->options(Problem::all()->pluck('readable_name', 'pid'))->required();
+ $form->text('alias', 'Problem Alias Title');
+ $form->number('points', 'Points Value')->default(100)->required();
+ });
});
return $form;
}
diff --git a/app/Admin/Controllers/DashboardController.php b/app/Admin/Controllers/DashboardController.php
index babd944ae..def2cd064 100644
--- a/app/Admin/Controllers/DashboardController.php
+++ b/app/Admin/Controllers/DashboardController.php
@@ -3,6 +3,8 @@
namespace App\Admin\Controllers;
use App\Models\Update\UpdateModel;
+use Illuminate\Support\Arr;
+use PharIo\Version\Version;
class DashboardController
{
@@ -13,15 +15,15 @@ public static function general()
{
$version=UpdateModel::checkUpdate();
- $status = [
- ['name' => 'NOJ Version', 'value' => version()],
- ['name' => 'Lastest Version', 'value' => is_null($version)?'Failed to fetch latest version':$version["name"]],
- ['name' => 'Problems', 'value' => \App\Models\Eloquent\Problem::count()],
- ['name' => 'Solutions', 'value' => \App\Models\Eloquent\ProblemSolutionModel::count()],
- ['name' => 'Submissions', 'value' => \App\Models\Eloquent\Submission::count()],
- ['name' => 'Contests', 'value' => \App\Models\Eloquent\Contest::count()],
- ['name' => 'Users', 'value' => \App\Models\Eloquent\UserModel::count()],
- ['name' => 'Groups', 'value' => \App\Models\Eloquent\Group::count()],
+ $status=[
+ ['name' => __("admin.home.version"), 'value' => version()],
+ ['name' => __("admin.home.latest"), 'value' => is_null($version) ? 'Failed to fetch latest version' : $version["name"]],
+ ['name' => __("admin.home.problems"), 'value' => \App\Models\Eloquent\Problem::count()],
+ ['name' => __("admin.home.solutions"), 'value' => \App\Models\Eloquent\ProblemSolution::count()],
+ ['name' => __("admin.home.submissions"), 'value' => \App\Models\Eloquent\Submission::count()],
+ ['name' => __("admin.home.contests"), 'value' => \App\Models\Eloquent\Contest::count()],
+ ['name' => __("admin.home.users"), 'value' => \App\Models\Eloquent\User::count()],
+ ['name' => __("admin.home.groups"), 'value' => \App\Models\Eloquent\Group::count()],
];
return view('admin::dashboard.general', [
@@ -29,4 +31,74 @@ public static function general()
'version'=>$version
]);
}
+
+ /**
+ * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+ */
+ public static function environment()
+ {
+ $envs=[
+ ['name' => __('admin.home.envs.php'), 'value' => 'PHP/'.PHP_VERSION],
+ ['name' => __('admin.home.envs.laravel'), 'value' => app()->version()],
+ ['name' => __('admin.home.envs.cgi'), 'value' => php_sapi_name()],
+ ['name' => __('admin.home.envs.uname'), 'value' => php_uname()],
+ ['name' => __('admin.home.envs.server'), 'value' => Arr::get($_SERVER, 'SERVER_SOFTWARE')],
+
+ ['name' => __('admin.home.envs.cache'), 'value' => config('cache.default')],
+ ['name' => __('admin.home.envs.session'), 'value' => config('session.driver')],
+ ['name' => __('admin.home.envs.queue'), 'value' => config('queue.default')],
+
+ ['name' => __('admin.home.envs.timezone'), 'value' => config('app.timezone')],
+ ['name' => __('admin.home.envs.locale'), 'value' => config('app.locale')],
+ ['name' => __('admin.home.envs.env'), 'value' => config('app.env')],
+ ['name' => __('admin.home.envs.url'), 'value' => config('app.url')],
+
+ ['name' => __('admin.home.envs.tlsv13'), 'value' => ["Not Supported", "Supported"][in_array("tlsv1.3", stream_get_transports())]],
+ ];
+
+ foreach ($envs as &$env) {
+ $env['icon']="check-circle";
+ $env['color']="wemd-teal-text";
+ }
+
+ // PHP Version Check
+ $installedVersion=new Version(PHP_VERSION);
+ $requireVersion=new Version("7.4.0");
+ if (!($installedVersion->isGreaterThan($requireVersion) || $installedVersion->getVersionString()===$requireVersion->getVersionString())) {
+ $envs[0]['icon']="close-circle";
+ $envs[0]['color']="wemd-pink-text";
+ }
+
+ // Cache Driver Check
+ if (config('cache.default')!="redis") {
+ $envs[5]['icon']="close-circle";
+ $envs[5]['color']="wemd-pink-text";
+ }
+
+ // Session Driver Check
+ if (config('session.driver')!="redis") {
+ $envs[6]['icon']="close-circle";
+ $envs[6]['color']="wemd-pink-text";
+ }
+
+ // Queue Driver Check
+ if (config('queue.default')!="database") {
+ $envs[7]['icon']="close-circle";
+ $envs[7]['color']="wemd-pink-text";
+ }
+
+ // Locale Check
+ if (!in_array(strtolower(config('app.locale')), ['en', 'zh-cn'])) {
+ $envs[9]['icon']="close-circle";
+ $envs[9]['color']="wemd-pink-text";
+ }
+
+ // TLSv1.3 Check
+ if ($envs[12]['value']=="Not Supported") {
+ $envs[12]['icon']="close-circle";
+ $envs[12]['color']="wemd-pink-text";
+ }
+
+ return view('admin::dashboard.environment', compact('envs'));
+ }
}
diff --git a/app/Admin/Controllers/DojoController.php b/app/Admin/Controllers/DojoController.php
new file mode 100644
index 000000000..b921803b8
--- /dev/null
+++ b/app/Admin/Controllers/DojoController.php
@@ -0,0 +1,157 @@
+header(__('admin.dojos.index.header'))
+ ->description(__('admin.dojos.index.description'))
+ ->body($this->grid()->render());
+ }
+
+ /**
+ * Show interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function show($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.dojos.show.header'))
+ ->description(__('admin.dojos.show.description'))
+ ->body($this->detail($id));
+ }
+
+ /**
+ * Edit interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function edit($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.dojos.edit.header'))
+ ->description(__('admin.dojos.edit.description'))
+ ->body($this->form()->edit($id));
+ }
+
+ /**
+ * Create interface.
+ *
+ * @param Content $content
+ * @return Content
+ */
+ public function create(Content $content)
+ {
+ return $content
+ ->header(__('admin.dojos.create.header'))
+ ->description(__('admin.dojos.create.description'))
+ ->body($this->form());
+ }
+
+ /**
+ * Make a grid builder.
+ *
+ * @return Grid
+ */
+ protected function grid()
+ {
+ $grid=new Grid(new Dojo);
+ $grid->column('id', "ID")->sortable();
+ $grid->column("name", __('admin.dojos.name'))->editable();
+ $grid->column("dojo_phase", __('admin.dojos.phase'))->display(function() {
+ return $this->phase->name;
+ });
+ $grid->column("totproblem", __('admin.dojos.totproblem'))->display(function() {
+ return $this->tot_problem;
+ });
+ $grid->column("passline", __('admin.dojos.passline'));
+ $grid->column("precondition", __('admin.dojos.precondition'))->display(function($precondition) {
+ $output='';
+ foreach ($precondition as $p) {
+ $output.=''.Dojo::find($p)->name.' ';
+ }
+ return $output;
+ });
+ $grid->column("order", __('admin.dojos.order'))->sortable();
+ $grid->created_at(__('admin.created_at'));
+ $grid->updated_at(__('admin.updated_at'));
+
+ $grid->filter(function(Grid\Filter $filter) {
+ $filter->column(6, function($filter) {
+ $filter->like('name', __('admin.dojos.name'));
+ });
+ $filter->column(6, function($filter) {
+ $filter->equal('dojo_phase_id', __('admin.dojos.phase'))->select(DojoPhase::all()->pluck('name', 'cid'));
+ });
+ });
+ return $grid;
+ }
+
+ /**
+ * Make a show builder.
+ *
+ * @param mixed $id
+ * @return Show
+ */
+ protected function detail($id)
+ {
+ $show=new Show(Dojo::findOrFail($id));
+ $show->id('ID');
+ $show->name(__('admin.dojos.name'));
+ $show->description(__('admin.dojos.description'));
+ $show->dojo_phase_id(__('admin.dojos.phase'));
+ $show->passline(__('admin.dojos.passline'));
+ $show->order(__('admin.dojos.order'));
+ return $show;
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $form=new Form(new Dojo);
+ $form->tab('Basic', function(Form $form) {
+ $form->display('id', 'ID');
+ $form->text('name', __('admin.dojos.name'))->rules('required');
+ $form->textarea('description', __('admin.dojos.description'))->rules('required');
+ $form->select('dojo_phase_id', __('admin.dojos.phase'))->options(DojoPhase::all()->pluck('name', 'id'))->rules('required');
+ $form->number('passline', __('admin.dojos.passline'))->default(0)->rules('required');
+ $form->number('order', __('admin.dojos.order'))->default(0)->rules('required');
+ $form->multipleSelect('precondition', __('admin.dojos.precondition'))->options(Dojo::all()->pluck('name', 'id'));
+ $form->hasMany('problems', __('admin.dojos.problems'), function(Form\NestedForm $form) {
+ $form->select('problem_id', __('admin.dojos.problem'))->options(Problem::all()->pluck('readable_name', 'pid'))->required();
+ $form->number('order', __('admin.dojos.problemorder'))->default(0)->required();
+ });
+ });
+ return $form;
+ }
+}
diff --git a/app/Admin/Controllers/DojoPhaseController.php b/app/Admin/Controllers/DojoPhaseController.php
new file mode 100644
index 000000000..4bfa75bf6
--- /dev/null
+++ b/app/Admin/Controllers/DojoPhaseController.php
@@ -0,0 +1,134 @@
+header(__('admin.dojophases.index.header'))
+ ->description(__('admin.dojophases.index.description'))
+ ->body($this->grid()->render());
+ }
+
+ /**
+ * Show interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function show($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.dojophases.show.header'))
+ ->description(__('admin.dojophases.show.description'))
+ ->body($this->detail($id));
+ }
+
+ /**
+ * Edit interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function edit($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.dojophases.edit.header'))
+ ->description(__('admin.dojophases.edit.description'))
+ ->body($this->form()->edit($id));
+ }
+
+ /**
+ * Create interface.
+ *
+ * @param Content $content
+ * @return Content
+ */
+ public function create(Content $content)
+ {
+ return $content
+ ->header(__('admin.dojophases.create.header'))
+ ->description(__('admin.dojophases.create.description'))
+ ->body($this->form());
+ }
+
+ /**
+ * Make a grid builder.
+ *
+ * @return Grid
+ */
+ protected function grid()
+ {
+ $grid=new Grid(new DojoPhase);
+ $grid->column('id', "ID")->sortable();
+ $grid->column("name", __('admin.dojophases.name'))->editable();
+
+ $grid->column("passline", __('admin.dojophases.passline'));
+ $grid->column("order", __('admin.dojophases.order'))->sortable();
+ $grid->created_at(__('admin.created_at'));
+ $grid->updated_at(__('admin.updated_at'));
+
+ $grid->filter(function(Grid\Filter $filter) {
+ $filter->column(6, function($filter) {
+ $filter->like('name', __('admin.dojophases.name'));
+ });
+ });
+ return $grid;
+ }
+
+ /**
+ * Make a show builder.
+ *
+ * @param mixed $id
+ * @return Show
+ */
+ protected function detail($id)
+ {
+ $show=new Show(DojoPhase::findOrFail($id));
+ $show->id('ID');
+ $show->name(__('admin.dojophases.name'));
+ $show->description(__('admin.dojophases.description'));
+ $show->passline(__('admin.dojophases.passline'));
+ $show->order(__('admin.dojophases.order'));
+ return $show;
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $form=new Form(new DojoPhase);
+ $form->tab('Basic', function(Form $form) {
+ $form->display('id', 'ID');
+ $form->text('name', __('admin.dojophases.name'))->rules('required');
+ $form->textarea('description', __('admin.dojophases.description'))->rules('required');
+ $form->number('passline', __('admin.dojophases.passline'))->default(0)->rules('required');
+ $form->number('order', __('admin.dojophases.order'))->default(0)->rules('required');
+ });
+ return $form;
+ }
+}
diff --git a/app/Admin/Controllers/GroupController.php b/app/Admin/Controllers/GroupController.php
index 4e955bd89..a57932f98 100644
--- a/app/Admin/Controllers/GroupController.php
+++ b/app/Admin/Controllers/GroupController.php
@@ -3,12 +3,15 @@
namespace App\Admin\Controllers;
use App\Models\Eloquent\Group;
+use App\Models\Eloquent\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
+use Illuminate\Support\MessageBag;
+use App\Models\Eloquent\GroupMember;
class GroupController extends Controller
{
@@ -124,8 +127,45 @@ protected function form()
$form=new Form(new Group);
$form->model()->makeVisible('password');
$form->tab('Basic', function(Form $form) {
- $form->display('gid');
- $form->text('name')->rules('required');
+ $form->text('gcode')->rules('required|alpha_dash|min:3|max:50');
+ $form->text('name')->rules('required|min:3|max:50');
+ $form->switch('public')->default(true);
+ $form->textarea('description')->rules('nullable|max:60000');
+ $form->select('join_policy', 'Join Policy')->options([
+ 0 => "Cannot Join",
+ 1 => "Invite Only",
+ 2 => "Apply Only",
+ 3 => "Invite & Apply"
+ ])->default(1);
+ $form->image('img', 'Custom Group Focus Image')->uniqueName()->move("static/img/group");
+ if ($form->isCreating()) {
+ $form->select('leader_uid', 'Group Leader')->options(User::all()->pluck('name', 'id'))->required();
+ }
+ $form->ignore(['leader_uid']);
+ $form->saving(function(Form $form) {
+ $err=function($msg, $title='Error occur.') {
+ $error=new MessageBag([
+ 'title' => $title,
+ 'message' => $msg,
+ ]);
+ return back()->with(compact('error'));
+ };
+ $gcode=$form->gcode;
+ $g=Group::where('gcode', $gcode)->first();
+ //check gcode has been token.
+ $gid=$form->pid ?? null;
+ if (!empty($gcode) && !blank($g) && $g->gid!=$gid) {
+ $err('Gcode has been token', 'Error occur.');
+ }
+ });
+ $form->saved(function(Form $form) {
+ $form->model()->members()->saveMany([new GroupMember([
+ 'gid' => $form->model()->gid,
+ 'uid' => request('leader_uid'),
+ 'role' => 3,
+ 'ranking' => 1500,
+ ])]);
+ });
});
return $form;
}
diff --git a/app/Admin/Controllers/HomeController.php b/app/Admin/Controllers/HomeController.php
index 228233c08..618c1d5f1 100644
--- a/app/Admin/Controllers/HomeController.php
+++ b/app/Admin/Controllers/HomeController.php
@@ -13,8 +13,8 @@ class HomeController extends Controller
public function index(Content $content)
{
return $content
- ->header('Dashboard')
- ->description('the general status of '.config("app.name"))
+ ->header(__('admin.home.dashboard'))
+ ->description(__('admin.home.description'))
->row(function(Row $row) {
$row->column(4, function(Column $column) {
@@ -22,7 +22,7 @@ public function index(Content $content)
});
$row->column(4, function(Column $column) {
- $column->append(Dashboard::environment());
+ $column->append(DashboardController::environment());
});
// $row->column(4, function(Column $column) {
diff --git a/app/Admin/Controllers/JudgeServerController.php b/app/Admin/Controllers/JudgeServerController.php
new file mode 100644
index 000000000..a323be0e2
--- /dev/null
+++ b/app/Admin/Controllers/JudgeServerController.php
@@ -0,0 +1,166 @@
+header(__('admin.judgeservers.index.header'))
+ ->description(__('admin.judgeservers.index.description'))
+ ->body($this->grid()->render());
+ }
+
+ /**
+ * Show interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function show($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.judgeservers.show.header'))
+ ->description(__('admin.judgeservers.show.description'))
+ ->body($this->detail($id));
+ }
+
+ /**
+ * Edit interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function edit($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.judgeservers.edit.header'))
+ ->description(__('admin.judgeservers.edit.description'))
+ ->body($this->form()->edit($id));
+ }
+
+ /**
+ * Create interface.
+ *
+ * @param Content $content
+ * @return Content
+ */
+ public function create(Content $content)
+ {
+ return $content
+ ->header(__('admin.judgeservers.create.header'))
+ ->description(__('admin.judgeservers.create.description'))
+ ->body($this->form());
+ }
+
+ /**
+ * Make a grid builder.
+ *
+ * @return Grid
+ */
+ protected function grid()
+ {
+ $grid=new Grid(new JudgeServer());
+
+ $grid->column('jsid', 'JSID');
+ $grid->column('scode', __('admin.judgeservers.scode'));
+ $grid->column('name', __('admin.judgeservers.name'));
+ $grid->column('host', __('admin.judgeservers.host'));
+ $grid->column('port', __('admin.judgeservers.port'));
+ $grid->column('token', __('admin.judgeservers.token'));
+ $grid->column('available', __('admin.judgeservers.availability'))->display(function($available) {
+ return $available ?__('admin.judgeservers.available') : __('admin.judgeservers.unavailable');
+ });
+ $grid->column('OJ', __('admin.judgeservers.oj'))->display(function() {
+ return $this->oj->name;
+ });
+ $grid->column('usage', __('admin.judgeservers.usage'))->display(function($usage) {
+ return blank($usage) ? "-" : "$usage%";
+ });
+ $grid->column('status', __('admin.judgeservers.status'))->display(function($status) {
+ $status=JudgerModel::$status[$status];
+ return ' '.$status['text'];
+ });
+ $grid->column('status_update_at', __('admin.judgeservers.status_update_at'));
+ $grid->column('created_at', __('admin.created_at'));
+ $grid->column('updated_at', __('admin.updated_at'));
+
+ return $grid;
+ }
+
+ /**
+ * Make a show builder.
+ *
+ * @param mixed $id
+ * @return Show
+ */
+ protected function detail($id)
+ {
+ $show=new Show(JudgeServer::findOrFail($id));
+
+ $show->field('jsid', 'JSID');
+ $show->field('scode', __('admin.judgeservers.scode'));
+ $show->field('name', __('admin.judgeservers.name'));
+ $show->field('host', __('admin.judgeservers.host'));
+ $show->field('port', __('admin.judgeservers.port'));
+ $show->field('token', __('admin.judgeservers.token'));
+ $show->field('available', __('admin.judgeservers.availability'))->as(function($available) {
+ return $available ?__('admin.judgeservers.available') : __('admin.judgeservers.unavailable');
+ });
+ $show->field('oj.name', __('admin.judgeservers.oj'));
+ $show->field('usage', __('admin.judgeservers.usage'))->as(function($usage) {
+ return blank($usage) ? "-" : "$usage%";
+ });
+ $show->field('status', __('admin.judgeservers.status'))->unescape()->as(function($status) {
+ $status=JudgerModel::$status[$status];
+ return ' '.$status['text'];
+ });
+ $show->field('status_update_at', __('admin.judgeservers.status_update_at'));
+ $show->field('created_at', __('admin.created_at'));
+ $show->field('updated_at', __('admin.updated_at'));
+
+ return $show;
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $form=new Form(new JudgeServer());
+
+ $form->text('scode', __('admin.judgeservers.scode'))->required();
+ $form->text('name', __('admin.judgeservers.name'))->required();
+ $form->text('host', __('admin.judgeservers.host'))->required();
+ $form->text('port', __('admin.judgeservers.port'))->required();
+ $form->text('token', __('admin.judgeservers.token'))->required();
+ $form->switch('available', __('admin.judgeservers.availability'));
+ $form->select('oid', __('admin.judgeservers.oj'))->options(OJ::all()->pluck('name', 'oid'))->help(__('admin.judgeservers.help.onlinejudge'))->required();
+ $form->hidden('status', __('admin.judgeservers.status'))->default(0);
+ return $form;
+ }
+}
diff --git a/app/Admin/Controllers/JudgerController.php b/app/Admin/Controllers/JudgerController.php
new file mode 100644
index 000000000..35eda338d
--- /dev/null
+++ b/app/Admin/Controllers/JudgerController.php
@@ -0,0 +1,150 @@
+header(__('admin.judgers.index.header'))
+ ->description(__('admin.judgers.index.description'))
+ ->body($this->grid()->render());
+ }
+
+ /**
+ * Show interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function show($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.judgers.show.header'))
+ ->description(__('admin.judgers.show.description'))
+ ->body($this->detail($id));
+ }
+
+ /**
+ * Edit interface.
+ *
+ * @param mixed $id
+ * @param Content $content
+ * @return Content
+ */
+ public function edit($id, Content $content)
+ {
+ return $content
+ ->header(__('admin.judgers.edit.header'))
+ ->description(__('admin.judgers.edit.description'))
+ ->body($this->form()->edit($id));
+ }
+
+ /**
+ * Create interface.
+ *
+ * @param Content $content
+ * @return Content
+ */
+ public function create(Content $content)
+ {
+ return $content
+ ->header(__('admin.judgers.create.header'))
+ ->description(__('admin.judgers.create.description'))
+ ->body($this->form());
+ }
+
+ /**
+ * Make a grid builder.
+ *
+ * @return Grid
+ */
+ protected function grid()
+ {
+ $grid=new Grid(new Judger());
+
+ $grid->column('jid', 'JID');
+ $grid->column('handle', __('admin.judgers.handle'))->editable();
+ $grid->column('password', __('admin.judgers.password'))->editable();
+ $grid->column('available', __('admin.judgers.availability'))->display(function($available) {
+ return $available ? ' '.__('admin.judgers.available') : ' '.__('admin.judgers.unavailable');
+ });
+ $grid->column('oid', __('admin.judgers.oj'))->display(function() {
+ return $this->oj->name;
+ });
+ $grid->column('user_id', __('admin.judgers.user_id'))->editable();
+ $grid->column('created_at', __('admin.created_at'));
+ $grid->column('updated_at', __('admin.updated_at'));
+
+ $grid->filter(function(Grid\Filter $filter) {
+ $filter->like('handle', __('admin.judgers.handle'));
+ $filter->like('password', __('admin.judgers.password'));
+ $filter->like('user_id', __('admin.judgers.user_id'));
+ $filter->equal('oid', __('admin.judgers.oj'))->select(OJ::all()->pluck('name', 'oid'));
+ });
+
+ return $grid;
+ }
+
+ /**
+ * Make a show builder.
+ *
+ * @param mixed $id
+ * @return Show
+ */
+ protected function detail($id)
+ {
+ $show=new Show(Judger::findOrFail($id));
+
+ $show->field('jid', 'JID');
+ $show->field('handle', __('admin.judgers.handle'));
+ $show->field('password', __('admin.judgers.password'));
+ $show->field('available', __('admin.judgers.availability'))->as(function($available) {
+ return $available ?__('admin.judgers.available') : __('admin.judgers.unavailable');
+ });
+ $show->field('oj.name', __('admin.judgers.oj'));
+ $show->field('user_id', __('admin.judgers.user_id'));
+ $show->field('created_at', __('admin.created_at'));
+ $show->field('updated_at', __('admin.updated_at'));
+
+ return $show;
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $form=new Form(new Judger());
+ $form->text('handle', __('admin.judgers.handle'))->help(__('admin.judgers.help.handle'))->required();
+ $form->text('password', __('admin.judgers.password'))->help(__('admin.judgers.help.password'))->required();
+ $form->switch('available', __('admin.judgers.availability'))->default(true);
+ $form->select('oid', __('admin.judgers.oj'))->options(OJ::all()->pluck('name', 'oid'))->required();
+ $form->text('user_id', __('admin.judgers.user_id'))->help(__('admin.judgers.help.user_id'));
+ $form->hidden('using')->default(0);
+ return $form;
+ }
+}
diff --git a/app/Admin/Controllers/ProblemController.php b/app/Admin/Controllers/ProblemController.php
index a838bf84e..3a6c8a267 100644
--- a/app/Admin/Controllers/ProblemController.php
+++ b/app/Admin/Controllers/ProblemController.php
@@ -143,11 +143,11 @@ protected function detail($id)
*
* @return Form
*/
- protected function form($create = false)
+ protected function form($create=false)
{
$form=new Form(new EloquentProblemModel);
$form->model()->makeVisible('password');
- $form->tab('Basic', function(Form $form){
+ $form->tab('Basic', function(Form $form) {
$form->text('pid')->readonly();
$form->text('pcode')->rules('required');
$form->text('title')->rules('required');
@@ -157,7 +157,7 @@ protected function form($create = false)
$form->simplemde('input');
$form->simplemde('output');
$form->simplemde('note');
- $form->hasMany('problemSamples', 'samples', function (Form\NestedForm $form) {
+ $form->hasMany('problemSamples', 'samples', function(Form\NestedForm $form) {
$form->textarea('sample_input', 'sample input')->rows(3);
$form->textarea('sample_output', 'sample output')->rows(3);
$form->textarea('sample_note', 'sample note')->rows(3);
@@ -167,10 +167,10 @@ protected function form($create = false)
$table->textarea('sample_output', 'sample output');
$table->textarea('sample_note', 'sample note');
}); */
- $ojs_temp = EloquentOJModel::select('oid', 'name')->get()->all();
- $ojs = [];
- foreach($ojs_temp as $v){
- $ojs[$v->oid] = $v->name;
+ $ojs_temp=EloquentOJModel::select('oid', 'name')->get()->all();
+ $ojs=[];
+ foreach ($ojs_temp as $v) {
+ $ojs[$v->oid]=$v->name;
}
$form->select('oj', 'OJ')->options($ojs)->default(1)->rules('required');
/* $form->display('update_date'); */
@@ -189,7 +189,7 @@ protected function form($create = false)
0 => 'NO',
1 => 'YES',
])->default(0)->rules('required');
- $form->clang('spj_src','SPJ Source Code');
+ $form->clang('spj_src', 'SPJ Source Code');
$form->file('test_case')->rules('required');
$form->ignore(['test_case']);
@@ -211,125 +211,128 @@ protected function form($create = false)
$tools->append(' Import from file');
});
} */
- $form->saving(function (Form $form){
- $err = function ($msg, $title = 'Test case file parse faild.') {
- $error = new MessageBag([
+ $form->saving(function(Form $form) {
+ $err=function($msg, $title='Test case file parse faild.') {
+ $error=new MessageBag([
'title' => $title,
'message' => $msg,
]);
return back()->with(compact('error'));
};
- $pcode = $form->pcode;
- $p = EloquentProblemModel::where('pcode',$pcode)->first();
+ $pcode=$form->pcode;
+ $p=EloquentProblemModel::where('pcode', $pcode)->first();
//check pcode has been token.
- $pid = $form->pid ?? null;
- if(!empty($p) && $p->pid != $pid){
+ $pid=$form->pid ?? null;
+ if (!empty($p) && $p->pid!=$pid) {
$err('Pcode has been token', 'Error occur.');
}
- $test_case = \request()->file('test_case');
+ $test_case=\request()->file('test_case');
//Make sure the user enters SPJ_SRc in spj problem.
- if($form->spj && empty($form->spj_src)) {
+ if ($form->spj && empty($form->spj_src)) {
$err('The SPJ problem must provide spj_src', 'create problem error');
}
//check info file. Try to generate if it does not exist.
- $info_content = [];
- if(!empty($test_case)){
- if($test_case->extension() != 'zip'){
+ $info_content=[];
+ if (!empty($test_case)) {
+ if ($test_case->extension()!='zip') {
$err('You must upload a zip file iuclude test case info and content.');
}
- $path = $test_case->path();
- $zip = new ZipArchive;
- if($zip->open($path) !== true) {
+ $path=$test_case->path();
+ $zip=new ZipArchive;
+ if ($zip->open($path)!==true) {
$err('You must upload a zip file without encrypt and can open successfully.');
};
- $info_content = [];
- if(($zip->getFromName('info')) === false){
- if(!$form->spj){
- $info_content = [
+ $info_content=[];
+ if (($zip->getFromName('info'))===false) {
+ if (!$form->spj) {
+ $info_content=[
'spj' => false,
'test_cases' => []
];
- $files = [];
- for ($i = 0; $i < $zip->numFiles; $i++) {
- $filename = $zip->getNameIndex($i);
- $files[] = $filename;
+ $files=[];
+ for ($i=0; $i<$zip->numFiles; $i++) {
+ $filename=$zip->getNameIndex($i);
+ $files[]=$filename;
}
- $files_in = array_filter($files, function ($filename) {
- return strpos('.in', $filename) != -1;
+ $files_in=array_filter($files, function($filename) {
+ return strpos('.in', $filename)!=-1;
});
sort($files_in);
- $testcase_index = 1;
- foreach($files_in as $filename_in){
- $filename = basename($filename_in, '.in');
- $filename_out = $filename.'.out';
- if(($zip->getFromName($filename_out)) === false) {
+ $testcase_index=1;
+ if (!count($files_in)) {
+ $err('Cannot detect any .in file, please make sure they are placed under the root directory of the zip file.');
+ }
+ foreach ($files_in as $filename_in) {
+ $filename=basename($filename_in, '.in');
+ $filename_out=$filename.'.out';
+ if (($zip->getFromName($filename_out))===false) {
continue;
}
- $test_case_in = preg_replace('~(*BSR_ANYCRLF)\R~',"\n", $zip->getFromName($filename_in));
- $test_case_out = preg_replace('~(*BSR_ANYCRLF)\R~',"\n", $zip->getFromName($filename_out));
- $info_content['test_cases']["{$testcase_index}"] = [
+ $test_case_in=preg_replace('~(*BSR_ANYCRLF)\R~', "\n", $zip->getFromName($filename_in));
+ $test_case_out=preg_replace('~(*BSR_ANYCRLF)\R~', "\n", $zip->getFromName($filename_out));
+ $info_content['test_cases']["{$testcase_index}"]=[
'input_size' => strlen($test_case_in),
'input_name' => $filename_in,
'output_size' => strlen($test_case_out),
'output_name' => $filename_out,
'stripped_output_md5' => md5(utf8_encode(rtrim($test_case_out)))
];
- $testcase_index += 1;
+ $testcase_index+=1;
}
- }else{
- $info_content = [
+ } else {
+ $info_content=[
'spj' => true,
'test_cases' => []
];
- $files = [];
- for ($i = 0; $i < $zip->numFiles; $i++) {
- $filename = $zip->getNameIndex($i);
- $files[] = $filename;
+ $files=[];
+ for ($i=0; $i<$zip->numFiles; $i++) {
+ $filename=$zip->getNameIndex($i);
+ $files[]=$filename;
}
- $files_in = array_filter($files, function ($filename) {
- return strpos($filename, '.in') !== false;
+ $files_in=array_filter($files, function($filename) {
+ return strpos($filename, '.in')!==false;
});
sort($files_in);
- $testcase_index = 1;
- foreach($files_in as $filename_in){
- $test_case_in = $zip->getFromName($filename_in);
- $info_content['test_cases']["{$testcase_index}"] = [
+ $testcase_index=1;
+ foreach ($files_in as $filename_in) {
+ $test_case_in=$zip->getFromName($filename_in);
+ $info_content['test_cases']["{$testcase_index}"]=[
'input_size' => strlen($test_case_in),
'input_name' => $filename_in
];
- $testcase_index += 1;
+ $testcase_index+=1;
}
}
$zip->addFromString('info', json_encode($info_content));
$zip->close();
//$err('The zip files must include a file named info including info of test cases, and the format can see ZsgsDesign/NOJ wiki.');
- }else{
- $info_content = json_decode($zip->getFromName('info'),true);
+ } else {
+ $info_content=json_decode($zip->getFromName('info'), true);
};
$zip->open($path);
//If there is an INFO file, check that the contents of the file match the actual situation
- $test_cases = $info_content['test_cases'];
+ $test_cases=$info_content['test_cases'];
//dd($test_cases);
- foreach($test_cases as $index => $case) {
- if(!isset($case['input_name']) || (!$form->spj && !isset($case['output_name']))) {
+ foreach ($test_cases as $index => $case) {
+ if (!isset($case['input_name']) || (!$form->spj && !isset($case['output_name']))) {
$err("Test case index {$index}: configuration missing input/output files name.");
}
- if($zip->getFromName($case['input_name']) === false || (!$form->spj && $zip->getFromName($case['output_name']) === false)) {
+ if ($zip->getFromName($case['input_name'])===false || (!$form->spj && $zip->getFromName($case['output_name'])===false)) {
$err("Test case index {$index}: missing input/output files that record in the configuration.");
}
}
- if(!empty($form->pid)){
- $problem = EloquentProblemModel::find($form->pid);
- if(!empty($problem)){
- $pcode = $problem->pcode;
- }else{
- $pcode = $form->pcode;
+ if (!empty($form->pid)) {
+ $problem=EloquentProblemModel::find($form->pid);
+ if (!empty($problem)) {
+ $pcode=$problem->pcode;
+ } else {
+ $pcode=$form->pcode;
}
- }else{
- $pcode = $form->pcode;
+ } else {
+ $pcode=$form->pcode;
}
- if(Storage::exists(base_path().'/storage/test_case/'.$pcode)){
+ if (Storage::exists(base_path().'/storage/test_case/'.$pcode)) {
Storage::deleteDirectory(base_path().'/storage/test_case/'.$pcode);
}
Storage::makeDirectory(base_path().'/storage/test_case/'.$pcode);
@@ -337,19 +340,19 @@ protected function form($create = false)
}
//Set the spj-related data
- if($form->spj){
- $form->spj_lang = 'c';
- $form->spj_version = "{$form->pcode}#".time();
+ if ($form->spj) {
+ $form->spj_lang='c';
+ $form->spj_version="{$form->pcode}#".time();
}
//Set default data
- $form->tot_score = count($info_content['test_cases']);
- $form->markdown = true;
- $form->input_type = 'standard input';
- $form->output_type = 'standard output';
- $form->solved_count = 0;
- $form->difficulty = -1;
- $form->partial = 1;
- $form->file = 0;
+ $form->tot_score=count($info_content['test_cases']);
+ $form->markdown=true;
+ $form->input_type='standard input';
+ $form->output_type='standard output';
+ $form->solved_count=0;
+ $form->difficulty=-1;
+ $form->partial=1;
+ $form->file=0;
});
return $form;
}
diff --git a/app/Admin/Controllers/SettingsController.php b/app/Admin/Controllers/SettingsController.php
new file mode 100644
index 000000000..4f9e5b398
--- /dev/null
+++ b/app/Admin/Controllers/SettingsController.php
@@ -0,0 +1,56 @@
+header(__('admin.settings.index.header'));
+ $content=$content->description(__('admin.settings.index.description'));
+ if (request()->isMethod('post')) {
+ $this->writeSettings();
+ admin_toastr(__('admin.settings.tooltip.success.message'), 'success');
+ }
+ return $content->body($this->form());
+ }
+
+ /**
+ * Make a form builder.
+ *
+ * @return Form
+ */
+ protected function form()
+ {
+ $box=new Box(__('admin.settings.form.header'));
+ $box->style('success');
+ $form=new Form();
+ $form->simplemde('terms', __('admin.settings.form.terms'))->default(setting('terms'))->help(__('admin.settings.help.terms'));
+ $form->method('POST');
+ $form->action(route('admin.settings.index'));
+ $form->disableReset();
+ $box->content($form);
+ return $box;
+ }
+
+ protected function writeSettings()
+ {
+ setting(['terms' => request()->terms]);
+ }
+}
diff --git a/app/Admin/Controllers/SolutionController.php b/app/Admin/Controllers/SolutionController.php
index 15cc3a577..8a2849575 100644
--- a/app/Admin/Controllers/SolutionController.php
+++ b/app/Admin/Controllers/SolutionController.php
@@ -2,8 +2,9 @@
namespace App\Admin\Controllers;
-use App\Models\ProblemModel;
-use App\Models\Eloquent\SolutionModel as EloquentSolutionModel;
+use App\Models\Eloquent\Solution;
+use App\Models\Eloquent\Problem;
+use App\Models\Eloquent\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
@@ -80,7 +81,7 @@ public function create(Content $content)
*/
protected function grid()
{
- $grid=new Grid(new EloquentSolutionModel);
+ $grid=new Grid(new Solution);
$grid->psoid("ID")->sortable();
$grid->uid("Uid")->editable();
$grid->pid("Pid")->editable();
@@ -113,7 +114,7 @@ protected function grid()
*/
protected function detail($id)
{
- $show=new Show(EloquentSolutionModel::findOrFail($id));
+ $show=new Show(Solution::findOrFail($id));
return $show;
}
@@ -124,25 +125,21 @@ protected function detail($id)
*/
protected function form()
{
- $form=new Form(new EloquentSolutionModel);
+ $form=new Form(new Solution);
$form->model()->makeVisible('password');
$form->tab('Basic', function(Form $form) {
$form->display("psoid");
- $form->text("uid")->rules('required');
- $form->text("pid")->rules('required');
- $form->text("content")->rules('required');
- $form->text("audit")->rules('required');
- $form->text("votes")->rules('required');
+ $form->select('uid', 'Author')->options(User::all()->pluck('name', 'id'))->required();
+ $form->select('pid', 'Problem')->options(Problem::all()->pluck('readable_name', 'pid'))->required();
+ $form->simplemde("content")->rules('required');
+ $form->select("audit")->options([
+ '0' => 'Waiting',
+ '1' => 'Accepted',
+ '2' => 'Declined',
+ ])->default(1)->required();
+ $form->number("votes")->rules('required');
$form->display("created_at");
$form->display("updated_at");
- $form->select('partial', 'Partial Score')->options([
- 0 => "No",
- 1 => "Yes"
- ])->rules('required');
- $form->select('markdown', 'Markdown Support')->options([
- 0 => "No",
- 1 => "Yes"
- ])->rules('required');
});
return $form;
}
diff --git a/app/Admin/Controllers/SubmissionController.php b/app/Admin/Controllers/SubmissionController.php
index 2ccd5f532..95bb041ff 100644
--- a/app/Admin/Controllers/SubmissionController.php
+++ b/app/Admin/Controllers/SubmissionController.php
@@ -2,7 +2,12 @@
namespace App\Admin\Controllers;
-use App\Models\Eloquent\Submission as EloquentSubmissionModel;
+use App\Models\Eloquent\Submission;
+use App\Models\Eloquent\Contest;
+use App\Models\Eloquent\Judger;
+use App\Models\Eloquent\Compiler;
+use App\Models\Eloquent\User;
+use App\Models\Eloquent\Problem;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
@@ -23,8 +28,8 @@ class SubmissionController extends Controller
public function index(Content $content)
{
return $content
- ->header('Submissions')
- ->description('all submissions')
+ ->header(__('admin.submissions.index.header'))
+ ->description(__('admin.submissions.index.description'))
->body($this->grid()->render());
}
@@ -38,8 +43,8 @@ public function index(Content $content)
public function show($id, Content $content)
{
return $content
- ->header('Submission Detail')
- ->description('the detail of submissions')
+ ->header(__('admin.submissions.show.header'))
+ ->description(__('admin.submissions.show.description'))
->body($this->detail($id));
}
@@ -53,8 +58,8 @@ public function show($id, Content $content)
public function edit($id, Content $content)
{
return $content
- ->header('Edit Submission')
- ->description('edit the detail of submissions')
+ ->header(__('admin.submissions.edit.header'))
+ ->description(__('admin.submissions.edit.description'))
->body($this->form()->edit($id));
}
@@ -67,8 +72,8 @@ public function edit($id, Content $content)
public function create(Content $content)
{
return $content
- ->header('Create New Submission')
- ->description('create a new submission')
+ ->header(__('admin.submissions.create.header'))
+ ->description(__('admin.submissions.create.description'))
->body($this->form());
}
@@ -79,32 +84,54 @@ public function create(Content $content)
*/
protected function grid()
{
- $grid=new Grid(new EloquentSubmissionModel);
+ $grid=new Grid(new Submission);
$grid->column('sid', "ID")->sortable();
- $grid->time("Time");
- $grid->memory("Memory");
- $grid->verdict("Verdict")->display(function ($verdict) {
+ $grid->column("time", __('admin.submissions.time'))->display(function($time) {
+ return __('admin.submissions.timeFormat', ['time'=>$time]);
+ });
+ $grid->column("memory", __('admin.submissions.memory'))->display(function($memory) {
+ return __('admin.submissions.memoryFormat', ['memory'=>$memory]);
+ });
+ $grid->column('verdict', __('admin.submissions.verdict'))->display(function($verdict) {
return ' '.$verdict;
});
- $grid->language("Language");
- $grid->submission_date("Submission Date")->display(function ($submission_date) {
+ $grid->column("language", __('admin.submissions.language'));
+ $grid->column("submission_date", __('admin.submissions.submission_date'))->display(function($submission_date) {
return date("Y-m-d H:i:s", $submission_date);
});
- ;
- $grid->uid("UID");
- $grid->cid("CID");
- $grid->pid("PID");
- $grid->jid("JID");
- $grid->coid("COID");
- $grid->score("Raw Score");
- $grid->filter(function (Grid\Filter $filter) {
- $filter->column(6, function ($filter) {
- $filter->like('verdict');
+ $grid->column("user_name", __('admin.submissions.user_name'))->display(function() {
+ return $this->user->name;
+ });
+ $grid->column("contest_name", __('admin.submissions.contest_name'))->display(function() {
+ if (!is_null($this->contest)) {
+ return $this->contest->name;
+ }
+ });
+ $grid->column("readable_name", __('admin.submissions.readable_name'))->display(function() {
+ return $this->problem->readable_name;
+ });
+ $grid->column("judger_name", __('admin.submissions.judger_name'))->display(function() {
+ return $this->judger_name;
+ });
+ $grid->column("share", __('admin.submissions.share'))->editable('select', [
+ 0 => __('admin.submissions.disableshare'),
+ 1 => __('admin.submissions.enableshare')
+ ]);
+ $grid->column("parsed_score", __('admin.submissions.parsed_score'))->display(function() {
+ return $this->parsed_score;
+ });
+ $grid->filter(function(Grid\Filter $filter) {
+ $filter->column(6, function($filter) {
+ $filter->like('verdict', __('admin.submissions.verdict'));
});
- $filter->column(6, function ($filter) {
- $filter->equal('cid', 'Contest ID');
- $filter->equal('uid', 'User ID');
- $filter->equal('pid', 'Problem ID');
+ $filter->column(6, function($filter) {
+ $filter->equal('cid', __('admin.submissions.cid'))->select(Contest::all()->pluck('name', 'cid'));
+ $filter->equal('uid', __('admin.submissions.uid'))->select(User::all()->pluck('name', 'id'));
+ $filter->equal('pid', __('admin.submissions.pid'))->select(Problem::all()->pluck('readable_name', 'pid'));
+ $filter->equal('share', __('admin.submissions.share'))->select([
+ 0 => __('admin.submissions.disableshare'),
+ 1 => __('admin.submissions.enableshare')
+ ]);
});
});
return $grid;
@@ -118,34 +145,33 @@ protected function grid()
*/
protected function detail($id)
{
- $show=new Show(EloquentSubmissionModel::findOrFail($id));
+ $show=new Show(Submission::findOrFail($id));
$show->sid('SID');
- $show->time();
- $show->memory();
- $show->verdict();
- $show->color();
- $show->language();
- $show->submission_date();
- $show->remote_id();
- $this->codify($show->solution(), $show->getModel()->compiler->lang);
+ $show->time(__('admin.submissions.time'));
+ $show->memory(__('admin.submissions.memory'));
+ $show->verdict(__('admin.submissions.verdict'));
+ $show->language(__('admin.submissions.language'));
+ $show->submission_date(__('admin.submissions.submission_date'));
+ $show->remote_id(__('admin.submissions.remote_id'));
+ $this->codify($show->solution(__('admin.submissions.solution')), $show->getModel()->compiler->lang);
if (!blank($show->getModel()->compile_info)) {
$this->codify($show->compile_info());
}
- $show->uid('UID');
- $show->pid('PID');
- $show->cid('CID');
- $show->jid('JID');
- $show->coid('COID');
- $show->vcid('VCID');
- $show->score();
- $show->share()->using(['No','Yes']);
+ $show->uid(__('admin.submissions.uid'));
+ $show->pid(__('admin.submissions.pid'));
+ $show->cid(__('admin.submissions.cid'));
+ $show->jid(__('admin.submissions.jid'));
+ $show->coid(__('admin.submissions.coid'));
+ $show->vcid(__('admin.submissions.vcid'));
+ $show->score(__('admin.submissions.parsed_score'));
+ $show->share(__('admin.submissions.share'))->using([__('admin.submissions.disableshare'), __('admin.submissions.enableshare')]);
return $show;
}
private function codify($field, $lang=null)
{
- $field->unescape()->as(function ($value) use ($field,$lang) {
- $field->border = false;
+ $field->unescape()->as(function($value) use ($field, $lang) {
+ $field->border=false;
$hash=md5($value);
if (blank($value)) {
$value=" ";
@@ -184,22 +210,25 @@ private function codify($field, $lang=null)
*/
protected function form()
{
- $form=new Form(new EloquentSubmissionModel);
- $form->model()->makeVisible('password');
- $form->tab('Basic', function (Form $form) {
- $form->display('sid');
- $form->text('time')->rules('required');
- $form->text('memory')->rules('required');
- $form->text('verdict')->rules('required');
- $form->text('color')->rules('required');
- $form->text('language')->rules('required');
- $form->display('submission_date');
- $form->number('uid')->rules('required');
- $form->number('cid');
- $form->number('pid')->rules('required');
- $form->number('jid')->rules('required');
- $form->number('coid')->rules('required');
- $form->number('score')->rules('required');
+ $form=new Form(new Submission);
+ $form->tab('Basic', function(Form $form) {
+ $form->display('sid', 'SID');
+ $form->text('time', __('admin.submissions.time'))->rules('required');
+ $form->text('memory', __('admin.submissions.memory'))->rules('required');
+ $form->text('verdict', __('admin.submissions.verdict'))->rules('required');
+ $form->text('color', __('admin.submissions.color'))->rules('required');
+ $form->textarea('language', __('admin.submissions.language'))->rules('required');
+ $form->display('submission_date', __('admin.submissions.submission_date'));
+ $form->select('uid', __('admin.submissions.uid'))->options(User::all()->pluck('name', 'id'))->required();
+ $form->select('cid', __('admin.submissions.cid'))->options(Contest::all()->pluck('name', 'cid'));
+ $form->select('pid', __('admin.submissions.pid'))->options(Problem::all()->pluck('readable_name', 'pid'))->rules('required');
+ $form->select('jid', __('admin.submissions.jid'))->options(Judger::all()->pluck('readable_name', 'jid'));
+ $form->select('coid', __('admin.submissions.coid'))->options(Compiler::all()->pluck('readable_name', 'coid'))->rules('required');
+ $form->number('score', __('admin.submissions.rawscore'))->rules('required');
+ $form->select('share', __('admin.submissions.share'))->options([
+ 0 => __('admin.submissions.disableshare'),
+ 1 => __('admin.submissions.enableshare')
+ ])->default(0)->rules('required');
});
return $form;
}
diff --git a/app/Admin/Controllers/UserController.php b/app/Admin/Controllers/UserController.php
index 21a39b0ec..42137d182 100644
--- a/app/Admin/Controllers/UserController.php
+++ b/app/Admin/Controllers/UserController.php
@@ -2,8 +2,7 @@
namespace App\Admin\Controllers;
-use App\Models\UserModel;
-use App\Models\Eloquent\UserModel as EloquentUserModel;
+use App\Models\Eloquent\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
@@ -24,8 +23,8 @@ class UserController extends Controller
public function index(Content $content)
{
return $content
- ->header('Users')
- ->description('all users')
+ ->header(__('admin.users.index.header'))
+ ->description(__('admin.users.index.description'))
->body($this->grid()->render());
}
@@ -39,8 +38,8 @@ public function index(Content $content)
public function show($id, Content $content)
{
return $content
- ->header('User Detail')
- ->description('the detail of users')
+ ->header(__('admin.users.show.header'))
+ ->description(__('admin.users.show.description'))
->body($this->detail($id));
}
@@ -54,8 +53,8 @@ public function show($id, Content $content)
public function edit($id, Content $content)
{
return $content
- ->header('Edit User')
- ->description('edit the detail of users')
+ ->header(__('admin.users.edit.header'))
+ ->description(__('admin.users.edit.description'))
->body($this->form()->edit($id));
}
@@ -68,8 +67,8 @@ public function edit($id, Content $content)
public function create(Content $content)
{
return $content
- ->header('Create New User')
- ->description('create a new user')
+ ->header(__('admin.users.create.header'))
+ ->description(__('admin.users.create.description'))
->body($this->form());
}
@@ -80,16 +79,16 @@ public function create(Content $content)
*/
protected function grid()
{
- $grid=new Grid(new EloquentUserModel);
+ $grid=new Grid(new User);
$grid->id('ID')->sortable();
- $grid->name()->editable();
- $grid->email();
- $grid->created_at();
- $grid->updated_at();
+ $grid->name(__('admin.users.name'))->editable();
+ $grid->email(__('admin.users.email'));
+ $grid->created_at(__('admin.created_at'));
+ $grid->updated_at(__('admin.updated_at'));
$grid->filter(function(Grid\Filter $filter) {
$filter->disableIdFilter();
- $filter->like('name');
- $filter->like('email')->email();
+ $filter->like('name', __('admin.users.name'));
+ $filter->like('email', __('admin.users.email'))->email();
});
return $grid;
}
@@ -102,7 +101,7 @@ protected function grid()
*/
protected function detail($id)
{
- $show=new Show(EloquentUserModel::findOrFail($id));
+ $show=new Show(User::findOrFail($id));
return $show;
}
@@ -113,17 +112,21 @@ protected function detail($id)
*/
protected function form()
{
- $form=new Form(new EloquentUserModel);
+ $form=new Form(new User);
$form->model()->makeVisible('password');
- $form->tab('Basic', function(Form $form) {
- $form->display('id');
- $form->text('name')->rules('required');
- $form->email('email')->rules('required');
- $form->display('created_at');
- $form->display('updated_at');
- })->tab('Password', function(Form $form) {
- $form->password('password')->rules('confirmed');
- $form->password('password_confirmation');
+ $form->tab(__('admin.users.basic'), function(Form $form) {
+ if ($form->isEditing()) {
+ $form->display('id', 'ID');
+ }
+ $form->text('name', __('admin.users.name'))->rules('required');
+ $form->email('email', __('admin.users.email'))->rules('required');
+ if ($form->isEditing()) {
+ $form->display('created_at', __('admin.created_at'));
+ $form->display('updated_at', __('admin.updated_at'));
+ }
+ })->tab(__('admin.users.password'), function(Form $form) {
+ $form->password('password', __('admin.password'))->rules('confirmed');
+ $form->password('password_confirmation', __('admin.password_confirmation'));
});
$form->ignore(['password_confirmation']);
$form->saving(function(Form $form) {
diff --git a/app/Admin/Forms/ImportPOEM.php b/app/Admin/Forms/ImportPOEM.php
index 6c0ee0c75..acd9df97c 100644
--- a/app/Admin/Forms/ImportPOEM.php
+++ b/app/Admin/Forms/ImportPOEM.php
@@ -17,7 +17,7 @@ class ImportPOEM extends Form
*
* @var string
*/
- public $title = 'Import';
+ public $title='Import';
/**
* Handle the form request.
@@ -28,29 +28,29 @@ class ImportPOEM extends Form
*/
public function handle(Request $request)
{
- $err = function ($msg) {
- $error = new MessageBag([
+ $err=function($msg) {
+ $error=new MessageBag([
'title' => 'POEM parse failed.',
'message' => $msg,
]);
return back()->with(compact('error'));
};
- $success_message = '';
+ $success_message='';
- $file = $request->file('Files');
- if(!$file->isValid()){
+ $file=$request->file('Files');
+ if (!$file->isValid()) {
$err('Invalid POEM files');
}
- $path = $file->getRealPath();
- $poetryRaw = file_get_contents($path);
- $parser = new POEMParser();
- $poem = $parser->parse($poetryRaw);
- if(empty($poem)){
+ $path=$file->getRealPath();
+ $poetryRaw=file_get_contents($path);
+ $parser=new POEMParser();
+ $poem=$parser->parse($poetryRaw);
+ if (empty($poem)) {
$err('Malformed POEM files');
}
- $success_message .= "
+ $success_message.="
POEM standard : {$poem['standard']}
generator : {$poem['generator']}
url : {$poem['url']}
@@ -58,31 +58,31 @@ public function handle(Request $request)
problems:
";
- $memory_unit = [
+ $memory_unit=[
'kb' => 1,
'mb' => 1024,
- 'gb' => 1024*1024
+ 'gb' => 1024 * 1024
];
- $time_unit = [
+ $time_unit=[
'ms' => 1,
's' => 1000,
'm' => 60000,
'h' => 3600000
];
- $prefix = 'NOJ';
- $p = ProblemModel::where('pcode','like',$prefix.'%')->orderBy('pcode','desc')->select('pcode')->first();
- if(empty($p)){
- $count = 1000;
- }else{
- $count = (int) str_replace($prefix,'',$p['pcode']);
+ $prefix='NOJ';
+ $p=ProblemModel::where('pcode', 'like', $prefix.'%')->orderBy('pcode', 'desc')->select('pcode')->first();
+ if (empty($p)) {
+ $count=1000;
+ } else {
+ $count=(int) str_replace($prefix, '', $p['pcode']);
}
foreach ($poem['problems'] as $problem) {
//insert problem
- $title = $problem['title'];
- $pro = [
- 'pcode' => $prefix . (++$count),
+ $title=$problem['title'];
+ $pro=[
+ 'pcode' => $prefix.(++$count),
'solved_count' => 0,
'difficulty' => -1,
'file' => 0,
@@ -101,49 +101,49 @@ public function handle(Request $request)
'force_raw' => $problem['extra']['forceRaw'],
'partial' => $problem['extra']['partial']
];
- $pid = ProblemModel::insertGetId($pro);
+ $pid=ProblemModel::insertGetId($pro);
//migrate sample
- $sample_count = 0;
- foreach($problem['sample'] as $sample){
- $sam = [
+ $sample_count=0;
+ foreach ($problem['sample'] as $sample) {
+ $sam=[
'pid' => $pid,
'sample_input' => $sample['input'],
'sample_output' => $sample['output'],
];
- $psid = DB::table('problem_sample')->insert($sam);
- $sample_count += 1;
+ $psid=DB::table('problem_sample')->insert($sam);
+ $sample_count+=1;
}
//create test case file
- if(Storage::exists(storage_path().'/test_case/'.$pro['pcode'])){
+ if (Storage::exists(storage_path().'/test_case/'.$pro['pcode'])) {
Storage::deleteDirectory(storage_path().'/test_case/'.$pro['pcode']);
}
Storage::makeDirectory(storage_path().'/test_case/'.$pro['pcode']);
- $test_case_count = 0;
- $test_case_info = [
+ $test_case_count=0;
+ $test_case_info=[
'spj' => false,
'test_cases' => []
];
- foreach($problem['testCases'] as $test_case){
- $test_case_count += 1;
- $test_case_arr = [
+ foreach ($problem['testCases'] as $test_case) {
+ $test_case_count+=1;
+ $test_case_arr=[
'input_name' => "data{$test_case_count}.in",
'output_name' => "data{$test_case_count}.out",
'input_size' => strlen($test_case['input']),
'output_size' => strlen($test_case['output']),
'stripped_output_md5' => md5(trim($test_case['output']))
];
- array_push($test_case_info['test_cases'],$test_case_arr);
+ array_push($test_case_info['test_cases'], $test_case_arr);
Storage::disk('test_case')->put('/'.$pro['pcode'].'/'.$test_case_arr['input_name'], $test_case['input']);
Storage::disk('test_case')->put('/'.$pro['pcode'].'/'.$test_case_arr['output_name'], $test_case['output']);
}
Storage::disk('test_case')->put('/'.$pro['pcode'].'/info', json_encode($test_case_info));
//migrate solutions
- $solution_count = 0;
- foreach($problem['solution'] as $solution) {
- $s = [
+ $solution_count=0;
+ foreach ($problem['solution'] as $solution) {
+ $s=[
'uid' => 1,
'pid' => $pid,
'content' => '``` '.$solution['source'],
@@ -152,10 +152,10 @@ public function handle(Request $request)
'created_at' => date('Y-m-d H:i:s')
];
DB::table('problem_solution')->insert($s);
- $solution_count += 1;
+ $solution_count+=1;
}
- $success_message .= ' '.
+ $success_message.=' '.
$pro['pcode'].': "
'.$title.'" with
'.$sample_count.' samples,
@@ -163,7 +163,7 @@ public function handle(Request $request)
'.$solution_count.' solutions
';
}
- admin_success('Import successfully',$success_message);
+ admin_success('Import successfully', $success_message);
return back();
}
diff --git a/app/Admin/menu.json b/app/Admin/menu.json
index e370fae60..0bb4c1c28 100644
--- a/app/Admin/menu.json
+++ b/app/Admin/menu.json
@@ -3,7 +3,7 @@
"id": 1,
"parent_id": 0,
"order": 1,
- "title": "Index",
+ "title": "admin.menu_titles.dashboard",
"icon": "MDI view-dashboard",
"uri": "\/",
"permission": null,
@@ -15,7 +15,7 @@
"id": 2,
"parent_id": 0,
"order": 2,
- "title": "Admin",
+ "title": "admin.menu_titles.adminCatg",
"icon": "MDI clipboard-check",
"uri": "",
"permission": null,
@@ -27,7 +27,7 @@
"id": 3,
"parent_id": 2,
"order": 3,
- "title": "Users",
+ "title": "admin.menu_titles.users",
"icon": "MDI account-settings-variant",
"uri": "auth\/users",
"permission": null,
@@ -39,7 +39,7 @@
"id": 15,
"parent_id": 2,
"order": 15,
- "title": "Abuses",
+ "title": "admin.menu_titles.abuses",
"icon": "MDI alert-circle-outline",
"uri": "\/abuses",
"permission": null,
@@ -53,7 +53,7 @@
"id": 8,
"parent_id": 0,
"order": 8,
- "title": "Users",
+ "title": "admin.menu_titles.users",
"icon": "MDI account",
"uri": "\/users",
"permission": null,
@@ -61,11 +61,23 @@
"updated_at": "2019-04-10 17:01:18",
"roles": []
},
+ {
+ "id": 33,
+ "parent_id": 0,
+ "order": 8,
+ "title": "admin.menu_titles.announcements",
+ "icon": "MDI newspaper",
+ "uri": "\/announcements",
+ "permission": null,
+ "created_at": "2019-04-10 16:45:06",
+ "updated_at": "2019-04-10 17:01:18",
+ "roles": []
+ },
{
"id": 9,
"parent_id": 0,
"order": 9,
- "title": "Problems",
+ "title": "admin.menu_titles.problemsCatg",
"icon": "MDI book-multiple",
"uri": "",
"permission": null,
@@ -77,7 +89,7 @@
"id": 9,
"parent_id": 0,
"order": 9,
- "title": "Problems",
+ "title": "admin.menu_titles.problems",
"icon": "MDI apple-keyboard-command",
"uri": "\/problems",
"permission": null,
@@ -89,7 +101,7 @@
"id": 27,
"parent_id": 0,
"order": 27,
- "title": "Solutions",
+ "title": "admin.menu_titles.solutions",
"icon": "MDI comment-check-outline",
"uri": "\/solutions?audit=0&per_page=30",
"permission": null,
@@ -103,7 +115,7 @@
"id": 10,
"parent_id": 0,
"order": 10,
- "title": "Submissions",
+ "title": "admin.menu_titles.submissions",
"icon": "MDI bookmark-outline",
"uri": "\/submissions",
"permission": null,
@@ -115,7 +127,7 @@
"id": 11,
"parent_id": 0,
"order": 11,
- "title": "Contests",
+ "title": "admin.menu_titles.contests",
"icon": "MDI trophy-variant",
"uri": "\/contests",
"permission": null,
@@ -127,7 +139,7 @@
"id": 12,
"parent_id": 0,
"order": 12,
- "title": "Groups",
+ "title": "admin.menu_titles.groups",
"icon": "MDI account-multiple",
"uri": "\/groups",
"permission": null,
@@ -135,11 +147,85 @@
"updated_at": "2019-04-10 17:01:18",
"roles": []
},
+ {
+ "id": 28,
+ "parent_id": 0,
+ "order": 12,
+ "title": "admin.menu_titles.dojoCatg",
+ "icon": "MDI coffee",
+ "uri": "",
+ "permission": null,
+ "created_at": "2019-04-10 17:00:09",
+ "updated_at": "2019-04-10 17:01:18",
+ "roles": [],
+ "children": [
+ {
+ "id": 31,
+ "parent_id": 28,
+ "order": 31,
+ "title": "admin.menu_titles.dojos",
+ "icon": "MDI coffee-outline",
+ "uri": "dojos",
+ "permission": null,
+ "created_at": "2019-04-11 12:53:03",
+ "updated_at": "2019-04-12 09:30:12",
+ "roles": []
+ },
+ {
+ "id": 32,
+ "parent_id": 28,
+ "order": 32,
+ "title": "admin.menu_titles.dojophases",
+ "icon": "MDI coffee-to-go",
+ "uri": "dojophases",
+ "permission": null,
+ "created_at": "2019-04-11 12:53:03",
+ "updated_at": "2019-04-12 09:30:12",
+ "roles": []
+ }
+ ]
+ },
+ {
+ "id": 29,
+ "parent_id": 0,
+ "order": 12,
+ "title": "admin.menu_titles.judgeserver",
+ "icon": "MDI server-network",
+ "uri": "\/judge-server",
+ "permission": null,
+ "created_at": "2019-04-10 17:00:09",
+ "updated_at": "2019-04-10 17:01:18",
+ "roles": []
+ },
+ {
+ "id": 30,
+ "parent_id": 0,
+ "order": 12,
+ "title": "admin.menu_titles.judger",
+ "icon": "MDI web",
+ "uri": "\/judger",
+ "permission": null,
+ "created_at": "2019-04-10 17:00:09",
+ "updated_at": "2019-04-10 17:01:18",
+ "roles": []
+ },
+ {
+ "id": 34,
+ "parent_id": 0,
+ "order": 12,
+ "title": "admin.menu_titles.tester",
+ "icon": "MDI test-tube",
+ "uri": "\/codetester",
+ "permission": null,
+ "created_at": "2019-04-10 17:00:09",
+ "updated_at": "2019-04-10 17:01:18",
+ "roles": []
+ },
{
"id": 13,
"parent_id": 0,
"order": 13,
- "title": "Helpers",
+ "title": "admin.menu_titles.helpers",
"icon": "MDI settings-box",
"uri": "",
"permission": null,
@@ -151,7 +237,7 @@
"id": 14,
"parent_id": 13,
"order": 14,
- "title": "Scaffold",
+ "title": "admin.menu_titles.scaffold",
"icon": "MDI keyboard",
"uri": "helpers\/scaffold",
"permission": null,
@@ -163,7 +249,7 @@
"id": 15,
"parent_id": 13,
"order": 15,
- "title": "Database terminal",
+ "title": "admin.menu_titles.database",
"icon": "MDI database",
"uri": "helpers\/terminal\/database",
"permission": null,
@@ -175,7 +261,7 @@
"id": 16,
"parent_id": 13,
"order": 16,
- "title": "Laravel artisan",
+ "title": "admin.menu_titles.artisan",
"icon": "MDI code-tags",
"uri": "helpers\/terminal\/artisan",
"permission": null,
@@ -187,7 +273,7 @@
"id": 17,
"parent_id": 13,
"order": 17,
- "title": "Routes",
+ "title": "admin.menu_titles.routes",
"icon": "MDI view-list",
"uri": "helpers\/routes",
"permission": null,
@@ -201,7 +287,7 @@
"id": 18,
"parent_id": 0,
"order": 18,
- "title": "Log viewer",
+ "title": "admin.menu_titles.logs",
"icon": "MDI alert-circle",
"uri": "logs",
"permission": null,
@@ -213,7 +299,7 @@
"id": 20,
"parent_id": 0,
"order": 20,
- "title": "Media manager",
+ "title": "admin.menu_titles.media",
"icon": "MDI file",
"uri": "media",
"permission": null,
@@ -225,7 +311,7 @@
"id": 21,
"parent_id": 0,
"order": 21,
- "title": "Scheduling",
+ "title": "admin.menu_titles.scheduling",
"icon": "MDI clock",
"uri": "scheduling",
"permission": null,
@@ -237,7 +323,7 @@
"id": 22,
"parent_id": 0,
"order": 22,
- "title": "Backup",
+ "title": "admin.menu_titles.backup",
"icon": "MDI backup-restore",
"uri": "backup",
"permission": null,
@@ -249,7 +335,7 @@
"id": 23,
"parent_id": 0,
"order": 23,
- "title": "Redis Manager",
+ "title": "admin.menu_titles.redis",
"icon": "MDI database",
"uri": "redis",
"permission": null,
@@ -261,7 +347,7 @@
"id": 24,
"parent_id": 0,
"order": 24,
- "title": "Babel Extension",
+ "title": "admin.menu_titles.babelCatg",
"icon": "MDI cube-outline",
"uri": "babel",
"permission": null,
@@ -273,7 +359,7 @@
"id": 25,
"parent_id": 24,
"order": 25,
- "title": "Extension Manager",
+ "title": "admin.menu_titles.babelinstalled",
"icon": "MDI cube-send",
"uri": "babel\/installed",
"permission": null,
@@ -285,7 +371,7 @@
"id": 26,
"parent_id": 24,
"order": 26,
- "title": "Babel Marketspace",
+ "title": "admin.menu_titles.babelmarketspace",
"icon": "MDI store",
"uri": "babel\/marketspace",
"permission": null,
@@ -294,5 +380,17 @@
"roles": []
}
]
+ },
+ {
+ "id": 35,
+ "parent_id": 0,
+ "order": 27,
+ "title": "admin.menu_titles.settings",
+ "icon": "MDI settings",
+ "uri": "settings",
+ "permission": null,
+ "created_at": "2019-04-22 13:13:45",
+ "updated_at": "2019-04-22 13:13:45",
+ "roles": []
}
]
diff --git a/app/Admin/routes.php b/app/Admin/routes.php
index 555c18138..725d266ac 100644
--- a/app/Admin/routes.php
+++ b/app/Admin/routes.php
@@ -10,17 +10,25 @@
'middleware' => config('admin.route.middleware'),
], function(Router $router) {
- $router->get('/', 'HomeController@index');
+ $router->get('/', 'HomeController@index')->name('admin.index');
$router->resource('users', UserController::class);
+ $router->resource('announcements', AnnouncementController::class);
$router->get('problems/import', 'ProblemController@import');
$router->resource('problems', ProblemController::class);
$router->resource('solutions', SolutionController::class);
$router->resource('submissions', SubmissionController::class);
$router->resource('contests', ContestController::class);
$router->resource('groups', GroupController::class);
+ $router->resource('dojos', DojoController::class);
+ $router->resource('dojophases', DojoPhaseController::class);
+ $router->resource('judge-server', JudgeServerController::class);
+ $router->resource('judger', JudgerController::class);
$router->resource('abuses', AbuseController::class);
- Route::group(['prefix' => 'babel'], function (Router $router) {
+ Route::match(['GET', 'POST'], 'codetester', 'CodeTesterController@tester')->name('admin.codetester.tester');
+ Route::match(['GET', 'POST'], 'settings', 'SettingsController@index')->name('admin.settings.index');
+
+ Route::group(['prefix' => 'babel'], function(Router $router) {
$router->get('/', 'BabelController@index')->name('admin.babel.index');
$router->get('installed', 'BabelController@installed')->name('admin.babel.installed');
$router->get('marketspace', 'BabelController@marketspace')->name('admin.babel.marketspace');
diff --git a/app/Babel/Babel.php b/app/Babel/Babel.php
index a49ace487..67f6aec23 100644
--- a/app/Babel/Babel.php
+++ b/app/Babel/Babel.php
@@ -6,6 +6,7 @@
use App\Babel\Judge\Judger;
use App\Babel\Synchronize\Synchronizer;
use App\Babel\Monit\Monitor;
+use App\Babel\TestRun\TestRunner;
class Babel
{
@@ -33,4 +34,9 @@ public function monitor($conf)
{
return new Monitor($conf);
}
+
+ public function testrun($conf)
+ {
+ return new TestRunner($conf);
+ }
}
diff --git a/app/Babel/Crawl/Crawler.php b/app/Babel/Crawl/Crawler.php
index 5dfcd65e3..df0038af5 100644
--- a/app/Babel/Crawl/Crawler.php
+++ b/app/Babel/Crawl/Crawler.php
@@ -32,7 +32,7 @@ public static function create($conf, $commandLineObject=null)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$name\\$crawlerProvider";
+ $className="App\\Babel\\Extension\\$name\\$crawlerProvider";
if (class_exists($className)) {
$temp=new $className();
$temp->importCommandLine($commandLineObject);
diff --git a/app/Babel/Crawl/CrawlerBase.php b/app/Babel/Crawl/CrawlerBase.php
index b8d782c44..0a39b7bca 100644
--- a/app/Babel/Crawl/CrawlerBase.php
+++ b/app/Babel/Crawl/CrawlerBase.php
@@ -90,11 +90,11 @@ private function _cacheImage($data)
if (!isset($data["ori"]) || !isset($data["path"]) || !isset($data["baseurl"]) || !isset($data["space_deli"]) || !isset($data["cookie"])) {
throw new Exception("data is not completely exist in cacheImage");
}
- $ori = $data["ori"];
- $path = $data["path"];
- $baseurl = $data["baseurl"];
- $space_deli = $data["space_deli"];
- $cookie = $data["cookie"];
+ $ori=$data["ori"];
+ $path=$data["path"];
+ $baseurl=$data["baseurl"];
+ $space_deli=$data["space_deli"];
+ $cookie=$data["cookie"];
$para["path"]=$path;
$para["base"]=$baseurl;
@@ -107,7 +107,7 @@ private function _cacheImage($data)
$reg="/< *im[a]?g[^>]*src *= *[\"\\']?([^\"\\'>]*)[^>]*>/si";
}
- return preg_replace_callback($reg, function ($matches) use ($para) {
+ return preg_replace_callback($reg, function($matches) use ($para) {
global $config;
$url=trim($matches[1]);
if (stripos($url, "http://")===false && stripos($url, "https://")===false) {
@@ -140,24 +140,24 @@ private function _cacheImage($data)
public function procInfo($data)
{
if (isset($data["path"])) {
- $path = $data["path"];
+ $path=$data["path"];
} else {
throw new Exception("path is not exist in data");
}
if (isset($data["baseurl"])) {
- $baseurl = $data["baseurl"];
+ $baseurl=$data["baseurl"];
} else {
throw new Exception("baseurl is not exist in data");
}
if (isset($data["space_deli"])) {
- $space_deli = $data["space_deli"];
+ $space_deli=$data["space_deli"];
} else {
- $space_deli = true;
+ $space_deli=true;
}
if (isset($data["cookie"])) {
- $cookie = $data["cookie"];
+ $cookie=$data["cookie"];
} else {
- $cookie = "";
+ $cookie="";
}
$this->pro["description"]=$this->_cacheImage($this->pro["description"], $path, $baseurl, $space_deli, $cookie);
diff --git a/app/Babel/Extension/noj/JudgeClient.php b/app/Babel/Extension/noj/JudgeClient.php
index 66da13e1d..b5bd5d751 100644
--- a/app/Babel/Extension/noj/JudgeClient.php
+++ b/app/Babel/Extension/noj/JudgeClient.php
@@ -43,8 +43,8 @@ public function judge($src, $language, $testCaseId, $config=[])
'language_config' => $languageConfig,
'src' => $src,
'test_case_id' => $testCaseId,
- 'max_cpu_time' => $languageConfig['compile']['max_cpu_time'],
- 'max_memory' => $languageConfig['compile']['max_memory'],
+ 'max_cpu_time' => is_null($languageConfig['compile']) ?null:$languageConfig['compile']['max_cpu_time'],
+ 'max_memory' => is_null($languageConfig['compile']) ?null:$languageConfig['compile']['max_memory'],
'spj_version' => null,
'spj_config' => null,
'spj_compile_config' => null,
@@ -64,7 +64,7 @@ public function compileSpj($src, $spjVersion, $spjCompileConfig)
}
public function getLanguageConfigByLanguage($language, $spj=false)
{
- return $this->getLanguageConfigByKey($language.($spj?'_lang_spj_config':'_lang_config'));
+ return $this->getLanguageConfigByKey($language.($spj ? '_lang_spj_config' : '_lang_config'));
}
public function getLanguageConfigByKey($key)
{
diff --git a/app/Babel/Extension/noj/Languages.php b/app/Babel/Extension/noj/Languages.php
index b3e11dbcf..a81fce10b 100644
--- a/app/Babel/Extension/noj/Languages.php
+++ b/app/Babel/Extension/noj/Languages.php
@@ -14,7 +14,7 @@ public static function get()
'max_cpu_time' => 3000,
'max_real_time' => 10000,
'max_memory' => 1024 * 1024 * 1024,
- 'compile_command' => '/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 -static {src_path} -lm -o {exe_path}',
+ 'compile_command' => '/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}',
],
'run' => [
'command' => '{exe_path}',
@@ -50,6 +50,7 @@ public static function get()
'run' => [
'command' => '{exe_path}',
'seccomp_rule' => 'c_cpp',
+ 'env' => $default_env,
'memory_limit_check_only' => 1
]
],
@@ -64,7 +65,7 @@ public static function get()
'compile_command' => '/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8'
],
'run' => [
- 'command' => '/usr/bin/java -cp {exe_dir} -Xss1M -Xms16M -Xmx{max_memory}k -Djava.security.manager -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main',
+ 'command' => '/usr/bin/java -cp {exe_dir} -XX:MaxRAM={max_memory}k -Djava.security.manager -Dfile.encoding=UTF-8 -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main',
'seccomp_rule' => null,
'env' => $default_env,
'memory_limit_check_only' => 1
@@ -81,7 +82,7 @@ public static function get()
],
'run' => [
'command' => '/usr/bin/python {exe_path}',
- 'seccomp_rule' => null,
+ 'seccomp_rule' => 'general',
'env' => $default_env
]
],
@@ -97,14 +98,14 @@ public static function get()
'run' => [
'command' => '/usr/bin/python3.7 {exe_path}',
'seccomp_rule' => 'general',
- 'env' => array_merge(['MALLOC_ARENA_MAX=1'], $default_env)
+ 'env' => array_merge(['MALLOC_ARENA_MAX=1', 'PYTHONIOENCODING=UTF-8'], $default_env)
]
],
'php7_lang_config' => [
'compile' => null,
'run' => [
'exe_name' => 'solution.php',
- 'command' => '/usr/bin/php {exe_path}',
+ 'command' => '/usr/bin/php -d error_reporting=0 -f {exe_path}',
'seccomp_rule' => null,
'env' => $default_env,
'memory_limit_check_only' => 1
@@ -120,21 +121,118 @@ public static function get()
]
],
'go_lang_config' => [
- 'name' => 'go',
'compile' => [
'src_name' => 'main.go',
'exe_name' => 'main',
'max_cpu_time' => 3000,
'max_real_time' => 10000,
- 'max_memory' => 1024 * 1024 * 1024,
+ 'max_memory' => -1,
'compile_command' => '/usr/bin/go build -o {exe_path} {src_path}',
+ 'env' => ["GOCACHE=/tmp", "GOPATH=/root/go"]
],
'run' => [
'command' => '{exe_path}',
+ 'seccomp_rule' => "",
+ 'env' => array_merge(["GODEBUG=madvdontneed=1", "GOCACHE=off"], $default_env),
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'csharp_lang_config' => [
+ 'compile' => [
+ 'src_name' => 'main.cs',
+ 'exe_name' => 'main',
+ 'max_cpu_time' => 3000,
+ 'max_real_time' => 10000,
+ 'max_memory' => 1024 * 1024 * 1024,
+ 'compile_command' => '/usr/bin/mcs -optimize+ -out:{exe_path} {src_path}'
+ ],
+ 'run' => [
+ 'command' => '/usr/bin/mono {exe_path}',
'seccomp_rule' => null,
+ 'env' => $default_env,
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'ruby_lang_config' => [
+ 'compile' => null,
+ 'run' => [
+ 'exe_name' => 'solution.rb',
+ 'command' => '/usr/bin/ruby {exe_path}',
+ 'seccomp_rule' => null,
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'rust_lang_config' => [
+ 'compile' => [
+ 'src_name' => 'main.rs',
+ 'exe_name' => 'main',
+ 'max_cpu_time' => 3000,
+ 'max_real_time' => 10000,
+ 'max_memory' => 1024 * 1024 * 1024,
+ 'compile_command' => '/usr/bin/rustc -O -o {exe_path} {src_path}'
+ ],
+ 'run' => [
+ 'command' => '{exe_path}',
+ 'seccomp_rule' => "general",
+ 'env' => $default_env,
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'haskell_lang_config' => [
+ 'compile' => [
+ 'src_name' => 'main.hs',
+ 'exe_name' => 'main',
+ 'max_cpu_time' => 3000,
+ 'max_real_time' => 10000,
+ 'max_memory' => 1024 * 1024 * 1024,
+ 'compile_command' => '/usr/bin/ghc -O -outputdir /tmp -o {exe_path} {src_path}'
+ ],
+ 'run' => [
+ 'command' => '{exe_path}',
+ 'seccomp_rule' => "general",
+ 'env' => $default_env,
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'pascal_lang_config' => [
+ 'compile' => [
+ 'src_name' => 'main.pas',
+ 'exe_name' => 'main',
+ 'max_cpu_time' => 3000,
+ 'max_real_time' => 10000,
+ 'max_memory' => 1024 * 1024 * 1024,
+ 'compile_command' => '/usr/bin/fpc -O2 -o{exe_path} {src_path}'
+ ],
+ 'run' => [
+ 'command' => '{exe_path}',
+ 'seccomp_rule' => "general",
+ 'env' => $default_env
+ ]
+ ],
+ 'plaintext_lang_config' => [
+ 'compile' => null,
+ 'run' => [
+ 'exe_name' => 'solution.txt',
+ 'command' => '/bin/cat {exe_path}',
+ 'seccomp_rule' => "general",
+ 'memory_limit_check_only' => 1
+ ]
+ ],
+ 'basic_lang_config' => [
+ 'compile' => [
+ 'src_name' => 'main.bas',
+ 'exe_name' => 'main',
+ 'max_cpu_time' => 3000,
+ 'max_real_time' => 10000,
+ 'max_memory' => 1024 * 1024 * 1024,
+ 'compile_command' => '/usr/local/bin/fbc {src_path}'
+ ],
+ 'run' => [
+ 'command' => '{exe_path}',
+ 'seccomp_rule' => "general",
'env' => $default_env
]
- ]
+ ],
];
}
}
diff --git a/app/Babel/Extension/noj/Monitor.php b/app/Babel/Extension/noj/Monitor.php
index a4de7d096..2eee6ef4d 100644
--- a/app/Babel/Extension/noj/Monitor.php
+++ b/app/Babel/Extension/noj/Monitor.php
@@ -5,6 +5,7 @@
use App\Models\OJModel;
use App\Models\JudgerModel;
use Exception;
+use Log;
class Monitor extends MonitorBase
{
@@ -79,7 +80,7 @@ private function ping($url, $port, $token)
curl_close($curl);
if ($err) {
- \Log::error($err);
+ Log::error($err);
return [];
} else {
return [
diff --git a/app/Babel/Extension/noj/Submitter.php b/app/Babel/Extension/noj/Submitter.php
index 1306cd7cd..51ec4e8ed 100644
--- a/app/Babel/Extension/noj/Submitter.php
+++ b/app/Babel/Extension/noj/Submitter.php
@@ -80,7 +80,7 @@ public function submit()
"spj_compile_config" => null,
"spj_src" => null
];
- if($probBasic["spj"] && $probBasic["spj_version"]){
+ if ($probBasic["spj"] && $probBasic["spj_version"]) {
$submit_data["spj_version"]=$probBasic["spj_version"];
$submit_data["spj_config"]=$probBasic["spj_lang"];
$submit_data["spj_compile_config"]=[
@@ -177,7 +177,7 @@ public function submit()
$tempTime=max($tempTime, $t["cpu_time"]);
}
$this->sub['verdict']="Accepted";
- $this->sub['score']=1;
+ // $this->sub['score']=1;
$this->sub['time']=$tempTime;
$this->sub['memory']=round($tempMemory / 1024);
}
diff --git a/app/Babel/Extension/noj/TestRunner.php b/app/Babel/Extension/noj/TestRunner.php
new file mode 100644
index 000000000..9c79cf9ef
--- /dev/null
+++ b/app/Babel/Extension/noj/TestRunner.php
@@ -0,0 +1,120 @@
+ "Compile Error",
+ -1 => "Wrong Answer",
+ 0 => "Accepted",
+ 1 => "Time Limit Exceed",
+ 2 => "Real Time Limit Exceed",
+ 3 => "Memory Limit Exceed",
+ 4 => "Runtime Error",
+ 5 => "System Error",
+ 6 => "Pending",
+ 7 => "Judging",
+ 8 => "Partially Accepted"
+ ];
+
+ public function __construct($config)
+ {
+ $this->oid=OJModel::oid($this->ocode);
+ $this->pid=$config['pid'];
+ $this->coid=$config['coid'];
+ $this->solution=$config['solution'];
+ }
+
+ public function run()
+ {
+ $judgerModel=new JudgerModel();
+ $compilerModel=new CompilerModel();
+ $problemModel=new ProblemModel();
+ $language=$compilerModel->detail($this->coid)['lcode'];
+ $bestServer=$judgerModel->server($this->oid);
+ if (is_null($bestServer)) {
+ $this->verdict=[
+ "verdict"=>"Compile Error",
+ "compile_info"=>"No Available Judger.",
+ "data"=>[]
+ ];
+ return;
+ }
+ $probBasic=$problemModel->basic($this->pid);
+ $submitURL="http://".$bestServer["host"].":".$bestServer["port"];
+ $submit_data=[
+ "solution" => $this->solution,
+ "language" => $language,
+ "max_cpu_time" => $probBasic["time_limit"] * ($language=="java" ? 3 : 1),
+ "max_memory" => $probBasic["memory_limit"] * 1024,
+ "test_case_id" => $probBasic["pcode"],
+ "token" => $bestServer["token"],
+ "spj_version" => null,
+ "spj_config" => null,
+ "spj_compile_config" => null,
+ "spj_src" => null
+ ];
+ if ($probBasic["spj"] && $probBasic["spj_version"]) {
+ $submit_data["spj_version"]=$probBasic["spj_version"];
+ $submit_data["spj_config"]=$probBasic["spj_lang"];
+ $submit_data["spj_compile_config"]=[
+ "src_name" => "spj-{spj_version}.c",
+ "exe_name" => "spj-{spj_version}",
+ "max_cpu_time" => 3000,
+ "max_real_time" => 5000,
+ "max_memory" => 1073741824,
+ "compile_command" => "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}"
+ ]; // fixed at C99, future linked with spj_lang
+ $submit_data["spj_src"]=$probBasic["spj_src"];
+ }
+ $judgeClient=new JudgeClient($submit_data["token"], $submitURL);
+ $temp=$judgeClient->judge($submit_data["solution"], $submit_data["language"], $submit_data["test_case_id"], [
+ 'output' => false,
+ 'max_cpu_time'=>$submit_data['max_cpu_time'],
+ 'max_memory'=>$submit_data['max_memory'],
+ 'spj_version'=>$submit_data['spj_version'],
+ 'spj_config'=>$submit_data['spj_config'],
+ 'spj_compile_config'=>$submit_data['spj_compile_config'],
+ 'spj_src'=>$submit_data['spj_src']
+ ]);
+ if (!is_null($temp["err"])) {
+ if (strpos($temp["data"], 'Compiler runtime error, info: ')!==false) {
+ $tempRes=json_decode(explode('Compiler runtime error, info: ', $temp["data"])[1], true);
+ $this->verdict['verdict']=$this->verdictDict[$tempRes["result"]];
+ $this->verdict['compile_info']=null;
+ } else {
+ $this->verdict['verdict']=$this->verdictDict["-2"];
+ $this->verdict['compile_info']=$temp["data"];
+ }
+ $this->verdict['data']=[];
+ return $this->verdict;
+ }
+
+ $this->verdict['verdict']="Accepted";
+ foreach ($temp["data"] as $record) {
+ if ($record["result"]) {
+ // well... WA or anyway
+ $this->verdict['verdict']=$this->verdictDict[$record["result"]];
+ break;
+ }
+ }
+
+ $this->verdict['data']=$temp["data"];
+ $this->verdict['compile_info']=null;
+ foreach ($this->verdict['data'] as &$record) {
+ $record["result"]=$this->verdictDict[$record["result"]];
+ }
+ return $this->verdict;
+ }
+}
diff --git a/app/Babel/Extension/noj/babel.json b/app/Babel/Extension/noj/babel.json
index 01aa616a6..0d7c44412 100644
--- a/app/Babel/Extension/noj/babel.json
+++ b/app/Babel/Extension/noj/babel.json
@@ -14,7 +14,8 @@
"provider": {
"submitter": "Submitter",
"installer": "Installer",
- "monitor": "Monitor"
+ "monitor": "Monitor",
+ "testrunner": "TestRunner"
},
"require": {
"NOJ": "__cur__"
diff --git a/app/Babel/Extension/noj/compiler/1616243142.json b/app/Babel/Extension/noj/compiler/1616243142.json
new file mode 100644
index 000000000..34fc8b7b3
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616243142.json
@@ -0,0 +1,10 @@
+{
+ "modifications":[{
+ "code":"csharp",
+ "compability":"csharp",
+ "language":"csharp",
+ "icon":"devicon-csharp-plain",
+ "display":"C#",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616298361.json b/app/Babel/Extension/noj/compiler/1616298361.json
new file mode 100644
index 000000000..27e45055f
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616298361.json
@@ -0,0 +1,17 @@
+{
+ "modifications":[{
+ "code":"ruby",
+ "compability":"ruby",
+ "language":"ruby",
+ "icon":"devicon-ruby-plain",
+ "display":"Ruby",
+ "method":"add"
+ },{
+ "code":"rust",
+ "compability":"rust",
+ "language":"rust",
+ "icon":"devicon-rust-plain",
+ "display":"Rust",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616485388.json b/app/Babel/Extension/noj/compiler/1616485388.json
new file mode 100644
index 000000000..a2d4386b5
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616485388.json
@@ -0,0 +1,10 @@
+{
+ "modifications":[{
+ "code":"haskell",
+ "compability":"haskell",
+ "language":"haskell",
+ "icon":"devicon-haskell-plain",
+ "display":"Haskell",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616512951.json b/app/Babel/Extension/noj/compiler/1616512951.json
new file mode 100644
index 000000000..803a0d9d6
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616512951.json
@@ -0,0 +1,10 @@
+{
+ "modifications":[{
+ "code":"pascal",
+ "compability":"pascal",
+ "language":"pascal",
+ "icon":"devicon-devicon-plain",
+ "display":"Free Pascal",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616514412.json b/app/Babel/Extension/noj/compiler/1616514412.json
new file mode 100644
index 000000000..065a808a4
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616514412.json
@@ -0,0 +1,10 @@
+{
+ "modifications":[{
+ "code":"plaintext",
+ "compability":"plaintext",
+ "language":"plaintext",
+ "icon":"devicon-vim-plain",
+ "display":"Plain Text",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616557725.json b/app/Babel/Extension/noj/compiler/1616557725.json
new file mode 100644
index 000000000..e28035886
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616557725.json
@@ -0,0 +1,7 @@
+{
+ "modifications":[{
+ "code":"pascal",
+ "icon":"langicon-delphi",
+ "method":"modify"
+ }]
+}
diff --git a/app/Babel/Extension/noj/compiler/1616566374.json b/app/Babel/Extension/noj/compiler/1616566374.json
new file mode 100644
index 000000000..1ccc94677
--- /dev/null
+++ b/app/Babel/Extension/noj/compiler/1616566374.json
@@ -0,0 +1,10 @@
+{
+ "modifications":[{
+ "code":"basic",
+ "compability":"basic",
+ "language":"vb",
+ "icon":"langicon-basic",
+ "display":"Free Basic",
+ "method":"add"
+ }]
+}
diff --git a/app/Babel/Install/InstallerBase.php b/app/Babel/Install/InstallerBase.php
index 88b61e491..6fb2c276c 100644
--- a/app/Babel/Install/InstallerBase.php
+++ b/app/Babel/Install/InstallerBase.php
@@ -39,8 +39,8 @@ protected function _install($ocode)
//writing database
$this->transactionDB();
- }catch(Throwable $e){
- if ($e->getMessage()!==""){
+ } catch (Throwable $e) {
+ if ($e->getMessage()!=="") {
$this->command->line("\n {$e->getMessage()} >\n");
}
}
@@ -59,12 +59,12 @@ protected function _uninstall($ocode)
public function __construct($class)
{
$this->command=$class;
- $this->versionParser = new VersionConstraintParser();
+ $this->versionParser=new VersionConstraintParser();
}
private function parseVersion()
{
- if(empty($this->babelConfig)){
+ if (empty($this->babelConfig)) {
throw new Exception('Missing babel.json Config file.');
}
@@ -134,7 +134,7 @@ private function transactionDB()
DB::commit();
- }catch(Throwable $e){
+ } catch (Throwable $e) {
DB::rollback();
if ($e->getMessage()!=="") {
$this->command->line("\n {$e->getMessage()} >\n");
diff --git a/app/Babel/Install/InstallerWorker.php b/app/Babel/Install/InstallerWorker.php
index 3683b0863..34428ce3d 100644
--- a/app/Babel/Install/InstallerWorker.php
+++ b/app/Babel/Install/InstallerWorker.php
@@ -84,9 +84,9 @@ public function importCompilerInfo($info)
$installed_timestamp=intval($info["compiler_timestamp"]);
}
$latest_timestamp=$installed_timestamp;
- $ConpilerConfig = glob(babel_path("Extension/$ocode/compiler/*.*"));
+ $ConpilerConfig=glob(babel_path("Extension/$ocode/compiler/*.*"));
foreach ($ConpilerConfig as $file) {
- if (intval(basename($file)) > $installed_timestamp) {
+ if (intval(basename($file))>$installed_timestamp) {
try {
$this->commitCompiler($file, json_decode(file_get_contents($file), true));
$latest_timestamp=intval(basename($file));
diff --git a/app/Babel/Judge/Judger.php b/app/Babel/Judge/Judger.php
index e871b6527..aadb94b79 100644
--- a/app/Babel/Judge/Judger.php
+++ b/app/Babel/Judge/Judger.php
@@ -56,7 +56,7 @@ public static function create($ocode)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$name\\$judgerProvider";
+ $className="App\\Babel\\Extension\\$name\\$judgerProvider";
if (class_exists($className)) {
return new $className();
} else {
diff --git a/app/Babel/Monit/Monitor.php b/app/Babel/Monit/Monitor.php
index 55f5aa64b..206b44de9 100644
--- a/app/Babel/Monit/Monitor.php
+++ b/app/Babel/Monit/Monitor.php
@@ -33,7 +33,7 @@ public static function create($conf)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$name\\$monitorProvider";
+ $className="App\\Babel\\Extension\\$name\\$monitorProvider";
if (class_exists($className)) {
return new $className();
} else {
diff --git a/app/Babel/Monit/MonitorBase.php b/app/Babel/Monit/MonitorBase.php
index ad18c3985..d16bc53cf 100644
--- a/app/Babel/Monit/MonitorBase.php
+++ b/app/Babel/Monit/MonitorBase.php
@@ -2,7 +2,7 @@
namespace App\Babel\Monit;
-use App\Models\Eloquent\JudgeServerModel;
+use App\Models\Eloquent\JudgeServer;
use ErrorException;
use Exception;
use Throwable;
@@ -11,7 +11,7 @@ class MonitorBase
{
public function updateStatus($jsid, $status, $usage=null)
{
- $judgeServer=JudgeServerModel::find($jsid);
+ $judgeServer=JudgeServer::find($jsid);
if (is_null($judgeServer)) {
return false;
} else {
diff --git a/app/Babel/Submit/Curl.php b/app/Babel/Submit/Curl.php
index 7ab846050..c05c1c212 100644
--- a/app/Babel/Submit/Curl.php
+++ b/app/Babel/Submit/Curl.php
@@ -18,11 +18,11 @@ public function __construct()
public function login($all_data)
{
- if(isset($all_data["url"])) $url = $all_data["url"]; else throw new Exception("url is not exist in all_data");
- if(isset($all_data["data"])) $data = $all_data["data"]; else throw new Exception("data is not exist in all_data");
- if(isset($all_data["oj"])) $oj = $all_data["oj"]; else throw new Exception("oj is not exist in all_data");
- if(isset($all_data["ret"])) $ret = $all_data["ret"]; else $ret = 'false';
- if(isset($all_data["handle"])) $handle = $all_data["handle"]; else $handle = "default";
+ if (isset($all_data["url"])) $url=$all_data["url"]; else throw new Exception("url is not exist in all_data");
+ if (isset($all_data["data"])) $data=$all_data["data"]; else throw new Exception("data is not exist in all_data");
+ if (isset($all_data["oj"])) $oj=$all_data["oj"]; else throw new Exception("oj is not exist in all_data");
+ if (isset($all_data["ret"])) $ret=$all_data["ret"]; else $ret='false';
+ if (isset($all_data["handle"])) $handle=$all_data["handle"]; else $handle="default";
$datapost=curl_init();
$headers=array("Expect:");
@@ -54,12 +54,12 @@ public function login($all_data)
public function grab_page($all_data)
{
- if(isset($all_data["site"])) $site = $all_data["site"]; else throw new Exception("site is not exist in all_data");
- if(isset($all_data["oj"])) $oj = $all_data["oj"]; else throw new Exception("oj is not exist in all_data");
- if(isset($all_data["headers"])) $headers = $all_data["headers"]; else $headers = [];
- if(isset($all_data["handle"])) $handle = $all_data["handle"]; else $handle = "default";
- if(isset($all_data["follow"])) $follow = $all_data["follow"]; else $follow = false;
- if(isset($all_data["vcid"])) $vcid = $all_data["vcid"]."_"; else $vcid = "";
+ if (isset($all_data["site"])) $site=$all_data["site"]; else throw new Exception("site is not exist in all_data");
+ if (isset($all_data["oj"])) $oj=$all_data["oj"]; else throw new Exception("oj is not exist in all_data");
+ if (isset($all_data["headers"])) $headers=$all_data["headers"]; else $headers=[];
+ if (isset($all_data["handle"])) $handle=$all_data["handle"]; else $handle="default";
+ if (isset($all_data["follow"])) $follow=$all_data["follow"]; else $follow=false;
+ if (isset($all_data["vcid"])) $vcid=$all_data["vcid"]."_"; else $vcid="";
$handle=urlencode($handle);
@@ -86,16 +86,16 @@ public function grab_page($all_data)
public function post_data($all_data)
{
- if(isset($all_data["site"])) $site = $all_data["site"]; else throw new Exception("site is not exist in all_data");
- if(isset($all_data["data"])) $data = $all_data["data"]; else throw new Exception("data is not exist in all_data");
- if(isset($all_data["oj"])) $oj = $all_data["oj"]; else throw new Exception("oj is not exist in all_data");
- if(isset($all_data["ret"])) $ret = $all_data["ret"]; else $ret = false;
- if(isset($all_data["follow"])) $follow = $all_data["follow"]; else $follow = true;
- if(isset($all_data["returnHeader"])) $returnHeader = $all_data["returnHeader"]; else $returnHeader = true;
- if(isset($all_data["postJson"])) $postJson = $all_data["postJson"]; else $postJson = false;
- if(isset($all_data["extraHeaders"])) $extraHeaders = $all_data["extraHeaders"]; else $extraHeaders = [];
- if(isset($all_data["handle"])) $handle = $all_data["handle"]; else $handle = "default";
- if(isset($all_data["vcid"])) $vcid = $all_data["vcid"]."_"; else $vcid = "";
+ if (isset($all_data["site"])) $site=$all_data["site"]; else throw new Exception("site is not exist in all_data");
+ if (isset($all_data["data"])) $data=$all_data["data"]; else throw new Exception("data is not exist in all_data");
+ if (isset($all_data["oj"])) $oj=$all_data["oj"]; else throw new Exception("oj is not exist in all_data");
+ if (isset($all_data["ret"])) $ret=$all_data["ret"]; else $ret=false;
+ if (isset($all_data["follow"])) $follow=$all_data["follow"]; else $follow=true;
+ if (isset($all_data["returnHeader"])) $returnHeader=$all_data["returnHeader"]; else $returnHeader=true;
+ if (isset($all_data["postJson"])) $postJson=$all_data["postJson"]; else $postJson=false;
+ if (isset($all_data["extraHeaders"])) $extraHeaders=$all_data["extraHeaders"]; else $extraHeaders=[];
+ if (isset($all_data["handle"])) $handle=$all_data["handle"]; else $handle="default";
+ if (isset($all_data["vcid"])) $vcid=$all_data["vcid"]."_"; else $vcid="";
$handle=urlencode($handle);
diff --git a/app/Babel/Submit/Submitter.php b/app/Babel/Submit/Submitter.php
index a088b48c8..979af9cb5 100644
--- a/app/Babel/Submit/Submitter.php
+++ b/app/Babel/Submit/Submitter.php
@@ -51,7 +51,7 @@ public static function create($oj, & $sub, $all_data)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$oj\\$submitterProvider";
+ $className="App\\Babel\\Extension\\$oj\\$submitterProvider";
if (class_exists($className)) {
return new $className($sub, $all_data);
} else {
diff --git a/app/Babel/Synchronize/Synchronizer.php b/app/Babel/Synchronize/Synchronizer.php
index 113e20542..586df4025 100644
--- a/app/Babel/Synchronize/Synchronizer.php
+++ b/app/Babel/Synchronize/Synchronizer.php
@@ -23,7 +23,7 @@ public static function create($oj, $all_data)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$oj\\$synchronizerProvider";
+ $className="App\\Babel\\Extension\\$oj\\$synchronizerProvider";
if (class_exists($className)) {
return new $className($all_data);
} else {
diff --git a/app/Babel/TestRun/TestRunner.php b/app/Babel/TestRun/TestRunner.php
new file mode 100644
index 000000000..928cd7f42
--- /dev/null
+++ b/app/Babel/TestRun/TestRunner.php
@@ -0,0 +1,39 @@
+verdict=$runner->run();
+ }
+ }
+
+ public static function create($conf)
+ {
+ $name=$conf["name"];
+ $runnerProvider="TestRunner";
+ try {
+ $BabelConfig=json_decode(file_get_contents(babel_path("Extension/$name/babel.json")), true);
+ $runnerProvider=$BabelConfig["provider"]["testrunner"];
+ } catch (Throwable $e) {
+ } catch (ErrorException $e) {
+ } catch (Exception $e) {
+ }
+ $className="App\\Babel\\Extension\\$name\\$runnerProvider";
+ if (class_exists($className)) {
+ return new $className($conf);
+ } else {
+ return null;
+ }
+ }
+}
diff --git a/app/Babel/spoj b/app/Babel/spoj
deleted file mode 160000
index 42b0e099c..000000000
--- a/app/Babel/spoj
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 42b0e099cb9be33011db6afba15384cc0344e31c
diff --git a/app/Console/Commands/Babel/BabelCommand.php b/app/Console/Commands/Babel/BabelCommand.php
index 7363a3232..76449f1ff 100644
--- a/app/Console/Commands/Babel/BabelCommand.php
+++ b/app/Console/Commands/Babel/BabelCommand.php
@@ -13,19 +13,19 @@ class BabelCommand extends Command
*
* @var string
*/
- protected $signature = 'babel';
+ protected $signature='babel';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'List all babel commands';
+ protected $description='List all babel commands';
/**
* @var string
*/
- public static $logo = <<line(static::$logo);
- $this->line(sprintf('NOJ version %s',version()));
+ $this->line(sprintf('NOJ version %s', version()));
$this->comment('');
$this->comment('Available commands:');
@@ -57,7 +57,7 @@ public function handle()
*/
protected function listBabelCommands()
{
- $commands = collect(Artisan::all())->mapWithKeys(function ($command, $key) {
+ $commands=collect(Artisan::all())->mapWithKeys(function($command, $key) {
if (Str::startsWith($key, 'babel:')) {
return [$key => $command];
}
@@ -65,7 +65,7 @@ protected function listBabelCommands()
return [];
})->toArray();
- $width = $this->getColumnWidth($commands);
+ $width=$this->getColumnWidth($commands);
/** @var Command $command */
foreach ($commands as $command) {
@@ -80,16 +80,16 @@ protected function listBabelCommands()
*/
private function getColumnWidth(array $commands)
{
- $widths = [];
+ $widths=[];
foreach ($commands as $command) {
- $widths[] = static::strlen($command->getName());
+ $widths[]=static::strlen($command->getName());
foreach ($command->getAliases() as $alias) {
- $widths[] = static::strlen($alias);
+ $widths[]=static::strlen($alias);
}
}
- return $widths ? max($widths) + 2 : 0;
+ return $widths ? max($widths)+2 : 0;
}
/**
@@ -101,7 +101,7 @@ private function getColumnWidth(array $commands)
*/
public static function strlen($string)
{
- if (false === $encoding = mb_detect_encoding($string, null, true)) {
+ if (false===$encoding=mb_detect_encoding($string, null, true)) {
return strlen($string);
}
diff --git a/app/Console/Commands/Babel/BabelRequire.php b/app/Console/Commands/Babel/BabelRequire.php
index 66c36040f..bb2b119aa 100644
--- a/app/Console/Commands/Babel/BabelRequire.php
+++ b/app/Console/Commands/Babel/BabelRequire.php
@@ -14,14 +14,14 @@ class BabelRequire extends Command
*
* @var string
*/
- protected $signature = 'babel:require {extension : The package name of the extension} {--exception}';
+ protected $signature='babel:require {extension : The package name of the extension} {--ignore-platform-reqs : Ignore the Platform Requirements when install} {--exception}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Download a given Babel Extension to NOJ';
+ protected $description='Download a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -40,9 +40,10 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $exception = $this->option('exception');
- $output = new BufferedOutput();
+ $extension=$this->argument('extension');
+ $exception=$this->option('exception');
+ $ignoreReqs=$this->option('ignore-platform-reqs');
+ $output=new BufferedOutput();
if (is_dir(babel_path("Extension/$extension/"))) {
if (!$exception) {
$this->line("\n Exception > : An extension named $extension> already took place, did you mean php artisan bable:update $extension>?>\n");
@@ -74,7 +75,7 @@ public function handle()
mkdir(babel_path("Tmp/$extension/"));
}
try {
- $zipFile = new ZipFile();
+ $zipFile=new ZipFile();
$zipFile->openFile(babel_path("Tmp/$filename"))->extractTo(babel_path("Tmp/$extension/"))->close();
$babelPath=glob_recursive(babel_path("Tmp/$extension/babel.json"));
if (empty($babelPath)) {
@@ -108,7 +109,10 @@ public function handle()
}
$this->postProc($filename, $extension);
$this->line("Downloaded $extension>({$targetPackage['version']}>)");
- $this->call("babel:install", ['extension' => $extension]);
+ $this->call("babel:install", [
+ 'extension' => $extension,
+ '--ignore-platform-reqs' => $ignoreReqs,
+ ]);
$output->fetch();
}
@@ -123,8 +127,8 @@ private function delDir($dir)
if (!is_dir($dir)) {
return;
}
- $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
- $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
+ $it=new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
+ $files=new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
diff --git a/app/Console/Commands/Babel/Crawl.php b/app/Console/Commands/Babel/Crawl.php
index 1dd425523..b0be399d6 100644
--- a/app/Console/Commands/Babel/Crawl.php
+++ b/app/Console/Commands/Babel/Crawl.php
@@ -5,7 +5,6 @@
use Illuminate\Console\Command;
use App\Babel\Babel;
use Exception;
-use function GuzzleHttp\json_decode;
class Crawl extends Command
{
@@ -14,7 +13,7 @@ class Crawl extends Command
*
* @var string
*/
- protected $signature = 'babel:crawl
+ protected $signature='babel:crawl
{extension : The package name of the extension}
{--action=crawl_problem : The action of the Crawler}
{--con=all : The target problemset of the Crawler}
@@ -26,7 +25,7 @@ class Crawl extends Command
*
* @var string
*/
- protected $description = 'Crawl problems for a given Babel Extension to NOJ';
+ protected $description='Crawl problems for a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -45,11 +44,11 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $action = $this->option('action');
- $con = $this->option('con');
- [$from, $to] = sscanf($this->option('range'),"%d:%d");
- $cached = $this->option('cached');
+ $extension=$this->argument('extension');
+ $action=$this->option('action');
+ $con=$this->option('con');
+ [$from, $to]=sscanf($this->option('range'), "%d:%d");
+ $cached=$this->option('cached');
$babel=new Babel();
$babel->crawl([
"name" => $extension,
diff --git a/app/Console/Commands/Babel/Install.php b/app/Console/Commands/Babel/Install.php
index d53b27aed..ad491091d 100644
--- a/app/Console/Commands/Babel/Install.php
+++ b/app/Console/Commands/Babel/Install.php
@@ -4,7 +4,6 @@
use Illuminate\Console\Command;
use Exception;
-use function GuzzleHttp\json_decode;
use Symfony\Component\Console\Output\BufferedOutput;
class Install extends Command
@@ -14,14 +13,14 @@ class Install extends Command
*
* @var string
*/
- protected $signature = 'babel:install {extension : The package name of the extension} {--ignore-platform-reqs : Ignore the Platform Requirements when install}';
+ protected $signature='babel:install {extension : The package name of the extension} {--ignore-platform-reqs : Ignore the Platform Requirements when install}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Install a given Babel Extension to NOJ';
+ protected $description='Install a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -40,16 +39,19 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $ignoreReqs = $this->option('ignore-platform-reqs');
- $output = new BufferedOutput();
+ $extension=$this->argument('extension');
+ $ignoreReqs=$this->option('ignore-platform-reqs');
+ $output=new BufferedOutput();
$installerProvider="Installer";
try {
$BabelConfig=json_decode(file_get_contents(babel_path("Extension/$extension/babel.json")), true);
} catch (Exception $e) {
$this->line("\n Exception > : babel.json parse error, The extension may not exist.>\n");
if ($this->confirm("Would you like to download it from the marketspace first?")) {
- $this->call("babel:require", ['extension' => $extension]);
+ $this->call("babel:require", [
+ 'extension' => $extension,
+ '--ignore-platform-reqs' => $ignoreReqs,
+ ]);
$output->fetch();
}
return;
@@ -69,7 +71,7 @@ public function handle()
public static function create($oj, $installerProvider, $class)
{
- $className = "App\\Babel\\Extension\\$oj\\$installerProvider";
+ $className="App\\Babel\\Extension\\$oj\\$installerProvider";
if (class_exists($className)) {
return new $className($class);
} else {
diff --git a/app/Console/Commands/Babel/Judge.php b/app/Console/Commands/Babel/Judge.php
new file mode 100644
index 000000000..6072a9b4f
--- /dev/null
+++ b/app/Console/Commands/Babel/Judge.php
@@ -0,0 +1,52 @@
+line("[$time] Processing: >NOJ Babel Judge Sync");
+ $babel->judge();
+ $time=date("Y-m-d H:i:s");
+ $this->line("[$time] Processed: >NOJ Babel Judge Sync");
+ sleep(5);
+ }
+ }
+}
diff --git a/app/Console/Commands/Babel/RefreshRank.php b/app/Console/Commands/Babel/RefreshRank.php
index 3f699aa9a..b88b0b0c4 100644
--- a/app/Console/Commands/Babel/RefreshRank.php
+++ b/app/Console/Commands/Babel/RefreshRank.php
@@ -5,7 +5,6 @@
use Illuminate\Console\Command;
use App\Babel\Babel;
use Exception;
-use function GuzzleHttp\json_decode;
class RefreshRank extends Command
{
@@ -14,14 +13,14 @@ class RefreshRank extends Command
*
* @var string
*/
- protected $signature = 'babel:rerank {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid=1 : The holding group} {--cid= : The NOJ contest}';
+ protected $signature='babel:rerank {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid=1 : The holding group} {--cid= : The NOJ contest}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Refresh Rank from a remote contest';
+ protected $description='Refresh Rank from a remote contest';
/**
* Create a new command instance.
@@ -40,18 +39,18 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $vcid = $this->option('vcid');
- $gid = $this->option('gid');
- $cid = $this->option('cid');
- $className = "App\\Babel\\Extension\\$extension\\Synchronizer";
- $all_data = [
+ $extension=$this->argument('extension');
+ $vcid=$this->option('vcid');
+ $gid=$this->option('gid');
+ $cid=$this->option('cid');
+ $className="App\\Babel\\Extension\\$extension\\Synchronizer";
+ $all_data=[
'oj'=>$extension,
'vcid'=>$vcid,
'gid'=>$gid,
'cid'=>$cid,
];
- $Sync = new $className($all_data);
+ $Sync=new $className($all_data);
$Sync->crawlRank();
}
}
diff --git a/app/Console/Commands/Babel/SyncContest.php b/app/Console/Commands/Babel/SyncContest.php
index f6a40de4b..fda3f6353 100644
--- a/app/Console/Commands/Babel/SyncContest.php
+++ b/app/Console/Commands/Babel/SyncContest.php
@@ -5,7 +5,6 @@
use Illuminate\Console\Command;
use App\Babel\Babel;
use Exception;
-use function GuzzleHttp\json_decode;
class SyncContest extends Command
{
@@ -14,14 +13,14 @@ class SyncContest extends Command
*
* @var string
*/
- protected $signature = 'babel:sync {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid=1 : The holding group}';
+ protected $signature='babel:sync {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid=1 : The holding group}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Crawl contests for a given Babel Extension to NOJ';
+ protected $description='Crawl contests for a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -40,16 +39,16 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $vcid = $this->option('vcid');
- $gid = $this->option('gid');
- $className = "App\\Babel\\Extension\\$extension\\Synchronizer";
- $all_data = [
+ $extension=$this->argument('extension');
+ $vcid=$this->option('vcid');
+ $gid=$this->option('gid');
+ $className="App\\Babel\\Extension\\$extension\\Synchronizer";
+ $all_data=[
'oj'=>$extension,
'vcid'=>$vcid,
'gid'=>$gid,
];
- $Sync = new $className($all_data);
+ $Sync=new $className($all_data);
$Sync->crawlContest();
}
}
diff --git a/app/Console/Commands/Babel/SyncProblems.php b/app/Console/Commands/Babel/SyncProblems.php
index 0a893be02..382a0150a 100644
--- a/app/Console/Commands/Babel/SyncProblems.php
+++ b/app/Console/Commands/Babel/SyncProblems.php
@@ -5,7 +5,6 @@
use Illuminate\Console\Command;
use App\Babel\Babel;
use Exception;
-use function GuzzleHttp\json_decode;
class SyncProblems extends Command
{
@@ -14,14 +13,14 @@ class SyncProblems extends Command
*
* @var string
*/
- protected $signature = 'babel:syncpro {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid= : The holding group} {--cid= : The contest in NOJ}';
+ protected $signature='babel:syncpro {extension : The package name of the extension} {--vcid= : The target contest of the Crawler} {--gid= : The holding group} {--cid= : The contest in NOJ}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Crawl contests for a given Babel Extension to NOJ';
+ protected $description='Crawl contests for a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -40,18 +39,18 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $vcid = $this->option('vcid');
- $gid = $this->option('gid');
- $cid = $this->option('cid');
- $className = "App\\Babel\\Extension\\$extension\\Synchronizer";
- $all_data = [
+ $extension=$this->argument('extension');
+ $vcid=$this->option('vcid');
+ $gid=$this->option('gid');
+ $cid=$this->option('cid');
+ $className="App\\Babel\\Extension\\$extension\\Synchronizer";
+ $all_data=[
'oj'=>$extension,
'vcid'=>$vcid,
'gid'=>$gid,
'cid'=>$cid,
];
- $Sync = new $className($all_data);
+ $Sync=new $className($all_data);
$Sync->scheduleCrawl();
}
}
diff --git a/app/Console/Commands/Babel/Uninstall.php b/app/Console/Commands/Babel/Uninstall.php
index c4f568178..9522c9098 100644
--- a/app/Console/Commands/Babel/Uninstall.php
+++ b/app/Console/Commands/Babel/Uninstall.php
@@ -12,14 +12,14 @@ class Uninstall extends Command
*
* @var string
*/
- protected $signature = 'babel:uninstall {extension : The package name of the extension}';
+ protected $signature='babel:uninstall {extension : The package name of the extension}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Uninstall a given Babel Extension to NOJ';
+ protected $description='Uninstall a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -38,7 +38,7 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
+ $extension=$this->argument('extension');
$submitter=self::create($extension, $this);
if (!is_null($submitter)) {
$submitter->uninstall();
@@ -56,7 +56,7 @@ public static function create($oj, $class)
} catch (ErrorException $e) {
} catch (Exception $e) {
}
- $className = "App\\Babel\\Extension\\$oj\\$installerProvider";
+ $className="App\\Babel\\Extension\\$oj\\$installerProvider";
if (class_exists($className)) {
return new $className($class);
} else {
diff --git a/app/Console/Commands/Babel/Update.php b/app/Console/Commands/Babel/Update.php
index a9419dd70..5d5d5759e 100644
--- a/app/Console/Commands/Babel/Update.php
+++ b/app/Console/Commands/Babel/Update.php
@@ -4,7 +4,6 @@
use Illuminate\Console\Command;
use Exception;
-use function GuzzleHttp\json_decode;
use Symfony\Component\Console\Output\BufferedOutput;
class Update extends Command
@@ -14,14 +13,14 @@ class Update extends Command
*
* @var string
*/
- protected $signature = 'babel:update {extension : The package name of the extension}';
+ protected $signature='babel:update {extension : The package name of the extension}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Update a given Babel Extension to NOJ';
+ protected $description='Update a given Babel Extension to NOJ';
/**
* Create a new command instance.
@@ -40,8 +39,8 @@ public function __construct()
*/
public function handle()
{
- $extension = $this->argument('extension');
- $output = new BufferedOutput();
+ $extension=$this->argument('extension');
+ $output=new BufferedOutput();
$this->line("Updating $extension>");
try {
$BabelConfig=json_decode(file_get_contents(babel_path("Extension/$extension/babel.json")), true);
@@ -90,8 +89,8 @@ private function delDir($dir)
if (!is_dir($dir)) {
return;
}
- $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
- $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
+ $it=new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
+ $files=new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
diff --git a/app/Console/Commands/Manage/BanUser.php b/app/Console/Commands/Manage/BanUser.php
index 61c097dc1..480d461a4 100644
--- a/app/Console/Commands/Manage/BanUser.php
+++ b/app/Console/Commands/Manage/BanUser.php
@@ -4,7 +4,7 @@
use Illuminate\Console\Command;
use App\Models\Eloquent\UserBanned;
-use App\User;
+use App\Models\Eloquent\User;
class BanUser extends Command
{
@@ -13,14 +13,14 @@ class BanUser extends Command
*
* @var string
*/
- protected $signature = 'manage:ban {--uid=: the user you want to ban} {--time=: Unban time, Supports time that can be resolved by the strtotime method} {--reason=: reason}';
+ protected $signature='manage:ban {--uid= : the user you want to ban} {--time= : Unban time, Supports time that can be resolved by the strtotime method} {--reason= : reason}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Ban a user';
+ protected $description='Ban a user';
/**
* Create a new command instance.
@@ -39,23 +39,23 @@ public function __construct()
*/
public function handle()
{
- $uid=(int)$this->option('uid');
+ $uid=(int) $this->option('uid');
$reason=$this->option('reason');
$time=$this->option('time');
- $user = User::find($uid);
- if(empty($user)) {
+ $user=User::find($uid);
+ if (empty($user)) {
$this->line("\n Exception > : User Not Found>\n");
return;
}
- try{
- $ban_time = date('Y-m-d H:i:s',strtotime($time));
+ try {
+ $ban_time=date('Y-m-d H:i:s', strtotime($time));
UserBanned::create([
'user_id' => $user->id,
'reason' => $reason,
'removed_at' => $ban_time
]);
$this->line("The user {$user->name}> will be banned until {$ban_time}>");
- }catch(Throwable $e){
+ } catch (Throwable $e) {
$this->line("\n Exception > : Wrong Time.>\n");
return;
}
diff --git a/app/Console/Commands/Manage/CreateAdminCommand.php b/app/Console/Commands/Manage/CreateAdminCommand.php
index 4043b3129..db050eccb 100644
--- a/app/Console/Commands/Manage/CreateAdminCommand.php
+++ b/app/Console/Commands/Manage/CreateAdminCommand.php
@@ -11,25 +11,25 @@ class CreateAdminCommand extends Command
*
* @var string
*/
- protected $signature = 'manage:create-admin';
+ protected $signature='manage:create-admin';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Create a admin user';
+ protected $description='Create a admin user';
/**
* Execute the console command.
*/
public function handle()
{
- $userModel = config('admin.database.users_model');
- $username = $this->ask('Please enter a username to login');
- $password = bcrypt($this->secret('Please enter a password to login'));
- $name = $this->ask('Please enter a name to display');
- $user = new $userModel(compact('username', 'password', 'name'));
+ $userModel=config('admin.database.users_model');
+ $username=$this->ask('Please enter a username to login');
+ $password=bcrypt($this->secret('Please enter a password to login'));
+ $name=$this->ask('Please enter a name to display');
+ $user=new $userModel(compact('username', 'password', 'name'));
$user->save();
$this->info("Admin User [$name] created successfully.");
}
diff --git a/app/Console/Commands/Manage/Permission.php b/app/Console/Commands/Manage/Permission.php
new file mode 100644
index 000000000..a89ccdd9e
--- /dev/null
+++ b/app/Console/Commands/Manage/Permission.php
@@ -0,0 +1,126 @@
+option('uid');
+ $permission_id=$this->option('permission');
+ $action=$this->option('action');
+
+ if (!in_array($action, ['list', 'grant', 'revoke'])) {
+ $this->line("\n Exception > : Unknown Action>\n");
+ return;
+ }
+
+ if ($action=='list') {
+ $this->listPermission();
+ return;
+ }
+
+ $userInfo=User::find($uid);
+ if (is_null($userInfo)) {
+ $this->line("\n Exception > : User Not Found>\n");
+ return;
+ }
+
+ if (!isset(UserPermission::$permInfo[$permission_id])) {
+ $this->line("\n Exception > : Unknown Permission>\n");
+ return;
+ }
+ $permissionInfo=UserPermission::$permInfo[$permission_id];
+
+ if ($action=='grant') {
+ $this->grantPermission($uid, $permission_id, $permissionInfo);
+ } else {
+ $this->revokePermission($uid, $permission_id, $permissionInfo);
+ }
+ }
+
+ protected function listPermission()
+ {
+ $headers=['ID', 'Permission'];
+ $permInfo=[];
+ foreach (UserPermission::$permInfo as $permID=>$permDesc) {
+ $permInfo[]=[$permID, $permDesc];
+ }
+ $this->table($headers, $permInfo);
+ }
+
+ protected function grantPermission($uid, $permission_id, $permissionInfo)
+ {
+ $this->line("Granting: >$permissionInfo");
+
+ $permissionExists=UserPermission::where([
+ 'user_id' => $uid,
+ 'permission_id' => $permission_id,
+ ])->count();
+
+ if (!$permissionExists) {
+ UserPermission::create([
+ 'user_id' => $uid,
+ 'permission_id' => $permission_id,
+ ]);
+ }
+
+ $this->line("Granted: >$permissionInfo");
+ }
+
+ protected function revokePermission($uid, $permission_id, $permissionInfo)
+ {
+ $this->line("Revoking: >$permissionInfo");
+
+ $permissionExists=UserPermission::where([
+ 'user_id' => $uid,
+ 'permission_id' => $permission_id,
+ ])->count();
+
+ if ($permissionExists) {
+ UserPermission::where([
+ 'user_id' => $uid,
+ 'permission_id' => $permission_id,
+ ])->delete();
+ }
+
+ $this->line("Revoked: >$permissionInfo");
+ }
+}
diff --git a/app/Console/Commands/Manage/ResetPass.php b/app/Console/Commands/Manage/ResetPass.php
index 13cd9c155..63c0cd014 100644
--- a/app/Console/Commands/Manage/ResetPass.php
+++ b/app/Console/Commands/Manage/ResetPass.php
@@ -4,9 +4,8 @@
use Illuminate\Console\Command;
use Exception;
-use function GuzzleHttp\json_decode;
use Symfony\Component\Console\Output\BufferedOutput;
-use App\Models\UserModel;
+use App\Models\Eloquent\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
@@ -17,14 +16,14 @@ class ResetPass extends Command
*
* @var string
*/
- protected $signature = 'manage:resetpass {--uid=: the user you want to reset} {--digit=: the number of the password, should be larger than 8}';
+ protected $signature='manage:resetpass {--uid= : the user you want to reset} {--digit= : the number of the password, should be larger than 8}';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Reset user passwords of NOJ';
+ protected $description='Reset user passwords of NOJ';
/**
* Create a new command instance.
@@ -45,7 +44,7 @@ public function handle()
{
$uid=$this->option('uid');
$digit=intval($this->option('digit'));
- $userInfo=UserModel::find($uid);
+ $userInfo=User::find($uid);
if (is_null($userInfo)) {
$this->line("\n Exception > : User Not Found>\n");
return;
diff --git a/app/Console/Commands/upgrade.php b/app/Console/Commands/upgrade.php
index db956ef92..29b1171b9 100644
--- a/app/Console/Commands/upgrade.php
+++ b/app/Console/Commands/upgrade.php
@@ -11,14 +11,14 @@ class upgrade extends Command
*
* @var string
*/
- protected $signature = 'upgrade';
+ protected $signature='upgrade';
/**
* The console command description.
*
* @var string
*/
- protected $description = 'Upgrade to the Latest of NOJ';
+ protected $description='Upgrade to the Latest of NOJ';
/**
* Create a new command instance.
@@ -37,7 +37,7 @@ public function __construct()
*/
public function handle()
{
- $bar = $this->output->createProgressBar(8);
+ $bar=$this->output->createProgressBar(8);
$bar->setFormat("%current%/%max% [%bar%] %percent:3s%%\n%message%");
$bar->setMessage("Enable Maintenance Mode.");
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index 52db78c68..8f0debd86 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -4,7 +4,7 @@
use Illuminate\Console\Scheduling\Schedule;
use App\Babel\Babel;
-use App\Models\Eloquent\JudgeServerModel as EloquentJudgeServerModel;
+use App\Models\Eloquent\JudgeServer as EloquentJudgeServerModel;
use App\Models\RankModel;
use App\Models\SiteMapModel;
use App\Models\ContestModel;
@@ -34,44 +34,36 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
- $schedule->call(function () {
- $babel=new Babel();
- for ($i=1; $i<=12; $i++) {
- $babel->judge();
- sleep(5);
- }
- // file_put_contents(storage_path('app/task-schedule.output'),"Successfully Synced Judger");
- })->everyMinute()->description("Sync Judger");
- $schedule->call(function () {
+ $schedule->call(function() {
$rankModel=new RankModel();
$rankModel->rankList();
// file_put_contents(storage_path('app/task-schedule.output'),"Successfully Updated Rank");
})->dailyAt('02:00')->description("Update Rank");
- $schedule->call(function () {
+ $schedule->call(function() {
$siteMapModel=new SiteMapModel();
// file_put_contents(storage_path('app/task-schedule.output'),"Successfully Updated SiteMap");
})->dailyAt('02:00')->description("Update SiteMap");
- $schedule->call(function () {
+ $schedule->call(function() {
$groupModel=new GroupModel();
$groupModel->cacheTrendingGroups();
// file_put_contents(storage_path('app/task-schedule.output'),"Successfully Cached Trending Groups");
})->dailyAt('03:00')->description("Update Trending Groups");
$schedule->call(function() {
- $groupModel = new GroupModel();
- $ret = $groupModel->refreshAllElo();
+ $groupModel=new GroupModel();
+ $ret=$groupModel->refreshAllElo();
foreach ($ret as $gid => $group) {
- if(empty($group['result'])){
+ if (empty($group['result'])) {
Log::channel('group_elo')->info('Refreshed Group Elo (Empty) : ('.$gid.')'.$group['name']);
- }else{
+ } else {
Log::channel('group_elo')->info('Refreshing Group Elo: ('.$gid.')'.$group['name']);
foreach ($group['result'] as $contest) {
- if($contest['ret'] == 'success'){
+ if ($contest['ret']=='success') {
Log::channel('group_elo')->info(' Elo Clac Successfully : ('.$contest['cid'].')'.$contest['name']);
- }else{
+ } else {
Log::channel('group_elo')->info(' Elo Clac Faild (Judge Not Over) : ('.$contest['cid'].')'.$contest['name'].' sids:');
foreach ($contest['submissions'] as $sid) {
Log::channel('group_elo')->info(' '.$sid['sid']);
@@ -82,46 +74,46 @@ protected function schedule(Schedule $schedule)
}
})->dailyAt('04:00')->description("Update Group Elo");
- $schedule->call(function () {
- $contestModel = new ContestModel();
- $syncList = $contestModel->runningContest();
+ $schedule->call(function() {
+ $contestModel=new ContestModel();
+ $syncList=$contestModel->runningContest();
foreach ($syncList as $syncContest) {
if (!isset($syncContest['vcid'])) {
- $contest = EloquentContestModel::find($syncContest['cid']);
- $contestRankRaw = $contest->rankRefresh();
+ $contest=EloquentContestModel::find($syncContest['cid']);
+ $contestRankRaw=$contest->rankRefresh();
$cid=$syncContest['cid'];
Cache::tags(['contest', 'rank'])->put($cid, $contestRankRaw);
Cache::tags(['contest', 'rank'])->put("contestAdmin$cid", $contestRankRaw);
- continue ;
+ continue;
}
- $className = "App\\Babel\\Extension\\hdu\\Synchronizer"; // TODO Add OJ judgement.
- $all_data = [
+ $className="App\\Babel\\Extension\\hdu\\Synchronizer"; // TODO Add OJ judgement.
+ $all_data=[
'oj'=>"hdu",
'vcid'=>$syncContest['vcid'],
'gid'=>$syncContest['gid'],
'cid'=>$syncContest['cid'],
];
- $hduSync = new $className($all_data);
+ $hduSync=new $className($all_data);
$hduSync->crawlRank();
$hduSync->crawlClarification();
}
// file_put_contents(storage_path('app/task-schedule.output'),"Successfully Synced Remote Rank and Clarification");
})->everyMinute()->description("Sync Remote Rank and Clarification");
- $schedule->call(function () {
- $contestModel = new ContestModel();
- $syncList = $contestModel->runningContest();
+ $schedule->call(function() {
+ $contestModel=new ContestModel();
+ $syncList=$contestModel->runningContest();
foreach ($syncList as $syncContest) {
if (isset($syncContest['crawled'])) {
if (!$syncContest['crawled']) {
- $className = "App\\Babel\\Extension\\hdu\\Synchronizer";
- $all_data = [
+ $className="App\\Babel\\Extension\\hdu\\Synchronizer";
+ $all_data=[
'oj'=>"hdu",
'vcid'=>$syncContest['vcid'],
'gid'=>$syncContest['gid'],
'cid'=>$syncContest['cid'],
];
- $hduSync = new $className($all_data);
+ $hduSync=new $className($all_data);
$hduSync->scheduleCrawl();
$contestModel->updateCrawlStatus($syncContest['cid']);
}
@@ -129,7 +121,7 @@ protected function schedule(Schedule $schedule)
}
})->everyMinute()->description("Sync Contest Problem");
- $schedule->call(function () {
+ $schedule->call(function() {
$oidList=EloquentJudgeServerModel::column('oid');
$babel=new Babel();
foreach ($oidList as $oid) {
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 4d819c700..b831a26b7 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -46,7 +46,7 @@ public function report(Exception $exception)
*/
public function render($request, Exception $exception)
{
- if(!env("APP_DEBUG") && $request->is('api/*')) {
+ if (!env("APP_DEBUG") && $request->is('api/*')) {
return response(json_encode([
'success' => false,
'message' => 'Server Error',
@@ -56,7 +56,7 @@ public function render($request, Exception $exception)
'msg' => 'Server Error',
'data'=>[]
]
- ]),500)->header('Content-Type','application/json');
+ ]), 500)->header('Content-Type', 'application/json');
};
return parent::render($request, $exception);
}
diff --git a/app/Exports/AccountExport.php b/app/Exports/AccountExport.php
index 432fee0b3..35895cc5e 100644
--- a/app/Exports/AccountExport.php
+++ b/app/Exports/AccountExport.php
@@ -11,7 +11,7 @@ class AccountExport implements FromArray, WithHeadings
public function __construct(array $data)
{
- $this->data = $data;
+ $this->data=$data;
}
public function array(): array
diff --git a/app/Exports/GroupAnalysisExport.php b/app/Exports/GroupAnalysisExport.php
index 9fcc5e4b6..cfe305d8d 100644
--- a/app/Exports/GroupAnalysisExport.php
+++ b/app/Exports/GroupAnalysisExport.php
@@ -16,27 +16,27 @@ class GroupAnalysisExport implements FromCollection, WithEvents, WithStrictNullC
private $member_data;
private $config;
- public function __construct($data, $config = [])
+ public function __construct($data, $config=[])
{
- if ($config['mode'] == 'contest') {
- $this->contest_data = $data['contest_data'];
- $this->member_data = $data['member_data'];
+ if ($config['mode']=='contest') {
+ $this->contest_data=$data['contest_data'];
+ $this->member_data=$data['member_data'];
} else {
- $this->member_data = $data['member_data'];
- $this->tag_problems = $data['tag_problems'];
+ $this->member_data=$data['member_data'];
+ $this->tag_problems=$data['tag_problems'];
}
- $this->config = $config;
+ $this->config=$config;
}
/**
- * @return array
- */
+ * @return array
+ */
public function registerEvents(): array
{
return [
- AfterSheet::class => function (AfterSheet $event) {
- if ($this->config['mode'] === 'contest') {
- $mergeCell = ['A1:A2','B1:E1'];
+ AfterSheet::class => function(AfterSheet $event) {
+ if ($this->config['mode']==='contest') {
+ $mergeCell=['A1:A2', 'B1:E1'];
foreach ($this->contest_data as $c) {
array_push($mergeCell, $this->mergeCellColumnNext());
}
@@ -47,50 +47,50 @@ public function registerEvents(): array
}
/**
- * @return \Illuminate\Support\Collection
- */
+ * @return \Illuminate\Support\Collection
+ */
public function collection()
{
- $maxium = $this->config['maxium'] ?? false;
- $percent = $this->config['percent'] ?? false;
+ $maxium=$this->config['maxium'] ?? false;
+ $percent=$this->config['percent'] ?? false;
- if ($this->config['mode'] == 'contest') {
- $row_1 = ['Member','Total','','',''];
- $row_2 = ['','Elo','Rank','Solved','Penalty'];
+ if ($this->config['mode']=='contest') {
+ $row_1=['Member', 'Total', '', '', ''];
+ $row_2=['', 'Elo', 'Rank', 'Solved', 'Penalty'];
foreach ($this->contest_data as $contest) {
- array_push($row_1, $contest['name'], '','');
- array_push($row_2, 'Rank','Solved', 'Penalty');
+ array_push($row_1, $contest['name'], '', '');
+ array_push($row_2, 'Rank', 'Solved', 'Penalty');
}
- $data = [$row_1,$row_2];
+ $data=[$row_1, $row_2];
foreach ($this->member_data as $member) {
- $display_name = $member['name'];
+ $display_name=$member['name'];
if (!empty($member['nick_name'])) {
- $display_name .= ' ('.$member['nick_name'].')';
+ $display_name.=' ('.$member['nick_name'].')';
}
- $row = [
+ $row=[
$display_name,
$member['elo'],
!empty($member['rank_ave']) ? round($member['rank_ave'], 1) : '-',
- $percent === 'true' ? ($member['problem_all'] != 0 ? round($member['solved_all'] / $member['problem_all'] * 100, 1) : '-'). ' %'
- : ($maxium === 'true' ? $member['solved_all'] . ' / ' . $member['problem_all'] : $member['solved_all']),
+ $percent==='true' ? ($member['problem_all']!=0 ? round($member['solved_all'] / $member['problem_all'] * 100, 1) : '-').' %'
+ : ($maxium==='true' ? $member['solved_all'].' / '.$member['problem_all'] : $member['solved_all']),
round($member['penalty']),
];
foreach ($this->contest_data as $contest) {
if (in_array($contest['cid'], array_keys($member['contest_detial']))) {
- $contest_detial = $member['contest_detial'][$contest['cid']];
+ $contest_detial=$member['contest_detial'][$contest['cid']];
array_push(
$row,
$contest_detial['rank'],
- $percent === 'true' ? (round($contest_detial['solved'] / $contest_detial['problems'] * 100, 1) . ' %')
- : ($maxium === 'true' ? $contest_detial['solved'].' / '.$contest_detial['problems'] : $contest_detial['solved']),
+ $percent==='true' ? (round($contest_detial['solved'] / $contest_detial['problems'] * 100, 1).' %')
+ : ($maxium==='true' ? $contest_detial['solved'].' / '.$contest_detial['problems'] : $contest_detial['solved']),
round($contest_detial['penalty'])
);
} else {
array_push(
$row,
'-',
- $percent === 'true' ? '- %'
- : ($maxium === 'true' ? '- / -' : ' - '),
+ $percent==='true' ? '- %'
+ : ($maxium==='true' ? '- / -' : ' - '),
0
);
}
@@ -98,27 +98,27 @@ public function collection()
array_push($data, $row);
}
} else {
- $row_1 = ['Member'];
- $row_2 = [''];
+ $row_1=['Member'];
+ $row_2=[''];
foreach ($this->tag_problems as $tag => $tag_problem_set) {
array_push($row_1, $tag);
array_push($row_2, 'Solved');
}
- $data = [$row_1,$row_2];
+ $data=[$row_1, $row_2];
foreach ($this->member_data as $member) {
- $display_name = $member['name'];
+ $display_name=$member['name'];
if (!empty($member['nick_name'])) {
- $display_name .= ' ('.$member['nick_name'].')';
+ $display_name.=' ('.$member['nick_name'].')';
}
- $row = [
+ $row=[
$display_name,
];
foreach ($member['completion'] as $tag => $tag_completion) {
- $count = count($tag_completion);
- $solved = eval('return '.join('+', array_values($tag_completion)).';');
+ $count=count($tag_completion);
+ $solved=eval('return '.join('+', array_values($tag_completion)).';');
array_push(
$row,
- $percent === 'true' ? (round($solved / $count * 100, 1) . ' %') : ($maxium === 'true' ? $solved .' / '.$count : $solved)
+ $percent==='true' ? (round($solved / $count * 100, 1).' %') : ($maxium==='true' ? $solved.' / '.$count : $solved)
);
}
array_push($data, $row);
@@ -129,33 +129,33 @@ public function collection()
private function mergeCellColumnNext()
{
- static $columns = [
- [2],[4]
+ static $columns=[
+ [2], [4]
];
- $columns_str = ['',''];
- $chars = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
+ $columns_str=['', ''];
+ $chars=str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
foreach ($columns as $key => &$column) {
- $column[0] += 3;
- if ($column[0] > 25) {
+ $column[0]+=3;
+ if ($column[0]>25) {
if (isset($column[1])) {
- $column[1] += 1;
- if ($column[1] > 25) {
+ $column[1]+=1;
+ if ($column[1]>25) {
if (isset($column[2])) {
- $column[2] += 1;
+ $column[2]+=1;
} else {
- $column[2] = 0;
+ $column[2]=0;
}
}
} else {
- $column[1] = 0;
+ $column[1]=0;
}
}
- $columns_str[$key] = '';
- $reverse_column = array_reverse($column);
+ $columns_str[$key]='';
+ $reverse_column=array_reverse($column);
foreach ($reverse_column as $ord) {
- $columns_str[$key] .= $chars[$ord];
+ $columns_str[$key].=$chars[$ord];
}
- $columns_str[$key] .= '1';
+ $columns_str[$key].='1';
}
return $columns_str[0].':'.$columns_str[1];
}
diff --git a/app/Helpers/functions.php b/app/Helpers/functions.php
index 953801d39..0f732225f 100644
--- a/app/Helpers/functions.php
+++ b/app/Helpers/functions.php
@@ -26,6 +26,8 @@
use GrahamCampbell\Markdown\Facades\Markdown;
use App\Models\Eloquent\Message;
use App\Models\Latex\LatexModel;
+use App\Models\Eloquent\Tool\Theme;
+use App\Models\Eloquent\Tool\AppSettings;
if (!function_exists('version')) {
function version()
@@ -64,20 +66,20 @@ function emailVerified()
}
}
-if (! function_exists('babel_path')) {
+if (!function_exists('babel_path')) {
/**
* Get the path to the application folder.
*
* @param string $path
* @return string
*/
- function babel_path($path = '')
+ function babel_path($path='')
{
return app('path').DIRECTORY_SEPARATOR.'Babel'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
}
-if (! function_exists('glob_recursive')) {
+if (!function_exists('glob_recursive')) {
/**
* Find pathnames matching a pattern recursively.
*
@@ -85,11 +87,11 @@ function babel_path($path = '')
* @param int $flags Valid flags: GLOB_MARK
* @return array|false an array containing the matched files/directories, an empty array if no file matched or false on error.
*/
- function glob_recursive($pattern, $flags = 0)
+ function glob_recursive($pattern, $flags=0)
{
- $files = glob($pattern, $flags);
- foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
- $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
+ $files=glob($pattern, $flags);
+ foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
+ $files=array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
@@ -123,8 +125,8 @@ function getOpenSearchXML()
function delFile($dirName)
{
if (file_exists($dirName) && $handle=opendir($dirName)) {
- while (false!==($item = readdir($handle))) {
- if ($item!= "." && $item != "..") {
+ while (false!==($item=readdir($handle))) {
+ if ($item!="." && $item!="..") {
if (file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)) {
delFile($dirName.'/'.$item);
} else {
@@ -142,7 +144,7 @@ function delFile($dirName)
if (!function_exists('convertMarkdownToHtml')) {
function convertMarkdownToHtml($md)
{
- return is_string($md)?Markdown::convertToHtml($md):'';
+ return is_string($md) ?Markdown::convertToHtml($md) : '';
}
}
@@ -186,7 +188,7 @@ function formatHumanReadableTime($date)
$periods[$j]=__("helper.time.singular.$periods[$j]");
}
- return __("helper.time.formatter",[
+ return __("helper.time.formatter", [
"time" => $difference,
"unit" => $periods[$j],
"tense" => $tense,
@@ -211,18 +213,53 @@ function formatProblemSolvedTime($seconds)
if (!function_exists('latex2Image')) {
function latex2Image($content)
{
- $callback = function ($matches) use (&$patch, &$display) {
- [$url,$width,$height]=LatexModel::info("$patch$matches[1]$patch");
+ $callback=function($matches) use (&$patch, &$display) {
+ [$url, $width, $height]=LatexModel::info("$patch$matches[1]$patch");
return "";
};
- $patch = '$';
- $display = 'inline-block';
- $content = preg_replace_callback('/\\$\\$\\$(.*?)\\$\\$\\$/', $callback, $content);
- $content = preg_replace_callback('/\\\\\\((.*?)\\\\\\)/', $callback, $content);
- $patch = '$$';
- $display = 'block';
- $content = preg_replace_callback('/\\$\\$(.*?)\\$\\$/', $callback, $content);
- $content = preg_replace_callback('/\\\\\\[(.*?)\\\\\\]/', $callback, $content);
+ $patch='$';
+ $display='inline-block';
+ $content=preg_replace_callback('/\\$\\$\\$(.*?)\\$\\$\\$/', $callback, $content);
+ $content=preg_replace_callback('/\\\\\\((.*?)\\\\\\)/', $callback, $content);
+ $patch='$$';
+ $display='block';
+ $content=preg_replace_callback('/\\$\\$(.*?)\\$\\$/', $callback, $content);
+ $content=preg_replace_callback('/\\\\\\[(.*?)\\\\\\]/', $callback, $content);
return $content;
}
}
+
+if (!function_exists('vscodeLocale')) {
+ function vscodeLocale()
+ {
+ $locale=Str::lower(App::getLocale());
+ $vscodelocale='';
+ if (in_array($locale, ['de', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'zh-cn', 'zh-tw'])) {
+ $vscodelocale=$locale;
+ }
+ return $vscodelocale;
+ }
+}
+
+if (!function_exists('getTheme')) {
+ function getTheme($id=null)
+ {
+ if (is_null($id)) {
+ $id=config('app.theme');
+ }
+ return Theme::getTheme($id);
+ }
+}
+
+if (!function_exists('setting')) {
+ function setting($identifier, $default=null)
+ {
+ if (is_array($identifier)) {
+ foreach ($identifier as $key=>$content) {
+ AppSettings::set($key, $content);
+ }
+ return true;
+ }
+ return AppSettings::get($identifier, $default);
+ }
+}
diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php
index 10d142a20..cf87c3750 100644
--- a/app/Http/Controllers/AccountController.php
+++ b/app/Http/Controllers/AccountController.php
@@ -4,6 +4,8 @@
use Illuminate\Http\Request;
use App\Models\AccountModel;
+use App\Models\Eloquent\UserExtra;
+use App\Models\Eloquent\Tool\Socialite;
use Auth;
class AccountController extends Controller
@@ -28,8 +30,8 @@ public function dashboard()
$accountModel=new AccountModel();
$info=$accountModel->detail(Auth::user()->id);
$feed=$accountModel->feed(Auth::user()->id);
- $extraInfo = $accountModel->getExtra(Auth::user()->id, ['gender', 'contanct', 'school', 'country', 'location'],100);
- $socialiteInfo = $accountModel->getSocialiteInfo(Auth::user()->id,100);
+ $extraInfo=Auth::user()->getExtra(['gender', 'contact', 'school', 'country', 'location'], 100);
+ $socialiteInfo=Auth::user()->getSocialiteInfo(100);
return view("account.dashboard", [
'page_title'=>"DashBoard",
'site_title'=>config("app.name"),
@@ -39,7 +41,9 @@ public function dashboard()
'settingsView' => false,
'feed'=>$feed,
'extra_info' => $extraInfo,
+ 'extraDict' => UserExtra::$extraDict,
'socialite_info' => $socialiteInfo,
+ 'socialites' => Socialite::getAvailable(),
]);
}
@@ -52,11 +56,11 @@ public function settings()
{
$accountModel=new AccountModel();
$info=$accountModel->detail(Auth::user()->id);
- if(!empty(session('last_email_send'))){
- $email_cooldown = 300 - (time() - session('last_email_send'));
+ if (!empty(session('last_email_send'))) {
+ $email_cooldown=300-(time()-session('last_email_send'));
}
- $extraInfo = $accountModel->getExtra(Auth::user()->id, ['gender', 'contanct', 'school', 'country', 'location'],100);
- $socialiteInfo = $accountModel->getSocialiteInfo(Auth::user()->id,100);
+ $extraInfo=Auth::user()->getExtra(['gender', 'contact', 'school', 'country', 'location'], 100);
+ $socialiteInfo=Auth::user()->getSocialiteInfo(100);
return view("account.dashboard", [
'page_title'=>"Settings",
'site_title'=>config("app.name"),
@@ -66,7 +70,9 @@ public function settings()
'settingsView' => true,
'email_cooldown' => $email_cooldown ?? null,
'extra_info' => $extraInfo,
+ 'extraDict' => UserExtra::$extraDict,
'socialite_info' => $socialiteInfo,
+ 'socialites' => Socialite::getAvailable(),
]);
}
}
diff --git a/app/Http/Controllers/Ajax/AbuseController.php b/app/Http/Controllers/Ajax/AbuseController.php
index 702aa8299..3a4ef4914 100644
--- a/app/Http/Controllers/Ajax/AbuseController.php
+++ b/app/Http/Controllers/Ajax/AbuseController.php
@@ -17,8 +17,8 @@ class AbuseController extends Controller
{
protected static $cause=[];
- public static function findCause($causeDesc){
- if(empty($cause)){
+ public static function findCause($causeDesc) {
+ if (empty($cause)) {
self::$cause=array_flip(Abuse::$cause);
}
$causeID=Arr::get(self::$cause, $causeDesc, 0);
@@ -34,24 +34,24 @@ public function report(Request $request)
"subject_id" => "required|integer"
]);
$category2link=[
- 'group'=>function($id){
- return route('group.detail',['gcode'=>Group::findOrFail($id)->gcode]);
+ 'group'=>function($id) {
+ return route('group.detail', ['gcode'=>Group::findOrFail($id)->gcode]);
},
- 'user'=>function($id){
- return route('user.view',['uid' => $id]);
+ 'user'=>function($id) {
+ return route('user.view', ['uid' => $id]);
}
];
- $supplement = $request->input('supplement');
- $category = $request->input('category');
- $subject_id = $request->input('subject_id');
+ $supplement=$request->input('supplement');
+ $category=$request->input('category');
+ $subject_id=$request->input('subject_id');
try {
- $link = $category2link[$category]($subject_id);
- } catch(Throwable $e){
+ $link=$category2link[$category]($subject_id);
+ } catch (Throwable $e) {
return ResponseModel::err(9001);
}
- $uid = Auth::user()->id;
- [$causeID, $causeDesc] = self::findCause('General');
- $abuseRecord = Abuse::create([
+ $uid=Auth::user()->id;
+ [$causeID, $causeDesc]=self::findCause('General');
+ $abuseRecord=Abuse::create([
'title' => Str::title($category)." #$subject_id Abused - $causeDesc",
'category' => array_search($category, Abuse::$supportCategory),
'cause' => $causeID,
diff --git a/app/Http/Controllers/Ajax/AccountController.php b/app/Http/Controllers/Ajax/AccountController.php
index 9566babb2..2bab665a4 100644
--- a/app/Http/Controllers/Ajax/AccountController.php
+++ b/app/Http/Controllers/Ajax/AccountController.php
@@ -4,19 +4,18 @@
use App\Http\Controllers\Controller;
use App\Models\ResponseModel;
-use App\Models\UserModel;
-use App\Models\AccountModel;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
+use Illuminate\Validation\Rule;
use Auth;
class AccountController extends Controller
{
- public function updateAvatar(Request $request){
+ public function updateAvatar(Request $request) {
$isValid=$request->file('avatar')->isValid();
if ($isValid) {
$extension=$request->file('avatar')->extension();
@@ -43,94 +42,110 @@ public function updateAvatar(Request $request){
}
}
- public function changeBasicInfo(Request $request){
- // if(!$request->has('username')){
- // return ResponseModel::err(1003);
- // }
- // $username = $request->input('username');
- $describes = $request->input('describes');
- if(strlen($describes) > 255){
- return ResponseModel::err(1006);
- }
- // $old_username=Auth::user()->name;
- // if($old_username != $username && !empty(UserModel::where('name',$username)->first())){
- // return ResponseModel::err(2003);
- // }
+ public function changeBasicInfo(Request $request) {
+ $request->validate([
+ "username" => [
+ "required",
+ "string",
+ "max:16",
+ "min:1",
+ Rule::unique('users', 'name')->ignore(Auth::user()->id)
+ ],
+ "describes" => "required|string|max:255"
+ ]);
+ $username=$request->input('username');
+ $describes=$request->input('describes');
$user=Auth::user();
- // $user->name = $username;
- $user->describes = $describes;
+ if (!Auth::user()->contest_account) {
+ $user->name=$username;
+ }
+ $user->describes=$describes;
$user->save();
return ResponseModel::success();
}
- public function changePassword(Request $request){
- if(!$request->has('old_password') || !$request->has('new_password') || !$request->has('confirm_password')){
+ public function changePassword(Request $request) {
+ if (!$request->has('old_password') || !$request->has('new_password') || !$request->has('confirm_password')) {
return ResponseModel::err(1003);
}
- $old_password = $request->input('old_password');
- $new_password = $request->input('new_password');
- $confirm_password = $request->input('confirm_password');
- if($new_password != $confirm_password){
+ $old_password=$request->input('old_password');
+ $new_password=$request->input('new_password');
+ $confirm_password=$request->input('confirm_password');
+ if ($new_password!=$confirm_password) {
return ResponseModel::err(2004);
}
- if(strlen($new_password) < 8 || strlen($old_password) < 8){
+ if (strlen($new_password)<8 || strlen($old_password)<8) {
return ResponseModel::err(1006);
}
- $user = Auth::user();
- if(!Hash::check($old_password, $user->password)){
+ $user=Auth::user();
+ if ($user->hasIndependentPassword() && !Hash::check($old_password, $user->password)) {
return ResponseModel::err(2005);
}
- $user->password = Hash::make($new_password);
+ $user->password=Hash::make($new_password);
$user->save();
return ResponseModel::success();
}
- public function checkEmailCooldown(Request $request){
- $last_send = $request->session()->get('last_email_send');
- if(empty($last_send) || time() - $last_send >= 300){
- $request->session()->put('last_email_send',time());
- return ResponseModel::success(200,null,0);
- }else{
- $cooldown = 300 - (time() - $last_send);
- return ResponseModel::success(200,null,$cooldown);
+ public function checkEmailCooldown(Request $request) {
+ $last_send=$request->session()->get('last_email_send');
+ if (empty($last_send) || time()-$last_send>=300) {
+ $request->session()->put('last_email_send', time());
+ return ResponseModel::success(200, null, 0);
+ } else {
+ $cooldown=300-(time()-$last_send);
+ return ResponseModel::success(200, null, $cooldown);
}
}
- public function changeExtraInfo(Request $request){
- $input = $request->input();
- $allow_change = ['gender','contact','school','country','location'];
- foreach($input as $key => $value){
- if(!in_array($key,$allow_change)){
+ public function changeExtraInfo(Request $request) {
+ $input=$request->input();
+ $allow_change=['gender', 'contact', 'school', 'country', 'location'];
+ foreach ($input as $key => $value) {
+ if (!in_array($key, $allow_change)) {
return ResponseModel::error(1007);
}
}
- $account_model = new AccountModel();
- $user_id = Auth::user()->id;
foreach ($input as $key => $value) {
- if(strlen($value) != 0){
- $account_model->setExtra($user_id,$key,$value,0);
- }else{
- $account_model->setExtra($user_id,$key,null);
+ if (strlen($value)!=0) {
+ Auth::user()->setExtra($key, $value, 0);
+ } else {
+ Auth::user()->setExtra($key, null);
}
}
return ResponseModel::success();
}
- public function saveEditorWidth(Request $request){
- $input = $request->input();
- $allow_change = ['editor_left_width'];
- foreach($input as $key => $value){
- if(!in_array($key,$allow_change)){
+ public function saveEditorWidth(Request $request) {
+ $input=$request->input();
+ $allow_change=['editor_left_width'];
+ foreach ($input as $key => $value) {
+ if (!in_array($key, $allow_change)) {
+ return ResponseModel::error(1007);
+ }
+ }
+ foreach ($input as $key => $value) {
+ if (strlen($value)!=0) {
+ Auth::user()->setExtra($key, $value, 0);
+ } else {
+ Auth::user()->setExtra($key, null);
+ }
+ }
+ return ResponseModel::success();
+ }
+
+ public function saveEditorTheme(Request $request) {
+ $input=$request->input();
+ $allow_change=['editor_theme'];
+ foreach ($input as $key => $value) {
+ if (!in_array($key, $allow_change)) {
return ResponseModel::error(1007);
}
}
- $account_model = new AccountModel();
- $user_id = Auth::user()->id;
foreach ($input as $key => $value) {
- if(strlen($value) != 0){
- $account_model->setExtra($user_id,$key,$value,0);
- }else{
- $account_model->setExtra($user_id,$key,null);
+ if (strlen($value)!=0) {
+ Auth::user()->setExtra($key, $value, 0);
+ } else {
+ Auth::user()->setExtra($key, null);
}
}
return ResponseModel::success();
diff --git a/app/Http/Controllers/Ajax/ContestAdminController.php b/app/Http/Controllers/Ajax/ContestAdminController.php
index ed59080d3..d94093262 100644
--- a/app/Http/Controllers/Ajax/ContestAdminController.php
+++ b/app/Http/Controllers/Ajax/ContestAdminController.php
@@ -27,22 +27,22 @@ public function assignMember(Request $request)
'cid' => 'required|integer',
'uid' => 'required|integer'
]);
- $cid = $request->input('cid');
- $uid = $request->input('uid');
+ $cid=$request->input('cid');
+ $uid=$request->input('uid');
- $groupModel = new GroupModel();
- $contestModel = new ContestModel();
+ $groupModel=new GroupModel();
+ $contestModel=new ContestModel();
- $contest_info = $contestModel->basic($cid);
- if($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ $contest_info=$contestModel->basic($cid);
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
- if($groupModel->judgeClearance($contest_info['gid'],$uid) < 2){
+ if ($groupModel->judgeClearance($contest_info['gid'], $uid)<2) {
return ResponseModel::err(7004);
}
- $contestModel->assignMember($cid,$uid);
+ $contestModel->assignMember($cid, $uid);
return ResponseModel::success(200);
}
@@ -51,30 +51,30 @@ public function details(Request $request)
$request->validate([
'cid' => 'required|integer',
]);
- $cid = $request->input('cid');
+ $cid=$request->input('cid');
- $contestModel = new ContestModel();
- $groupModel = new GroupModel();
+ $contestModel=new ContestModel();
+ $groupModel=new GroupModel();
- $contest_problems = $contestModel->problems($cid);
- $contest_detail = $contestModel->basic($cid);
- $contest_detail['problems'] = $contest_problems;
- $assign_uid = $contest_detail['assign_uid'];
- $clearance = $contestModel->judgeClearance($cid,Auth::user()->id);
- if($clearance != 3){
+ $contest_problems=$contestModel->problems($cid);
+ $contest_detail=$contestModel->basic($cid);
+ $contest_detail['problems']=$contest_problems;
+ $assign_uid=$contest_detail['assign_uid'];
+ $clearance=$contestModel->judgeClearance($cid, Auth::user()->id);
+ if ($clearance!=3) {
return ResponseModel::err(2001);
}
- if($assign_uid != 0){
- $assignee = $groupModel->userProfile($assign_uid,$contest_detail['gid']);
- }else{
- $assignee = null;
+ if ($assign_uid!=0) {
+ $assignee=$groupModel->userProfile($assign_uid, $contest_detail['gid']);
+ } else {
+ $assignee=null;
}
- $ret = [
+ $ret=[
'contest_info' => $contest_detail,
'assignee' => $assignee,
- 'is_admin' => $clearance == 3,
+ 'is_admin' => $clearance==3,
];
- return ResponseModel::success(200,null,$ret);
+ return ResponseModel::success(200, null, $ret);
}
public function rejudge(Request $request)
@@ -109,15 +109,15 @@ public function update(Request $request)
'end_time' => 'required|date|after:begin_time',
'description' => 'string'
]);
- $all_data = $request->all();
- $cid = $all_data['cid'];
+ $all_data=$request->all();
+ $cid=$all_data['cid'];
- $contestModel = new ContestModel();
- if($contestModel->judgeClearance($all_data['cid'],Auth::user()->id) != 3){
+ $contestModel=new ContestModel();
+ if ($contestModel->judgeClearance($all_data['cid'], Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
- if($contestModel->remainingTime($cid) > 0){
+ if ($contestModel->remainingTime($cid)>0) {
$problems=explode(",", $all_data["problems"]);
if (count($problems)>26) {
return ResponseModel::err(4002);
@@ -134,32 +134,32 @@ public function update(Request $request)
];
}
}
- $allow_update = ['name','description','begin_time','end_time', 'status_visibility'];
+ $allow_update=['name', 'description', 'begin_time', 'end_time', 'status_visibility'];
- foreach($all_data as $key => $value){
- if(!in_array($key,$allow_update)){
+ foreach ($all_data as $key => $value) {
+ if (!in_array($key, $allow_update)) {
unset($all_data[$key]);
}
}
- $contestModel->contestUpdate($cid,$all_data,$problemSet);
+ $contestModel->contestUpdate($cid, $all_data, $problemSet);
return ResponseModel::success(200);
- }else{
- $allow_update = ['name','description'];
+ } else {
+ $allow_update=['name', 'description'];
- foreach($all_data as $key => $value){
- if(!in_array($key,$allow_update)){
+ foreach ($all_data as $key => $value) {
+ if (!in_array($key, $allow_update)) {
unset($all_data[$key]);
}
}
- $contestModel->contestUpdate($cid,$all_data,false);
- return ResponseModel::success(200,'
+ $contestModel->contestUpdate($cid, $all_data, false);
+ return ResponseModel::success(200, '
Successful! However, only the name and description of the match can be changed for the match that has been finished.
');
}
}
- public function issueAnnouncement(Request $request){
+ public function issueAnnouncement(Request $request) {
$request->validate([
'cid' => 'required|integer',
'title' => 'required|string|max:250',
@@ -179,7 +179,7 @@ public function issueAnnouncement(Request $request){
}
}
- public function replyClarification(Request $request){
+ public function replyClarification(Request $request) {
$request->validate([
'cid' => 'required|integer',
'ccid' => 'required|integer',
@@ -199,7 +199,7 @@ public function replyClarification(Request $request){
}
}
- public function setClarificationPublic(Request $request){
+ public function setClarificationPublic(Request $request) {
$request->validate([
'cid' => 'required|integer',
'ccid' => 'required|integer',
@@ -232,7 +232,7 @@ public function generateContestAccount(Request $request)
$groupModel=new GroupModel();
$contestModel=new ContestModel();
$verified=$contestModel->isVerified($all_data["cid"]);
- if(!$verified){
+ if (!$verified) {
return ResponseModel::err(2001);
}
$gid=$contestModel->gid($all_data["cid"]);
@@ -253,18 +253,18 @@ public function getScrollBoardData(Request $request)
$request->validate([
'cid' => 'required|integer',
]);
- $cid = $request->input('cid');
- $contestModel = new ContestModel();
- if($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ $cid=$request->input('cid');
+ $contestModel=new ContestModel();
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
- if($contestModel->remainingTime($cid) >= 0){
+ if ($contestModel->remainingTime($cid)>=0) {
return ResponseModel::err(4008);
}
- if($contestModel->basic($cid)['froze_length'] == 0){
+ if ($contestModel->basic($cid)['froze_length']==0) {
return ResponseModel::err(4009);
}
- $data = $contestModel->getScrollBoardData($cid);
+ $data=$contestModel->getScrollBoardData($cid);
return ResponseModel::success(200, null, $data);
}
@@ -273,20 +273,20 @@ public function downloadCode(Request $request)
$request->validate([
"cid"=>"required|integer",
]);
- $cid = $request->input('cid');
+ $cid=$request->input('cid');
$groupModel=new GroupModel();
$contestModel=new ContestModel();
- if($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
$zip_name=$contestModel->zipName($cid);
- if(!(Storage::disk("private")->exists("contestCodeZip/$cid/".$cid.".zip"))){
- $contestModel->GenerateZip("contestCodeZip/$cid/",$cid,"contestCode/$cid/",$zip_name);
+ if (!(Storage::disk("private")->exists("contestCodeZip/$cid/".$cid.".zip"))) {
+ $contestModel->GenerateZip("contestCodeZip/$cid/", $cid, "contestCode/$cid/", $zip_name);
}
$files=Storage::disk("private")->files("contestCodeZip/$cid/");
- response()->download(base_path("/storage/app/private/".$files[0]),$zip_name,[
+ response()->download(base_path("/storage/app/private/".$files[0]), $zip_name, [
"Content-Transfer-Encoding" => "binary",
"Content-Type"=>"application/octet-stream",
"filename"=>$zip_name
@@ -299,15 +299,15 @@ public function downloadPlagiarismReport(Request $request)
$request->validate([
"cid"=>"required|integer",
]);
- $cid = $request->input('cid');
+ $cid=$request->input('cid');
$contestModel=new ContestModel();
- if($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
$name=$contestModel->basic($cid)["name"];
- return response()->download(storage_path("app/contest/anticheat/$cid/report/report.zip"), "$name Code Plagiarism.zip");
+ return response()->download(storage_path("app/contest/anticheat/$cid/report/report.zip"), __("contest.inside.admin.anticheat.downloadFile", ["name" => $name]).".zip");
}
public function generatePDF(Request $request)
@@ -317,17 +317,19 @@ public function generatePDF(Request $request)
"config.cover"=>"required",
"config.advice"=>"required",
]);
- $cid = $request->input('cid');
- $config = [
+ $cid=$request->input('cid');
+ $config=[
'cover'=>$request->input('config.cover')=='true',
'advice'=>$request->input('config.advice')=='true'
];
$contestModel=new ContestModel();
- if ($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
- if(!is_null(Cache::tags(['contest', 'admin', 'PDFGenerate'])->get($cid))) return ResponseModel::err(8001);
- $generateProcess=new GeneratePDF($cid,$config);
+ if (!is_null(Cache::tags(['contest', 'admin', 'PDFGenerate'])->get($cid))) {
+ return ResponseModel::err(8001);
+ }
+ $generateProcess=new GeneratePDF($cid, $config);
dispatch($generateProcess)->onQueue('normal');
Cache::tags(['contest', 'admin', 'PDFGenerate'])->put($cid, $generateProcess->getJobStatusId());
return ResponseModel::success(200, null, [
@@ -340,13 +342,15 @@ public function anticheat(Request $request)
$request->validate([
"cid"=>"required|integer"
]);
- $cid = $request->input('cid');
+ $cid=$request->input('cid');
$contestModel=new ContestModel();
- if ($contestModel->judgeClearance($cid,Auth::user()->id) != 3){
+ if ($contestModel->judgeClearance($cid, Auth::user()->id)!=3) {
return ResponseModel::err(2001);
}
- if(!is_null(Cache::tags(['contest', 'admin', 'anticheat'])->get($cid))) return ResponseModel::err(8001);
- if(EloquentContestModel::find($cid)->isJudgingComplete()) {
+ if (!is_null(Cache::tags(['contest', 'admin', 'anticheat'])->get($cid))) {
+ return ResponseModel::err(8001);
+ }
+ if (EloquentContestModel::find($cid)->isJudgingComplete()) {
$anticheatProcess=new AntiCheat($cid);
dispatch($anticheatProcess)->onQueue('normal');
Cache::tags(['contest', 'admin', 'anticheat'])->put($cid, $anticheatProcess->getJobStatusId());
diff --git a/app/Http/Controllers/Ajax/ContestController.php b/app/Http/Controllers/Ajax/ContestController.php
index 74ac19935..96305dd22 100644
--- a/app/Http/Controllers/Ajax/ContestController.php
+++ b/app/Http/Controllers/Ajax/ContestController.php
@@ -42,7 +42,7 @@ public function updateProfessionalRate(Request $request)
$all_data=$request->all();
$contestModel=new ContestModel();
- return $contestModel->updateProfessionalRate($all_data["cid"])?ResponseModel::success(200):ResponseModel::err(1001);
+ return $contestModel->updateProfessionalRate($all_data["cid"]) ?ResponseModel::success(200) : ResponseModel::err(1001);
}
public function requestClarification(Request $request)
@@ -78,16 +78,16 @@ public function registContest(Request $request)
$groupModel=new GroupModel();
$basic=$contestModel->basic($all_data["cid"]);
- if(!$basic["registration"]){
+ if (!$basic["registration"]) {
return ResponseModel::err(4003);
}
- if(strtotime($basic["registration_due"])