Passed
Push — master ( 876400...7ca6f3 )
by John
04:05
created

ContestModel::contestProblemInfoOI()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 25
nc 5
nop 3
dl 0
loc 34
rs 9.52
c 0
b 0
f 0
1
<?php
2
3
namespace App\Models;
4
5
use GrahamCampbell\Markdown\Facades\Markdown;
6
use App\Models\Submission\SubmissionModel;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Facades\DB;
9
use App\Models\Rating\RatingCalculator;
10
use Auth;
11
use Cache;
12
use Log;
13
14
class ContestModel extends Model
15
{
16
    protected $tableName='contest';
17
    protected $table='contest';
18
    protected $primaryKey='cid';
19
    const DELETED_AT=null;
20
    const UPDATED_AT=null;
21
    const CREATED_AT=null;
22
23
    public $rule=["Unknown", "ICPC", "IOI", "Custom ICPC", "Custom IOI"];
24
25
    public function calcLength($a, $b)
26
    {
27
        $s=strtotime($b)-strtotime($a);
28
        $h=intval($s / 3600);
29
        $m=round(($s-$h * 3600) / 60);
30
        if ($m==60) {
31
            $h++;
32
            $m=0;
33
        }
34
        if ($m==0 && $h==0) {
35
            $text="$s Seconds";
36
        } elseif ($m==0) {
37
            $text="$h Hours";
38
        } elseif ($h==0) {
39
            $text="$m Minutes";
40
        } else {
41
            $text="$h Hours $m Minutes";
42
        }
43
        return $text;
44
    }
45
46
    public function canViewContest($cid, $uid)
47
    {
48
        $contest_detail=DB::table($this->tableName)->where([
49
            "cid"=>$cid
50
        ])->first();
51
52
        if ($contest_detail["public"]==1) {
53
            return $contest_detail;
54
        } else {
55
            // group contest
56
            if ($uid==0) {
57
                return [];
58
            }
59
            $group_info=DB::table("group_member")->where([
60
                "uid"=>$uid,
61
                "gid"=>$contest_detail['gid'],
62
                ["role", ">", 0]
63
            ])->first();
64
            return empty($group_info) ? [] : $contest_detail;
65
        }
66
    }
67
68
    public function basic($cid)
69
    {
70
        return DB::table($this->tableName)->where([
71
            "cid"=>$cid
72
        ])->first();
73
    }
74
75
    public function detail($cid, $uid=0)
76
    {
77
        $contest_clearance=$this->judgeOutSideClearance($cid, $uid);
78
        $contest_detail=$this->basic($cid);
79
80
        if ($contest_clearance==0) {
81
            return [
82
                "ret"=>1000,
83
                "desc"=>"You have no right to view this contest.",
84
                "data"=>null
85
            ];
86
        } else {
87
            $contest_detail["rule_parsed"]=$this->rule[$contest_detail["rule"]];
88
            $contest_detail["date_parsed"]=[
89
                "date"=>date_format(date_create($contest_detail["begin_time"]), 'j'),
90
                "month_year"=>date_format(date_create($contest_detail["begin_time"]), 'M, Y'),
91
            ];
92
            $contest_detail["length"]=$this->calcLength($contest_detail["begin_time"], $contest_detail["end_time"]);
93
            $contest_detail["description_parsed"]=clean(convertMarkdownToHtml($contest_detail["description"]));
94
            $contest_detail["group_info"]=DB::table("group")->where(["gid"=>$contest_detail["gid"]])->first();
95
            $contest_detail["problem_count"]=DB::table("contest_problem")->where(["cid"=>$cid])->count();
96
            return [
97
                "ret"=>200,
98
                "desc"=>"succeed",
99
                "data"=>[
100
                    "contest_detail"=>$contest_detail
101
                ]
102
            ];
103
        }
104
    }
105
106
    public function gid($cid)
107
    {
108
        return DB::table($this->tableName)->where([
109
            "cid"=>$cid
110
        ])->first()["gid"];
111
    }
112
113
    public function gcode($cid)
114
    {
115
        $gid = $this->gid($cid);
116
        return DB::table('group')->where('gid','=',$gid)->first()["gcode"];
117
    }
118
119
    public function runningContest()
120
    {
121
        return DB::select("select * from contest where begin_time < SYSDATE() and end_time > SYSDATE()");
122
    }
123
124
    public function updateCrawlStatus($cid) {
125
        return DB::table("contest")->where("cid", $cid)->update([
126
            "crawled"=>1,
127
        ]);
128
    }
129
130
    public function grantAccess($uid, $cid, $audit=0)
131
    {
132
        return DB::table('contest_participant')->insert([
133
            "cid"=>$cid,
134
            "uid"=>$uid,
135
            "audit"=>$audit
136
        ]);
137
    }
138
139
    public function listForSetting($gid)
140
    {
141
        $uid = Auth::user()->id;
142
        $group_contests = DB::table('contest')
143
            ->where('gid',$gid)
144
            ->orderBy('begin_time','desc')
145
            ->get()->all();
146
        $groupModel = new GroupModel();
147
        $group_clearance = $groupModel->judgeClearance($gid,$uid);
148
        foreach ($group_contests as &$contest) {
149
            $contest['is_admin'] = ($contest['assign_uid'] == $uid || $group_clearance == 3);
150
            $contest['begin_stamps'] = strtotime($contest['begin_time']);
151
            $contest['end_stamps'] = strtotime($contest['end_time']);
152
            $contest['status'] = time() >= $contest['end_stamps'] ? 1
153
                : (time() <= $contest['begin_stamps'] ? -1 : 0);
154
            $contest["rule_parsed"]=$this->rule[$contest["rule"]];
155
            $contest["date_parsed"]=[
156
                "date"=>date_format(date_create($contest["begin_time"]), 'j'),
157
                "month_year"=>date_format(date_create($contest["begin_time"]), 'M, Y'),
158
            ];
159
            $contest["length"]=$this->calcLength($contest["begin_time"], $contest["end_time"]);
160
        }
161
        usort($group_contests,function($a,$b){
162
            if($a['is_admin'] == $b['is_admin']){
163
                return $b['begin_stamps'] - $a['begin_stamps'];
164
            }
165
            return $b['is_admin'] - $a['is_admin'];
166
        });
167
        return $group_contests;
168
    }
169
170
    public function listByGroup($gid)
171
    {
172
        // $contest_list=DB::table($this->tableName)->where([
173
        //     "gid"=>$gid
174
        // ])->orderBy('begin_time', 'desc')->get()->all();
175
        $preQuery=DB::table($this->tableName);
176
        $paginator=$preQuery->where('gid','=',$gid)->orderBy('begin_time', 'desc')->paginate(10);
177
        $contest_list=$paginator->all();
178
        if(empty($contest_list)){
179
            return null;
180
        }
181
182
        foreach ($contest_list as &$c) {
183
            $c["rule_parsed"]=$this->rule[$c["rule"]];
184
            $c["date_parsed"]=[
185
                "date"=>date_format(date_create($c["begin_time"]), 'j'),
186
                "month_year"=>date_format(date_create($c["begin_time"]), 'M, Y'),
187
            ];
188
            $c["length"]=$this->calcLength($c["begin_time"], $c["end_time"]);
189
        }
190
        return [
191
            'paginator' => $paginator,
192
            'contest_list' => $contest_list,
193
        ];
194
    }
195
196
    public function rule($cid)
197
    {
198
        return DB::table($this->tableName)->where([
199
            "cid"=>$cid
200
        ])->first()["rule"];
201
    }
202
203
    public function list($filter,$uid)
204
    {
205
        if ($uid) {
206
            //$paginator=DB::select('SELECT DISTINCT contest.* FROM group_member inner join contest on group_member.gid=contest.gid left join contest_participant on contest.cid=contest_participant.cid where (public=1 and audit=1) or (group_member.uid=:uid and group_member.role>0 and (contest_participant.uid=:uidd or ISNULL(contest_participant.uid)) and (registration=0 or (registration=1 and not ISNULL(contest_participant.uid))))',["uid"=>$uid,"uidd"=>$uid])->paginate(10);
207
            if ($filter['public']=='1') {
208
                $paginator=DB::table($this->tableName)->where([
209
                    "public"=>1,
210
                    "audit_status"=>1
211
                ])->orderBy('begin_time', 'desc');
212
                if ($filter['rule']) {
213
                    $paginator=$paginator->where(["rule"=>$filter['rule']]);
214
                }
215
                if ($filter['verified']) {
216
                    $paginator=$paginator->where(["verified"=>$filter['verified']]);
217
                }
218
                if ($filter['rated']) {
219
                    $paginator=$paginator->where(["rated"=>$filter['rated']]);
220
                }
221
                if ($filter['anticheated']) {
222
                    $paginator=$paginator->where(["anticheated"=>$filter['anticheated']]);
223
                }
224
                if ($filter['practice']) {
225
                    $paginator=$paginator->where(["practice"=>$filter['practice']]);
226
                }
227
                $paginator = $paginator ->paginate(10);
228
            }elseif($filter['public']=='0'){
229
                $paginator=DB::table('group_member')
230
                ->groupBy('contest.cid')
231
                ->select('contest.*')
232
                ->join('contest', 'group_member.gid', '=', 'contest.gid')
233
                ->leftJoin('contest_participant', 'contest.cid', '=', 'contest_participant.cid')
234
                ->where(
235
                    function ($query) use ($filter,$uid) {
236
                        if ($filter['rule']) {
237
                            $query=$query->where(["rule"=>$filter['rule']]);
238
                        }
239
                        if ($filter['verified']) {
240
                            $query=$query->where(["verified"=>$filter['verified']]);
241
                        }
242
                        if ($filter['rated']) {
243
                            $query=$query->where(["rated"=>$filter['rated']]);
244
                        }
245
                        if ($filter['anticheated']) {
246
                            $query=$query->where(["anticheated"=>$filter['anticheated']]);
247
                        }
248
                        if ($filter['practice']) {
249
                            $query=$query->where(["practice"=>$filter['practice']]);
250
                        }
251
                        $query->where('group_member.uid', $uid)
252
                                ->where('group_member.role', '>', 0)
253
                                ->where(["public"=>0]);
254
                    }
255
                )
256
                ->orderBy('contest.begin_time', 'desc')
257
                ->paginate(10);
258
            }else{
259
                $paginator=DB::table('group_member')
260
                ->groupBy('contest.cid')
261
                ->select('contest.*')
262
                ->join('contest', 'group_member.gid', '=', 'contest.gid')
263
                ->leftJoin('contest_participant', 'contest.cid', '=', 'contest_participant.cid')
264
                ->where(
265
                    function ($query) use ($filter) {
266
                        if ($filter['rule']) {
267
                            $query=$query->where(["rule"=>$filter['rule']]);
268
                        }
269
                        if ($filter['verified']) {
270
                            $query=$query->where(["verified"=>$filter['verified']]);
271
                        }
272
                        if ($filter['rated']) {
273
                            $query=$query->where(["rated"=>$filter['rated']]);
274
                        }
275
                        if ($filter['anticheated']) {
276
                            $query=$query->where(["anticheated"=>$filter['anticheated']]);
277
                        }
278
                        if ($filter['practice']) {
279
                            $query=$query->where(["practice"=>$filter['practice']]);
280
                        }
281
                        $query->where('public', 1)
282
                              ->where('audit_status', 1);
283
                    }
284
                )
285
                ->orWhere(
286
                    function ($query) use ($filter,$uid) {
287
                        if ($filter['rule']) {
288
                            $query=$query->where(["rule"=>$filter['rule']]);
289
                        }
290
                        if ($filter['public']) {
291
                            $query=$query->where(["public"=>$filter['public']]);
292
                        }
293
                        if ($filter['verified']) {
294
                            $query=$query->where(["verified"=>$filter['verified']]);
295
                        }
296
                        if ($filter['rated']) {
297
                            $query=$query->where(["rated"=>$filter['rated']]);
298
                        }
299
                        if ($filter['anticheated']) {
300
                            $query=$query->where(["anticheated"=>$filter['anticheated']]);
301
                        }
302
                        if ($filter['practice']) {
303
                            $query=$query->where(["practice"=>$filter['practice']]);
304
                        }
305
                        $query->where('group_member.uid', $uid)
306
                                ->where('group_member.role', '>', 0);
307
                    }
308
                )
309
                ->orderBy('contest.begin_time', 'desc')
310
                ->paginate(10);
311
            }
312
        } else {
313
            $paginator=DB::table($this->tableName)->where([
314
                "public"=>1,
315
                "audit_status"=>1
316
            ])->orderBy('begin_time', 'desc');
317
            if ($filter['rule']) {
318
                $paginator=$paginator->where(["rule"=>$filter['rule']]);
319
            }
320
            if ($filter['verified']) {
321
                $paginator=$paginator->where(["verified"=>$filter['verified']]);
322
            }
323
            if ($filter['rated']) {
324
                $paginator=$paginator->where(["rated"=>$filter['rated']]);
325
            }
326
            if ($filter['anticheated']) {
327
                $paginator=$paginator->where(["anticheated"=>$filter['anticheated']]);
328
            }
329
            if ($filter['practice']) {
330
                $paginator=$paginator->where(["practice"=>$filter['practice']]);
331
            }
332
            $paginator = $paginator ->paginate(10);
333
        }
334
        $contest_list=$paginator->all();
335
        foreach ($contest_list as &$c) {
336
            $c["rule_parsed"]=$this->rule[$c["rule"]];
337
            $c["date_parsed"]=[
338
                "date"=>date_format(date_create($c["begin_time"]), 'j'),
339
                "month_year"=>date_format(date_create($c["begin_time"]), 'M, Y'),
340
            ];
341
            $c["length"]=$this->calcLength($c["begin_time"], $c["end_time"]);
342
        }
343
        return [
344
            'contents' => $contest_list,
345
            'paginator' => $paginator
346
        ];
347
    }
348
349
    public function featured()
350
    {
351
        $featured=DB::table($this->tableName)->where([
352
            "public"=>1,
353
            "audit_status"=>1,
354
            "featured"=>1
355
        ])->orderBy('begin_time', 'desc')->first();
356
357
        if (!empty($featured)) {
358
            $featured["rule_parsed"]=$this->rule[$featured["rule"]];
359
            $featured["date_parsed"]=[
360
                "date"=>date_format(date_create($featured["begin_time"]), 'j'),
361
                "month_year"=>date_format(date_create($featured["begin_time"]), 'M, Y'),
362
            ];
363
            $featured["length"]=$this->calcLength($featured["begin_time"], $featured["end_time"]);
364
            return $featured;
365
        } else {
366
            return null;
367
        }
368
    }
369
370
    public function registContest($cid,$uid)
371
    {
372
        $registered=DB::table("contest_participant")->where([
373
            "cid"=>$cid,
374
            "uid"=>$uid
375
        ])->first();
376
377
        if(empty($registered)){
378
            DB::table("contest_participant")->insert([
379
                "cid"=>$cid,
380
                "uid"=>$uid,
381
                "audit"=>1
382
            ]);
383
            return true;
384
        }
385
        return false;
386
    }
387
388
    public function remainingTime($cid)
389
    {
390
        $end_time=DB::table($this->tableName)->where([
391
            "cid"=>$cid
392
        ])->select("end_time")->first()["end_time"];
393
        $end_time=strtotime($end_time);
394
        $cur_time=time();
395
        return $end_time-$cur_time;
396
    }
397
398
    public function intToChr($index, $start=65)
399
    {
400
        $str='';
401
        if (floor($index / 26)>0) {
402
            $str.=$this->intToChr(floor($index / 26)-1);
403
        }
404
        return $str.chr($index % 26+$start);
405
    }
406
407
    public function problems($cid)
408
    {
409
        return DB::table('contest_problem')
410
            ->join('problem','contest_problem.pid','=','problem.pid')
411
            ->where('cid',$cid)
412
            ->select('problem.pid as pid','pcode','number')
413
            ->orderBy('number')
414
            ->get()->all();
415
    }
416
417
    public function contestProblems($cid, $uid)
418
    {
419
        $submissionModel=new SubmissionModel();
420
421
        $contest_rule=$this->contestRule($cid);
422
423
        $problemSet=DB::table("contest_problem")
424
        ->join("problem", "contest_problem.pid", "=", "problem.pid")
425
        ->join("contest", "contest_problem.cid", "=", "contest.cid")
426
        ->where([
427
            "contest_problem.cid"=>$cid
428
        ])->orderBy('ncode', 'asc')->select("ncode", "alias", "contest_problem.pid as pid", "title", "contest.gid as gid", "contest.practice as practice")->get()->all();
429
430
        $frozen_time=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
431
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
0 ignored issues
show
Unused Code introduced by
The assignment to $end_time is dead and can be removed.
Loading history...
432
433
        foreach ($problemSet as &$p) {
434
            if($p['practice']){
435
                $tags = DB::table("group_problem_tag")
436
                ->where('gid',$p['gid'])
437
                ->where('pid',$p['pid'])
438
                ->get()->all();
439
                $tags_arr = [];
440
                if(!empty($tags)){
441
                    foreach ($tags as $value) {
442
                        array_push($tags_arr,$value['tag']);
443
                    }
444
                }
445
                $p['tags'] = $tags_arr;
446
            }
447
            if ($contest_rule==1) {
448
                $prob_stat=DB::table("submission")->select(
449
                    DB::raw("count(sid) as submission_count"),
450
                    DB::raw("sum(verdict='accepted') as passed_count"),
451
                    DB::raw("sum(verdict='accepted')/count(sid)*100 as ac_rate")
452
                )->where([
453
                    "pid"=>$p["pid"],
454
                    "cid"=>$cid
455
                ])->where("submission_date", "<", $frozen_time)->first();
456
457
                if ($prob_stat["submission_count"]==0) {
458
                    $p["submission_count"]=0;
459
                    $p["passed_count"]=0;
460
                    $p["ac_rate"]=0;
461
                } else {
462
                    $p["submission_count"]=$prob_stat["submission_count"];
463
                    $p["passed_count"]=$prob_stat["passed_count"];
464
                    $p["ac_rate"]=round($prob_stat["ac_rate"], 2);
465
                }
466
            } else {
467
                $prob_stat=$this->contestProblemInfoIOI($cid, $p["pid"], $uid);
468
                $p["points"]=$prob_stat["points"];
469
                $p["score"]=empty($prob_stat["score_parsed"]) ? 0 : $prob_stat["score_parsed"];
470
            }
471
            $prob_status=$submissionModel->getProblemStatus($p["pid"], $uid, $cid);
472
            if (empty($prob_status)) {
473
                $p["prob_status"]=[
474
                    "icon"=>"checkbox-blank-circle-outline",
475
                    "color"=>"wemd-grey-text"
476
                ];
477
            } else {
478
                $p["prob_status"]=[
479
                    "icon"=>$prob_status["verdict"]=="Accepted" ? "checkbox-blank-circle" : "cisco-webex",
480
                    "color"=>$prob_status["color"]
481
                ];
482
            }
483
484
485
        }
486
487
        return $problemSet;
488
    }
489
490
    public function getPid($cid, $ncode)
491
    {
492
        return DB::table("contest_problem")->where([
493
            "cid"=>$cid,
494
            "ncode"=>$ncode
495
        ])->select("contest_problem.pid")->first()["pid"];
496
    }
497
498
    public function getPcode($cid, $ncode)
0 ignored issues
show
Unused Code introduced by
The parameter $ncode is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

498
    public function getPcode($cid, /** @scrutinizer ignore-unused */ $ncode)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
499
    {
500
        return DB::table("problem")->where([
501
            "cid"=>$cid
502
        ])->select("contest_problem.pid")->first()["pcode"];
503
    }
504
505
    public function getCustomInfo($cid)
506
    {
507
        $basic_info=DB::table($this->tableName)->where([
508
            "cid"=>$cid
509
        ])->select("verified", "custom_icon", "custom_title")->first();
510
        return $basic_info["verified"] ? ((is_null($basic_info["custom_icon"]) && is_null($basic_info["custom_title"])) ?null:$basic_info) : null;
511
    }
512
513
514
    public function formatTime($seconds)
515
    {
516
        if ($seconds>3600) {
517
            $hours=intval($seconds / 3600);
518
            $minutes=$seconds % 3600;
519
            $time=$hours.":".gmstrftime('%M:%S', $minutes);
520
        } else {
521
            $time=gmstrftime('%H:%M:%S', $seconds);
522
        }
523
        return $time;
524
    }
525
526
    public function contestProblemInfoIOI($cid, $pid, $uid)
527
    {
528
        $ret=[
529
            "color"=>"",
530
            "score"=>null,
531
            "score_parsed"=>"",
532
            "solved"=>0,
533
            "points"=>DB::table("contest_problem")->where([
534
                "pid"=>$pid,
535
                "cid"=>$cid
536
            ])->first()["points"]
537
        ];
538
539
        $frozen_time=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
540
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
0 ignored issues
show
Unused Code introduced by
The assignment to $end_time is dead and can be removed.
Loading history...
541
542
        $highest_record=DB::table("submission")->where([
543
            "cid"=>$cid,
544
            "pid"=>$pid,
545
            "uid"=>$uid
546
        ])->where("submission_date", "<", $frozen_time)->orderBy('score', 'desc')->first();
547
548
        if (!empty($highest_record)) {
549
            $ret["score"]=$highest_record["score"];
550
551
            $tot_score=DB::table("problem")->where([
552
                "pid"=>$pid
553
            ])->first()["tot_score"];
554
555
            $ret["color"]=($ret["score"]==$tot_score) ? "wemd-teal-text" : "wemd-green-text";
556
            $ret["solved"]=($ret["score"]==$tot_score) ? 1 : 0;
557
            $ret["score_parsed"]=$ret["score"] / $tot_score * ($ret["points"]);
558
        }
559
        return $ret;
560
    }
561
562
    public function isFrozen($cid)
563
    {
564
        $frozen=DB::table("contest")->where(["cid"=>$cid])->select("froze_length", DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first();
565
        if (empty($frozen["froze_length"])) {
566
            return false;
567
        } else {
568
            return time()>$frozen["frozen_time"];
569
        }
570
    }
571
572
    public function contestProblemInfoACM($cid, $pid, $uid)
573
    {
574
        $ret=[
575
            "color"=>"",
576
            "solved"=>0,
577
            "solved_time"=>"",
578
            "solved_time_parsed"=>"",
579
            "wrong_doings"=>0,
580
            "color"=>"",
581
        ];
582
583
        $frozen_time=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
584
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
0 ignored issues
show
Unused Code introduced by
The assignment to $end_time is dead and can be removed.
Loading history...
585
586
        $ac_record=DB::table("submission")->where([
587
            "cid"=>$cid,
588
            "pid"=>$pid,
589
            "uid"=>$uid,
590
            "verdict"=>"Accepted"
591
        ])->where("submission_date", "<", $frozen_time)->orderBy('submission_date', 'asc')->first();
592
593
        if (!empty($ac_record)) {
594
            $ret["solved"]=1;
595
596
            $ret["solved_time"]=$ac_record["submission_date"]-strtotime(DB::table($this->tableName)->where([
597
                "cid"=>$cid
598
            ])->first()["begin_time"]);
599
600
            $ret["solved_time_parsed"]=$this->formatTime($ret["solved_time"]);
601
602
            $ret["wrong_doings"]=DB::table("submission")->where([
603
                "cid"=>$cid,
604
                "pid"=>$pid,
605
                "uid"=>$uid
606
            ])->whereIn('verdict', [
607
                'Runtime Error',
608
                'Wrong Answer',
609
                'Time Limit Exceed',
610
                'Real Time Limit Exceed',
611
                'Memory Limit Exceed',
612
                'Presentation Error',
613
                'Output Limit Exceeded'
614
            ])->where("submission_date", "<", $ac_record["submission_date"])->count();
615
616
            $others_first=DB::table("submission")->where([
617
                "cid"=>$cid,
618
                "pid"=>$pid,
619
                "verdict"=>"Accepted"
620
            ])->where("submission_date", "<", $ac_record["submission_date"])->count();
621
622
            $ret["color"]=$others_first ? "wemd-green-text" : "wemd-teal-text";
623
        } else {
624
            $ret["wrong_doings"]=DB::table("submission")->where([
625
                "cid"=>$cid,
626
                "pid"=>$pid,
627
                "uid"=>$uid
628
            ])->whereIn('verdict', [
629
                'Runtime Error',
630
                'Wrong Answer',
631
                'Time Limit Exceed',
632
                'Real Time Limit Exceed',
633
                'Memory Limit Exceed',
634
                'Presentation Error',
635
                'Output Limit Exceeded'
636
            ])->where("submission_date", "<", $frozen_time)->count();
637
        }
638
639
        return $ret;
640
    }
641
642
    public function contestRankCache($cid)
643
    {
644
        // if(Cache::tags(['contest','rank'])->get($cid)!=null) return Cache::tags(['contest','rank'])->get($cid);
645
        $ret=[];
646
647
        $contest_info=DB::table("contest")->where("cid", $cid)->first();
648
        $frozen_time=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
649
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
0 ignored issues
show
Unused Code introduced by
The assignment to $end_time is dead and can be removed.
Loading history...
650
651
        if ($contest_info["registration"]) {
652
            $submissionUsers=DB::table("contest_participant")->where([
653
                "cid"=>$cid,
654
                "audit"=>1
655
            ])->select('uid')->get()->all();
656
        } else {
657
            // Those who submitted are participants
658
            $submissionUsers=DB::table("submission")->where([
659
                "cid"=>$cid
660
            ])->where(
661
                "submission_date",
662
                "<",
663
                $frozen_time
664
            )->select('uid')->groupBy('uid')->get()->all();
665
        }
666
667
        $problemSet=DB::table("contest_problem")->join("problem", "contest_problem.pid", "=", "problem.pid")->where([
668
            "cid"=>$cid
669
        ])->orderBy('ncode', 'asc')->select("ncode", "alias", "contest_problem.pid as pid", "title")->get()->all();
670
671
        if ($contest_info["rule"]==1) {
672
            // ACM/ICPC Mode
673
            foreach ($submissionUsers as $s) {
674
                $prob_detail=[];
675
                $totPen=0;
676
                $totScore=0;
677
                foreach ($problemSet as $p) {
678
                    $prob_stat=$this->contestProblemInfoACM($cid, $p["pid"], $s["uid"]);
679
                    $prob_detail[]=[
680
                        "ncode"=>$p["ncode"],
681
                        "pid"=>$p["pid"],
682
                        "color"=>$prob_stat["color"],
683
                        "wrong_doings"=>$prob_stat["wrong_doings"],
684
                        "solved_time_parsed"=>$prob_stat["solved_time_parsed"]
685
                    ];
686
                    if ($prob_stat["solved"]) {
687
                        $totPen+=$prob_stat["wrong_doings"] * 20;
688
                        $totPen+=$prob_stat["solved_time"] / 60;
689
                        $totScore+=$prob_stat["solved"];
690
                    }
691
                }
692
                $ret[]=[
693
                    "uid" => $s["uid"],
694
                    "name" => DB::table("users")->where([
695
                        "id"=>$s["uid"]
696
                    ])->first()["name"],
697
                    "nick_name" => DB::table("group_member")->where([
698
                        "uid" => $s["uid"],
699
                        "gid" => $contest_info["gid"]
700
                    ])->where("role", ">", 0)->first()["nick_name"],
701
                    "score" => $totScore,
702
                    "penalty" => $totPen,
703
                    "problem_detail" => $prob_detail
704
                ];
705
            }
706
            usort($ret, function ($a, $b) {
707
                if ($a["score"]==$b["score"]) {
708
                    if ($a["penalty"]==$b["penalty"]) {
709
                        return 0;
710
                    } elseif (($a["penalty"]>$b["penalty"])) {
711
                        return 1;
712
                    } else {
713
                        return -1;
714
                    }
715
                } elseif ($a["score"]>$b["score"]) {
716
                    return -1;
717
                } else {
718
                    return 1;
719
                }
720
            });
721
        } elseif ($contest_info["rule"]==2) {
722
            // IOI Mode
723
            foreach ($submissionUsers as $s) {
724
                $prob_detail=[];
725
                $totScore=0;
726
                $totSolved=0;
727
                foreach ($problemSet as $p) {
728
                    $prob_stat=$this->contestProblemInfoIOI($cid, $p["pid"], $s["uid"]);
729
                    $prob_detail[]=[
730
                        "ncode"=>$p["ncode"],
731
                        "pid"=>$p["pid"],
732
                        "color"=>$prob_stat["color"],
733
                        "score"=>$prob_stat["score"],
734
                        "score_parsed"=>$prob_stat["score_parsed"]
735
                    ];
736
                    $totSolved+=$prob_stat["solved"];
737
                    $totScore+=intval($prob_stat["score_parsed"]);
738
                }
739
                $ret[]=[
740
                    "uid" => $s["uid"],
741
                    "name" => DB::table("users")->where([
742
                        "id"=>$s["uid"]
743
                    ])->first()["name"],
744
                    "nick_name" => DB::table("group_member")->where([
745
                        "uid" => $s["uid"],
746
                        "gid" => $contest_info["gid"]
747
                    ])->where("role", ">", 0)->first()["nick_name"],
748
                    "score" => $totScore,
749
                    "solved" => $totSolved,
750
                    "problem_detail" => $prob_detail
751
                ];
752
            }
753
            usort($ret, function ($a, $b) {
754
                if ($a["score"]==$b["score"]) {
755
                    if ($a["solved"]==$b["solved"]) {
756
                        return 0;
757
                    } elseif (($a["solved"]<$b["solved"])) {
758
                        return 1;
759
                    } else {
760
                        return -1;
761
                    }
762
                } elseif ($a["score"]>$b["score"]) {
763
                    return -1;
764
                } else {
765
                    return 1;
766
                }
767
            });
768
        }
769
770
        Cache::tags(['contest', 'rank'])->put($cid, $ret, 60);
771
772
        return $ret;
773
    }
774
775
    public function contestRank($cid, $uid = 0)
776
    {
777
        // [ToDo] If the current user's in the organizer group show nick name
778
        // [ToDo] The participants determination
779
        // [ToDo] Frozen Time
780
        // [ToDo] Performance Opt
781
        // [Todo] Ajaxization - Should have done in controller
782
        // [Todo] Authorization ( Public / Private ) - Should have done in controller
783
784
        $ret=[];
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
785
786
        $contest_info=DB::table("contest")->where("cid", $cid)->first();
787
788
        $user_in_group=!empty(DB::table("group_member")->where([
789
            "uid" => $uid,
790
            "gid" => $contest_info["gid"]
791
        ])->where("role", ">", 0)->first());
792
793
        $clearance = $this -> judgeClearance($cid, $uid);
794
795
        /** New Version With MySQL */
796
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
797
798
        if(time() < $end_time){
799
            if($clearance == 3){
800
                $contestRankRaw=Cache::tags(['contest', 'rank'])->get("contestAdmin$cid");
801
            }else{
802
                $contestRankRaw=Cache::tags(['contest', 'rank'])->get($cid);
803
            }
804
            if(!isset($contestRankRaw)){
805
                $contestRankRaw=$this->contestRankCache($cid);
806
            }
807
        }else{
808
            if($clearance == 3){
809
                $contestRankRaw=Cache::tags(['contest', 'rank'])->get("contestAdmin$cid");
810
                if (!isset($contestRankRaw)) {
811
                    $contestRankRaw=$this->getContestRankFromMySQL($cid);
812
                    if(!isset($contestRankRaw)){
813
                        $contestRankRaw=$this->contestRankCache($cid);
814
                        $this->storeContestRankInMySQL($cid, $contestRankRaw);
815
                    }
816
                }
817
            }else{
818
                $contestRankRaw=$this->getContestRankFromMySQL($cid);
819
                if(!isset($contestRankRaw)){
820
                    $contestRankRaw=Cache::tags(['contest', 'rank'])->get($cid);
821
                    if(!isset($contestRankRaw)){
822
                        $contestRankRaw=$this->contestRankCache($cid);
823
                    }
824
                    $this->storeContestRankInMySQL($cid, $contestRankRaw);
825
                }
826
            }
827
        }
828
829
        /** Old version */
830
        // if ($contestRankRaw==null) {
831
        //     $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
832
        //     if(time() > $end_time && !Cache::has($cid)){
833
        //         $contestRankRaw=$this->contestRankCache($cid);
834
        //         // Cache::forever($cid, $contestRankRaw);
835
        //     }else{
836
        //         $contestRankRaw=$this->contestRankCache($cid);
837
        //     }
838
        // }
839
        if($contest_info["rule"]==1){
840
            foreach ($contestRankRaw as &$cr) {
841
                $solved = 0;
842
                foreach($cr['problem_detail'] as $pd){
843
                    if(!empty($pd['solved_time_parsed'])){
844
                        $solved ++;
845
                    }
846
                }
847
                $cr['solved'] = $solved;
848
            }
849
        }
850
851
        $ret=$contestRankRaw;
852
853
        foreach ($ret as $r) {
854
            if (!$user_in_group) {
855
                $r["nick_name"]='';
856
            }
857
        }
858
859
        return $ret;
860
    }
861
862
    public function getRejudgeQueue($cid)
863
    {
864
        $problemModel=new ProblemModel();
865
        $submissionModel=new SubmissionModel();
0 ignored issues
show
Unused Code introduced by
The assignment to $submissionModel is dead and can be removed.
Loading history...
866
        $compilerModel=new CompilerModel();
867
868
        $tempQueue=DB::table("submission")->where([
869
            "cid"=>$cid
870
        ])->whereIn('verdict', [
871
            'Runtime Error',
872
            'Wrong Answer',
873
            'Time Limit Exceed',
874
            'Real Time Limit Exceed',
875
            'Memory Limit Exceed',
876
            'Presentation Error',
877
            'Output Limit Exceeded'
878
        ])->get()->all();
879
880
        foreach ($tempQueue as &$t) {
881
            $lang=$compilerModel->detail($t["coid"]);
882
            $probBasic=$problemModel->basic($t["pid"]);
883
            $t["oj"]=$problemModel->ocode($t["pid"]);
884
            $t["lang"]=$lang['lcode'];
885
            $t["cid"]=$probBasic["contest_id"];
886
            $t["iid"]=$probBasic["index_id"];
887
            $t["pcode"]=$probBasic["pcode"];
888
            $t["contest"]=$cid;
889
        }
890
891
        return $tempQueue;
892
    }
893
894
    public function getClarificationList($cid)
895
    {
896
        $uid = Auth::user()->id;
897
        $clearance = $this -> judgeClearance($cid, $uid);
898
        if($clearance == 3){
899
            return DB::table("contest_clarification")->where([
900
                "cid"=>$cid
901
            ])->orderBy('create_time', 'desc')->get()->all();
902
        }else{
903
            return DB::table("contest_clarification")->where([
904
                "cid"=>$cid
905
            ])->where(function ($query) {
906
                $query->where([
907
                    "public"=>1
908
                ])->orWhere([
909
                    "uid" => Auth::user()->id
910
                ]);
911
            })->orderBy('create_time', 'desc')->get()->all();
912
        }
913
    }
914
915
    public function fetchClarification($cid)
916
    {
917
        return DB::table("contest_clarification")->where([
918
            "cid"=>$cid,
919
            "type"=>0,
920
            "public"=>1
921
        ])->whereBetween(
922
            'create_time',
923
            [
924
                date("Y-m-d H:i:s", time()-59),
925
                date("Y-m-d H:i:s")
926
            ]
927
        )->first();
928
    }
929
930
    public function getlatestClarification($cid)
931
    {
932
        return DB::table("contest_clarification")->where([
933
            "cid"=>$cid,
934
            "type"=>0,
935
            "public"=>1
936
        ])->orderBy('create_time', 'desc')->first();
937
    }
938
939
    public function getClarificationDetail($ccid)
940
    {
941
        return DB::table("contest_clarification")->where([
942
            "ccid"=>$ccid,
943
            "public"=>1
944
        ])->first();
945
    }
946
947
    public function requestClarification($cid, $title, $content, $uid)
948
    {
949
        return DB::table("contest_clarification")->insertGetId([
950
            "cid"=>$cid,
951
            "type"=>1,
952
            "title"=>$title,
953
            "content"=>$content,
954
            "public"=>"0",
955
            "uid"=>$uid,
956
            "create_time"=>date("Y-m-d H:i:s")
957
        ]);
958
    }
959
960
    public function issueAnnouncement($cid, $title, $content, $uid, $remote_code=null)
961
    {
962
        return DB::table("contest_clarification")->insertGetId([
963
            "cid"=>$cid,
964
            "type"=>0,
965
            "title"=>$title,
966
            "content"=>$content,
967
            "public"=>"1",
968
            "uid"=>$uid,
969
            "create_time"=>date("Y-m-d H:i:s"),
970
            "remote_code"=>$remote_code
971
        ]);
972
    }
973
974
    public function remoteAnnouncement($remote_code) {
975
        return DB::table("contest_clarification")->where("remote_code", $remote_code)->get()->first();
976
    }
977
978
    public function isContestEnded($cid)
979
    {
980
        return DB::table("contest")->where("cid", $cid)->where("end_time", "<", date("Y-m-d H:i:s"))->count();
981
    }
982
983
    public function isContestRunning($cid)
984
    {
985
        return DB::table("contest")->where("cid", $cid)->where("begin_time", "<", date("Y-m-d H:i:s"))->where("end_time", ">", date("Y-m-d H:i:s"))->count();
986
    }
987
988
    public function formatSubmitTime($date)
989
    {
990
        $periods=["second", "minute", "hour", "day", "week", "month", "year", "decade"];
991
        $lengths=["60", "60", "24", "7", "4.35", "12", "10"];
992
993
        $now=time();
994
        $unix_date=strtotime($date);
995
996
        if (empty($unix_date)) {
997
            return "Bad date";
998
        }
999
1000
        if ($now>$unix_date) {
1001
            $difference=$now-$unix_date;
1002
            $tense="ago";
1003
        } else {
1004
            $difference=$unix_date-$now;
1005
            $tense="from now";
1006
        }
1007
1008
        for ($j=0; $difference>=$lengths[$j] && $j<count($lengths)-1; $j++) {
1009
            $difference/=$lengths[$j];
1010
        }
1011
1012
        $difference=round($difference);
1013
1014
        if ($difference!=1) {
1015
            $periods[$j].="s";
1016
        }
1017
1018
        return "$difference $periods[$j] {$tense}";
1019
    }
1020
1021
    public function formatAbsTime($sec)
1022
    {
1023
        $periods=["second", "minute", "hour", "day", "week", "month", "year", "decade"];
1024
        $lengths=["60", "60", "24", "7", "4.35", "12", "10"];
1025
1026
1027
        $difference=$sec;
1028
1029
        for ($j=0; $difference>=$lengths[$j] && $j<count($lengths)-1; $j++) {
1030
            $difference/=$lengths[$j];
1031
        }
1032
1033
        $difference=round($difference);
1034
1035
        if ($difference!=1) {
1036
            $periods[$j].="s";
1037
        }
1038
1039
        return "$difference $periods[$j]";
1040
    }
1041
1042
    public function frozenTime($cid)
1043
    {
1044
        $basicInfo=$this->basic($cid);
1045
        return $this->formatAbsTime($basicInfo["froze_length"]);
1046
    }
1047
1048
    public function getContestRecord($filter, $cid)
1049
    {
1050
        $basicInfo=$this->basic($cid);
1051
        $userInfo=DB::table('group_member')->where('gid',$basicInfo["gid"])->where('uid',Auth::user()->id)->get()->first();
1052
        $problemSet_temp=DB::table("contest_problem")->join("problem", "contest_problem.pid", "=", "problem.pid")->where([
1053
            "cid"=>$cid
1054
        ])->orderBy('ncode', 'asc')->select("ncode", "alias", "contest_problem.pid as pid", "title", "points", "tot_score")->get()->all();
1055
        $problemSet=[];
1056
        foreach ($problemSet_temp as $p) {
1057
            $problemSet[(string) $p["pid"]]=["ncode"=>$p["ncode"], "points"=>$p["points"], "tot_score"=>$p["tot_score"]];
1058
        }
1059
1060
        $frozen_time=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
1061
        $end_time=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
1062
        $contestEnd=time()>$end_time;
1063
1064
        $filter['pid'] = array_search($filter['ncode'], array_column($problemSet_temp, 'ncode'));
1065
        if($filter['pid']==false){
1066
            $filter['pid'] = null;
1067
        }else{
1068
            $filter['pid'] = $problemSet_temp[$filter['pid']]['pid'];
1069
        }
1070
1071
        if($userInfo==null || $userInfo["role"]!=3){
1072
            if ($basicInfo["status_visibility"]==2) {
1073
                // View all
1074
                $paginator=DB::table("submission")->where([
1075
                    'cid'=>$cid
1076
                ])->where(
1077
                    "submission_date",
1078
                    "<",
1079
                    $end_time
1080
                )->join(
1081
                    "users",
1082
                    "users.id",
1083
                    "=",
1084
                    "submission.uid"
1085
                )->where(function ($query) use ($frozen_time) {
1086
                    $query->where(
1087
                        "submission_date",
1088
                        "<",
1089
                        $frozen_time
1090
                    )->orWhere(
1091
                        'uid',
1092
                        Auth::user()->id
1093
                    );
1094
                })->select(
1095
                    "sid",
1096
                    "uid",
1097
                    "pid",
1098
                    "name",
1099
                    "color",
1100
                    "verdict",
1101
                    "time",
1102
                    "memory",
1103
                    "language",
1104
                    "score",
1105
                    "submission_date",
1106
                    "share"
1107
                )->orderBy(
1108
                    'submission_date',
1109
                    'desc'
1110
                );
1111
1112
                if($filter["pid"]){
1113
                    $paginator=$paginator->where(["pid"=>$filter["pid"]]);
1114
                }
1115
1116
                if($filter["result"]){
1117
                    $paginator=$paginator->where(["verdict"=>$filter["result"]]);
1118
                }
1119
1120
                if($filter["account"]){
1121
                    $paginator=$paginator->where(["name"=>$filter["account"]]);
1122
                }
1123
1124
                $paginator=$paginator->paginate(50);
1125
            } elseif ($basicInfo["status_visibility"]==1) {
1126
                $paginator=DB::table("submission")->where([
1127
                    'cid'=>$cid,
1128
                    'uid'=>Auth::user()->id
1129
                ])->where(
1130
                    "submission_date",
1131
                    "<",
1132
                    $end_time
1133
                )->join(
1134
                    "users",
1135
                    "users.id",
1136
                    "=",
1137
                    "submission.uid"
1138
                )->select(
1139
                    "sid",
1140
                    "uid",
1141
                    "pid",
1142
                    "name",
1143
                    "color",
1144
                    "verdict",
1145
                    "time",
1146
                    "memory",
1147
                    "language",
1148
                    "score",
1149
                    "submission_date",
1150
                    "share"
1151
                )->orderBy(
1152
                    'submission_date',
1153
                    'desc'
1154
                );
1155
1156
                if($filter["pid"]){
1157
                    $paginator=$paginator->where(["pid"=>$filter["pid"]]);
1158
                }
1159
1160
                if($filter["result"]){
1161
                    $paginator=$paginator->where(["verdict"=>$filter["result"]]);
1162
                }
1163
1164
                if($filter["account"]){
1165
                    $paginator=$paginator->where(["name"=>$filter["account"]]);
1166
                }
1167
1168
                $paginator=$paginator->paginate(50);
1169
            } else {
1170
                return [
1171
                    "paginator"=>null,
1172
                    "records"=>[]
1173
                ];
1174
            }
1175
        }else{
1176
            if ($basicInfo["status_visibility"]==2) {
1177
                // View all
1178
                $paginator=DB::table("submission")->where([
1179
                    'cid'=>$cid
1180
                ])->where(
1181
                    "submission_date",
1182
                    "<",
1183
                    $end_time
1184
                )->join(
1185
                    "users",
1186
                    "users.id",
1187
                    "=",
1188
                    "submission.uid"
1189
                )->select(
1190
                    "sid",
1191
                    "uid",
1192
                    "pid",
1193
                    "name",
1194
                    "color",
1195
                    "verdict",
1196
                    "time",
1197
                    "memory",
1198
                    "language",
1199
                    "score",
1200
                    "submission_date",
1201
                    "share"
1202
                )->orderBy(
1203
                    'submission_date',
1204
                    'desc'
1205
                );
1206
1207
                if($filter["pid"]){
1208
                    $paginator=$paginator->where(["pid"=>$filter["pid"]]);
1209
                }
1210
1211
                if($filter["result"]){
1212
                    $paginator=$paginator->where(["verdict"=>$filter["result"]]);
1213
                }
1214
1215
                if($filter["account"]){
1216
                    $paginator=$paginator->where(["name"=>$filter["account"]]);
1217
                }
1218
1219
                $paginator=$paginator->paginate(50);
1220
            } elseif ($basicInfo["status_visibility"]==1) {
1221
                $paginator=DB::table("submission")->where([
1222
                    'cid'=>$cid,
1223
                    'uid'=>Auth::user()->id
1224
                ])->where(
1225
                    "submission_date",
1226
                    "<",
1227
                    $end_time
1228
                )->join(
1229
                    "users",
1230
                    "users.id",
1231
                    "=",
1232
                    "submission.uid"
1233
                )->select(
1234
                    "sid",
1235
                    "uid",
1236
                    "pid",
1237
                    "name",
1238
                    "color",
1239
                    "verdict",
1240
                    "time",
1241
                    "memory",
1242
                    "language",
1243
                    "score",
1244
                    "submission_date",
1245
                    "share"
1246
                )->orderBy(
1247
                    'submission_date',
1248
                    'desc'
1249
                );
1250
1251
                if($filter["pid"]){
1252
                    $paginator=$paginator->where(["pid"=>$filter["pid"]]);
1253
                }
1254
1255
                if($filter["result"]){
1256
                    $paginator=$paginator->where(["verdict"=>$filter["result"]]);
1257
                }
1258
1259
                if($filter["account"]){
1260
                    $paginator=$paginator->where(["name"=>$filter["account"]]);
1261
                }
1262
1263
                $paginator=$paginator->paginate(50);
1264
            } else {
1265
                return [
1266
                    "paginator"=>null,
1267
                    "records"=>[]
1268
                ];
1269
            }
1270
        }
1271
1272
        $records=$paginator->all();
1273
        foreach ($records as &$r) {
1274
            $r["submission_date_parsed"]=$this->formatSubmitTime(date('Y-m-d H:i:s', $r["submission_date"]));
1275
            $r["submission_date"]=date('Y-m-d H:i:s', $r["submission_date"]);
1276
            $r["nick_name"]="";
1277
            $r["ncode"]=$problemSet[(string) $r["pid"]]["ncode"];
1278
            if ($r["verdict"]=="Partially Accepted") {
1279
                $score_parsed=round($r["score"] / $problemSet[(string) $r["pid"]]["tot_score"] * $problemSet[(string) $r["pid"]]["points"], 1);
1280
                $r["verdict"].=" ($score_parsed)";
1281
            }
1282
            if (!$contestEnd) {
1283
                $r["share"]=0;
1284
            }
1285
        }
1286
        return [
1287
            "paginator"=>$paginator,
1288
            "records"=>$records
1289
        ];
1290
    }
1291
1292
    public function registration($cid, $uid=0)
1293
    {
1294
        if ($uid==0) {
1295
            return [];
1296
        }
1297
1298
1299
        return DB::table("contest_participant")->where([
1300
            "cid" => $cid,
1301
            "uid" => $uid,
1302
            "audit" => 1
1303
        ])->first();
1304
    }
1305
1306
    public function judgeClearance($cid, $uid=0)
1307
    {
1308
        /***************************
1309
         * 2 stands for participant*
1310
         * 3 stands for admin      *
1311
         ***************************/
1312
        if ($uid==0) {
1313
            return 0;
1314
        }
1315
        $groupModel = new GroupModel();
1316
        $contest_info=DB::table("contest")->where("cid", $cid)->first();
1317
        $userInfo=DB::table('group_member')->where('gid',$contest_info["gid"])->where('uid',$uid)->get()->first();
1318
1319
        if(empty($contest_info)){
1320
            // contest not exist
1321
            return 0;
1322
        }
1323
1324
        if($uid == $contest_info['assign_uid'] || $groupModel->judgeClearance($contest_info['gid'],$uid) == 3){
1325
            return 3;
1326
        }
1327
1328
        $contest_started = strtotime($contest_info['begin_time']) < time();
1329
        $contest_ended = strtotime($contest_info['end_time']) < time();
1330
        if (!$contest_started) {
1331
            // not started or do not exist
1332
            return 0;
1333
        }
1334
1335
        if ($userInfo["role"]==3) {
1336
            return 3;
1337
        }
1338
1339
        if ($contest_info["public"]) {
1340
            //public
1341
            if ($contest_ended) {
1342
                return 1;
1343
            } else {
1344
                if ($contest_info["registration"]) {
1345
                    // check if uid in registration, temp return 3
1346
                    $isParticipant=DB::table("contest_participant")->where([
1347
                        "cid" => $cid,
1348
                        "uid" => $uid,
1349
                        "audit" => 1
1350
                    ])->count();
1351
                    if ($isParticipant) {
1352
                        return 2;
1353
                    } else {
1354
                        return 0;
1355
                    }
1356
                } else {
1357
                    return 2;
1358
                }
1359
            }
1360
        } else {
1361
            //private
1362
            $isMember=DB::table("group_member")->where([
1363
                "gid"=> $contest_info["gid"],
1364
                "uid"=> $uid
1365
            ])->where("role", ">", 0)->count();
1366
            if (!$isMember) {
1367
                return 0;
1368
            } else {
1369
                if ($contest_info["registration"]) {
1370
                    // check if uid in registration, temp return 3
1371
                    $isParticipant=DB::table("contest_participant")->where([
1372
                        "cid" => $cid,
1373
                        "uid" => $uid,
1374
                        "audit" => 1
1375
                    ])->count();
1376
                    if ($isParticipant) {
1377
                        return 2;
1378
                    } else {
1379
                        return 0;
1380
                    }
1381
                } else {
1382
                    return 2;
1383
                }
1384
            }
1385
        }
1386
    }
1387
1388
    public function judgeOutsideClearance($cid, $uid=0)
1389
    {
1390
        $contest_info=DB::table("contest")->where("cid", $cid)->first();
1391
        if (empty($contest_info)) {
1392
            return 0;
1393
        }
1394
        if ($contest_info["public"]) {
1395
            return 1;
1396
        } else {
1397
            if ($uid==0) {
1398
                return 0;
1399
            }
1400
            return DB::table("group_member")->where([
1401
                "gid"=> $contest_info["gid"],
1402
                "uid"=> $uid
1403
            ])->where("role", ">", 0)->count() ? 1 : 0;
1404
        }
1405
    }
1406
1407
    public function contestName($cid)
1408
    {
1409
        return DB::table("contest")->where("cid", $cid)->select("name")->first()["name"];
1410
    }
1411
1412
    public function contestRule($cid)
1413
    {
1414
        return DB::table("contest")->where("cid", $cid)->select("rule")->first()["rule"];
1415
    }
1416
1417
    public function updateProfessionalRate($cid)
1418
    {
1419
        $basic=$this->basic($cid);
1420
        if($basic["rated"]&&!$basic["is_rated"]){
1421
            $ratingCalculator=new RatingCalculator($cid);
1422
            if($ratingCalculator->calculate()){
1423
                $ratingCalculator->storage();
1424
                return true;
1425
            }else{
1426
                return false;
1427
            }
1428
        } else {
1429
            return false;
1430
        }
1431
    }
1432
1433
    public function contestUpdate($cid,$data,$problems)
1434
    {
1435
        if($problems !== false){
1436
            $old_problmes = array_column(
1437
                DB::table('contest_problem')
1438
                ->where('cid',$cid)
1439
                ->get()->all(),
1440
                'pid'
1441
            );
1442
            DB::transaction(function () use ($cid, $data, $problems,$old_problmes) {
1443
                DB::table($this->tableName)
1444
                    ->where('cid',$cid)
1445
                    ->update($data);
1446
                DB::table('contest_problem')
1447
                    ->where('cid',$cid)
1448
                    ->delete();
1449
                $new_problems = [];
1450
                foreach ($problems as $p) {
1451
                    $pid=DB::table("problem")->where(["pcode"=>$p["pcode"]])->select("pid")->first()["pid"];
1452
                    array_push($new_problems,$pid);
1453
                    DB::table("contest_problem")->insert([
1454
                        "cid"=>$cid,
1455
                        "number"=>$p["number"],
1456
                        "ncode"=>$this->intToChr($p["number"]-1),
1457
                        "pid"=>$pid,
1458
                        "alias"=>"",
1459
                        "points"=>$p["points"]
1460
                    ]);
1461
                }
1462
                foreach($old_problmes as $op) {
1463
                    if(!in_array($op,$new_problems)){
1464
                        DB::table('submission')
1465
                            ->where('cid',$cid)
1466
                            ->where('pid',$op)
1467
                            ->delete();
1468
                    }
1469
                }
1470
            }, 5);
1471
            $contestRankRaw = $this->contestRankCache($cid);
1472
            Cache::tags(['contest', 'rank'])->put($cid, $contestRankRaw);
1473
            Cache::tags(['contest', 'rank'])->put("contestAdmin$cid", $contestRankRaw);
1474
        }else{
1475
            DB::table($this->tableName)
1476
                ->where('cid',$cid)
1477
                ->update($data);
1478
        }
1479
    }
1480
1481
    public function contestUpdateProblem($cid,$problems)
1482
    {
1483
        DB::table('contest_problem')
1484
                ->where('cid',$cid)
1485
                ->delete();
1486
        foreach ($problems as $p) {
1487
            DB::table("contest_problem")->insertGetId([
1488
                "cid"=>$cid,
1489
                "number"=>$p["number"],
1490
                "ncode"=>$this->intToChr($p["number"]-1),
1491
                "pid"=>$p['pid'],
1492
                "alias"=>"",
1493
                "points"=>$p["points"]
1494
            ]);
1495
        }
1496
    }
1497
1498
    public function arrangeContest($gid, $config, $problems)
1499
    {
1500
        $cid = -1;
1501
        DB::transaction(function () use ($gid, $config, $problems,&$cid) {
1502
            $cid=DB::table($this->tableName)->insertGetId([
1503
                "gid"=>$gid,
1504
                "name"=>$config["name"],
1505
                "assign_uid"=>$config["assign_uid"],
1506
                "verified"=>0, //todo
1507
                "rated"=>0,
1508
                "anticheated"=>0,
1509
                "practice"=>$config["practice"],
1510
                "featured"=>0,
1511
                "description"=>$config["description"],
1512
                "rule"=>1, //todo
1513
                "begin_time"=>$config["begin_time"],
1514
                "end_time"=>$config["end_time"],
1515
                "vcid"=>isset($config["vcid"])?$config["vcid"]:null,
1516
                "public"=>$config["public"],
1517
                "registration"=>0, //todo
1518
                "registration_due"=>null, //todo
1519
                "registant_type"=>0, //todo
1520
                "froze_length"=>0, //todo
1521
                "status_visibility"=>2, //todo
1522
                "create_time"=>date("Y-m-d H:i:s"),
1523
                "crawled" => isset($config['vcid'])?$config['crawled'] : null,
1524
                "audit_status"=>$config["public"] ? 0 : 1
1525
            ]);
1526
1527
            foreach ($problems as $p) {
1528
                $pid=DB::table("problem")->where(["pcode"=>$p["pcode"]])->select("pid")->first()["pid"];
1529
                DB::table("contest_problem")->insert([
1530
                    "cid"=>$cid,
1531
                    "number"=>$p["number"],
1532
                    "ncode"=>$this->intToChr($p["number"]-1),
1533
                    "pid"=>$pid,
1534
                    "alias"=>"",
1535
                    "points"=>$p["points"]
1536
                ]);
1537
            }
1538
        }, 5);
1539
        return $cid;
1540
    }
1541
1542
    public function updateContestRankTable($cid,$sub)
1543
    {
1544
        $lock = Cache::lock("contestrank$cid",10);
1545
        try{
1546
            if($lock->get()){
1547
                if(Cache::tags(['contest','rank'])->get($cid) != null){
1548
                    $ret = Cache::tags(['contest','rank'])->get($cid);
1549
                    $chache=[];
1550
                    $chache['contest_info']=DB::table("contest")->where("cid", $cid)->first();
1551
                    $chache['problemSet']=DB::table("contest_problem")->join("problem", "contest_problem.pid", "=", "problem.pid")->where([
1552
                        "cid"=>$cid
1553
                    ])->orderBy('ncode', 'asc')->select("ncode", "alias", "contest_problem.pid as pid", "title")->get()->all();
1554
                    $chache['frozen_time']=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
1555
                    $chache['end_time']=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
1556
1557
                    $id = 0;
1558
1559
                    foreach($chache['problemSet'] as $key => $p){
1560
                        if ($p['pid'] == $sub['pid']){
1561
                            $chache['problemSet'][$key]['cpid'] = $key;
1562
                            $id = $key;
1563
                        }
1564
                    }
1565
1566
                    $ret = $this->updateContestRankDetail($chache['contest_info'],$chache['problemSet'][$id],$cid,$sub['uid'],$ret);
1567
                    $ret = $this->sortContestRankTable($chache['contest_info'],$cid,$ret);
1568
1569
                    if (time() < $chache['frozen_time']){
1570
                        Cache::tags(['contest', 'rank'])->put($cid, $ret);
1571
                    }
1572
                    Cache::tags(['contest', 'rank'])->put("contestAdmin$cid", $ret);
1573
                    if(time() > $chache['end_time']){
1574
                        $this->storeContestRankInMySQL($cid, $ret);
1575
                    }
1576
                }
1577
                else{
1578
                    $ret=[];
1579
                    $chache=[];
1580
                    $chache['contest_info']=DB::table("contest")->where("cid", $cid)->first();
1581
                    $chache['problemSet']=DB::table("contest_problem")->join("problem", "contest_problem.pid", "=", "problem.pid")->where([
1582
                        "cid"=>$cid
1583
                    ])->orderBy('ncode', 'asc')->select("ncode", "alias", "contest_problem.pid as pid", "title")->get()->all();
1584
                    $chache['frozen_time']=DB::table("contest")->where(["cid"=>$cid])->select(DB::raw("UNIX_TIMESTAMP(end_time)-froze_length as frozen_time"))->first()["frozen_time"];
1585
                    $chache['end_time']=strtotime(DB::table("contest")->where(["cid"=>$cid])->select("end_time")->first()["end_time"]);
1586
1587
                    if ($chache['contest_info']["registration"]) {
1588
                        $submissionUsers=DB::table("contest_participant")->where([
1589
                            "cid"=>$cid,
1590
                            "audit"=>1
1591
                        ])->select('uid')->get()->all();
1592
                    }else{
1593
                        $submissionUsers=DB::table("submission")->where([
1594
                            "cid"=>$cid
1595
                        ])->where(
1596
                            "submission_date",
1597
                            "<",
1598
                            $chache['frozen_time']
1599
                        )->select('uid')->groupBy('uid')->get()->all();
1600
                        $submissionUsersAdmin=DB::table("submission")->where([
1601
                            "cid"=>$cid
1602
                        ])->select('uid')->groupBy('uid')->get()->all();
1603
                    }
1604
1605
                    $chacheAdmin = $chache;
1606
1607
                    foreach ($submissionUsers as $s) {
1608
                        foreach ($chache['problemSet'] as $key => $p) {
1609
                            $p['cpid'] = $key;
1610
                            $ret = $this->updateContestRankDetail($chache['contest_info'],$p,$cid,$s['uid'],$ret);
1611
                        }
1612
                    }
1613
                    $ret = $this->sortContestRankTable($chache['contest_info'],$cid,$ret);
1614
                    Cache::tags(['contest', 'rank'])->put($cid, $ret);
1615
1616
                    $retAdmin=[];
1617
                    foreach ($submissionUsersAdmin as $s) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $submissionUsersAdmin does not seem to be defined for all execution paths leading up to this point.
Loading history...
1618
                        foreach ($chacheAdmin['problemSet'] as $key => $p) {
1619
                            $p['cpid'] = $key;
1620
                            $retAdmin = $this->updateContestRankDetail($chacheAdmin['contest_info'],$p,$cid,$s['uid'],$retAdmin);
1621
                        }
1622
                    }
1623
                    $retAdmin = $this->sortContestRankTable($chacheAdmin['contest_info'],$cid,$retAdmin);
1624
                    Cache::tags(['contest', 'rank'])->put("contestAdmin$cid", $retAdmin);
1625
                }
1626
            }
1627
        }catch(LockTimeoutException $e){
0 ignored issues
show
Bug introduced by
The type App\Models\LockTimeoutException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1628
            Log::warning("Contest Rank Lock Timed Out");
1629
        }finally{
1630
            optional($lock)->release();
1631
        }
1632
    }
1633
1634
    public function sortContestRankTable($contest_info,$cid,$ret)
0 ignored issues
show
Unused Code introduced by
The parameter $cid is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1634
    public function sortContestRankTable($contest_info,/** @scrutinizer ignore-unused */ $cid,$ret)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1635
    {
1636
        if ($contest_info["rule"]==1){
1637
            usort($ret, function ($a, $b) {
1638
                if ($a["score"]==$b["score"]) {
1639
                    if ($a["penalty"]==$b["penalty"]) {
1640
                        return 0;
1641
                    } elseif (($a["penalty"]>$b["penalty"])) {
1642
                        return 1;
1643
                    } else {
1644
                        return -1;
1645
                    }
1646
                } elseif ($a["score"]>$b["score"]) {
1647
                    return -1;
1648
                } else {
1649
                    return 1;
1650
                }
1651
            });
1652
        }else if ($contest_info["rule"]==2){
1653
            usort($ret, function ($a, $b) {
1654
                if ($a["score"]==$b["score"]) {
1655
                    if ($a["solved"]==$b["solved"]) {
1656
                        return 0;
1657
                    } elseif (($a["solved"]<$b["solved"])) {
1658
                        return 1;
1659
                    } else {
1660
                        return -1;
1661
                    }
1662
                } elseif ($a["score"]>$b["score"]) {
1663
                    return -1;
1664
                } else {
1665
                    return 1;
1666
                }
1667
            });
1668
        }
1669
        return $ret;
1670
    }
1671
1672
    public function updateContestRankDetail($contest_info,$problem,$cid,$uid,$ret)
1673
    {
1674
        $id = count($ret);
1675
        foreach($ret as $key => $r){
1676
            if($r['uid'] == $uid)
1677
                $id = $key;
1678
        }
1679
        if ($contest_info["rule"]==1) {
1680
            // ACM/ICPC Mode
1681
            if($id == count($ret)){
1682
                $prob_detail = [];
1683
                $totPen = 0;
1684
                $totScore = 0;
1685
            }else{
1686
                $prob_detail = $ret[$id]['problem_detail'];
1687
                $totPen=$ret[$id]['penalty'];
1688
                $totScore=$ret[$id]['score'];
1689
            };
1690
1691
            $ac_times=DB::table("submission")->where([
1692
                "cid"=>$cid,
1693
                "pid"=>$problem['pid'],
1694
                "uid"=>$uid,
1695
                "verdict"=>"Accepted"
1696
            ])->count();
1697
1698
            $last_record=DB::table("submission")->where([
1699
                "cid"=>$cid,
1700
                "pid"=>$problem['pid'],
1701
                "uid"=>$uid,
1702
            ])->orderBy('submission_date', 'desc')->first();
1703
1704
            if ($ac_times<=1 && isset($last_record) && $last_record['verdict']!="Waiting" && $last_record['verdict']!="Submission Error" && $last_record['verdict']!="System Error"){
1705
                $prob_stat=$this->contestProblemInfoACM($cid, $problem["pid"], $uid);
1706
1707
                $prob_detail[$problem['cpid']]=[
1708
                    "ncode"=>$problem["ncode"],
1709
                    "pid"=>$problem["pid"],
1710
                    "color"=>$prob_stat["color"],
1711
                    "wrong_doings"=>$prob_stat["wrong_doings"],
1712
                    "solved_time_parsed"=>$prob_stat["solved_time_parsed"]
1713
                ];
1714
                if ($prob_stat["solved"]) {
1715
                    $totPen+=$prob_stat["wrong_doings"] * 20;
1716
                    $totPen+=$prob_stat["solved_time"] / 60;
1717
                    $totScore+=$prob_stat["solved"];
1718
                }
1719
1720
                $ret[$id]=[
1721
                    "uid" => $uid,
1722
                    "name" => DB::table("users")->where([
1723
                        "id"=>$uid
1724
                    ])->first()["name"],
1725
                    "nick_name" => DB::table("group_member")->where([
1726
                        "uid" => $uid,
1727
                        "gid" => $contest_info["gid"]
1728
                    ])->where("role", ">", 0)->first()["nick_name"],
1729
                    "score" => $totScore,
1730
                    "penalty" => $totPen,
1731
                    "problem_detail" => $prob_detail
1732
                ];
1733
            }
1734
        } elseif ($contest_info["rule"]==2) {
1735
            // IOI Mode
1736
            if($id == count($ret)){
1737
                $prob_detail = [];
1738
                $totSolved = 0;
1739
                $totScore = 0;
1740
            }else{
1741
                $prob_detail = $ret[$id]['problem_detail'];
1742
                $totSolved=$ret[$id]['solved'];
1743
                $totScore=$ret[$id]['score'];
1744
            };
1745
1746
            $prob_stat=$this->contestProblemInfoIOI($cid, $problem["pid"], $uid);
1747
            $prob_detail[$problem['cpid']]=[
1748
                "ncode"=>$problem["ncode"],
1749
                "pid"=>$problem["pid"],
1750
                "color"=>$prob_stat["color"],
1751
                "score"=>$prob_stat["score"],
1752
                "score_parsed"=>$prob_stat["score_parsed"]
1753
            ];
1754
            $totSolved+=$prob_stat["solved"];
1755
            $totScore+=intval($prob_stat["score_parsed"]);
1756
1757
            $ret[$id]=[
1758
                "uid" => $uid,
1759
                "name" => DB::table("users")->where([
1760
                    "id"=> $uid
1761
                ])->first()["name"],
1762
                "nick_name" => DB::table("group_member")->where([
1763
                    "uid" => $uid,
1764
                    "gid" => $contest_info["gid"]
1765
                ])->where("role", ">", 0)->first()["nick_name"],
1766
                "score" => $totScore,
1767
                "solved" => $totSolved,
1768
                "problem_detail" => $prob_detail
1769
            ];
1770
        }
1771
        return $ret;
1772
    }
1773
1774
    public function assignMember($cid,$uid){
1775
        return DB::table("contest")->where(["cid"=>$cid])->update([
1776
            "assign_uid"=>$uid
1777
        ]);
1778
    }
1779
1780
    public function canUpdateContestTime($cid,$time = [])
1781
    {
1782
        $begin_time_new = $time['begin'] ?? null;
1783
        $end_time_new = $time['end'] ?? null;
1784
1785
        $hold_time = DB::table('contest')
1786
            ->where('cid',$cid)
1787
            ->select('begin_time','end_time')
1788
            ->first();
1789
        $begin_stamps = strtotime($hold_time['begin_time']);
1790
        $end_stamps = strtotime($hold_time['end_time']);
1791
        /*
1792
        -1 : have not begun
1793
         0 : ing
1794
         1 : end
1795
        */
1796
        $status = time() >= $end_stamps ? 1
1797
                : (time() <= $begin_stamps ? -1 : 0);
1798
        if($status === -1){
1799
            if(time() > $begin_time_new){
1800
                return false;
1801
            }
1802
            return true;
1803
        }else if($status === 0){
1804
            if($begin_time_new !== null){
1805
                return false;
1806
            }
1807
            if($end_time_new !== null){
1808
                if(strtotime($end_time_new) <= time()){
1809
                    return false;
1810
                }else{
1811
                    return true;
1812
                }
1813
            }
1814
        }else{
1815
            return false;
1816
        }
1817
1818
        return true;
1819
    }
1820
1821
    public function replyClarification($ccid, $content)
1822
    {
1823
        return DB::table("contest_clarification")->where('ccid','=',$ccid)->update([
1824
            "reply"=>$content
1825
        ]);
1826
    }
1827
1828
    public function setClarificationPublic($ccid, $public)
1829
    {
1830
        if($public)
1831
        {
1832
            return DB::table("contest_clarification")->where('ccid','=',$ccid)->update([
1833
                "public"=>1
1834
            ]);
1835
        }
1836
        else
1837
        {
1838
            return DB::table("contest_clarification")->where('ccid','=',$ccid)->update([
1839
                "public"=>0
1840
            ]);
1841
        }
1842
    }
1843
1844
    public function getContestAccount($cid)
1845
    {
1846
        return Cache::tags(['contest', 'account'])->get($cid);
1847
    }
1848
1849
    public function praticeAnalysis($cid)
1850
    {
1851
        $gid = DB::table('contest')
1852
            ->where('cid',$cid)
1853
            ->first()['gid'];
1854
        $contestRank = $this->contestRank($cid,Auth::user()->id);
1855
        if(!empty($contestRank)){
1856
            $all_problems = DB::table('problem')
1857
            ->whereIn('pid',array_column($contestRank[0]['problem_detail'],'pid'))
1858
            ->select('pid','title')
1859
            ->get()->all();
1860
        }else{
1861
            $all_problems = [];
1862
        }
1863
        $tags = DB::table('group_problem_tag')
1864
            ->where('gid', $gid)
1865
            ->whereIn('pid', array_column($all_problems,'pid'))
1866
            ->get()->all();
1867
        $all_tags = array_unique(array_column($tags,'tag'));
1868
        $memberData = [];
1869
        foreach($contestRank as $member){
1870
            $m = [
1871
                'uid' => $member['uid'],
1872
                'name' => $member['name'],
1873
                'nick_name' => $member['nick_name'],
1874
            ];
1875
            $completion = [];
1876
            foreach ($all_tags as $tag){
1877
                $completion[$tag] = [];
1878
                foreach ($tags as $t) {
1879
                    if($t['tag'] == $tag){
1880
                        foreach ($member['problem_detail'] as $pd) {
1881
                            if($pd['pid'] == $t['pid']){
1882
                                $completion[$tag][$t['pid']] = $pd['solved_time_parsed'] == "" ? 0 : 1;
1883
                            }
1884
                        }
1885
                    }
1886
                }
1887
            }
1888
            $m['completion'] = $completion;
1889
            $memberData[] = $m;
1890
        }
1891
        return $memberData;
1892
    }
1893
1894
    public function storeContestRankInMySQL($cid, $data)
1895
    {
1896
        $contestRankJson = json_encode($data);
1897
        return DB::table('contest')->where('cid','=',$cid)->update([
1898
            'rank' => $contestRankJson
1899
        ]);
1900
    }
1901
1902
    public function getContestRankFromMySQL($cid)
1903
    {
1904
        $contestRankJson = DB::table('contest')->where('cid','=',$cid)->pluck('rank')->first();
1905
        $data = json_decode($contestRankJson, true);
1906
        return $data;
1907
    }
1908
1909
    public function isVerified($cid)
1910
    {
1911
        return DB::table('contest')->where('cid','=',$cid)->pluck('verified')->first();
1912
    }
1913
1914
    public function getScrollBoardData($cid)
1915
    {
1916
        $members = DB::table("submission")
1917
            ->join('users','users.id','=','submission.uid')
1918
            ->join('contest', 'contest.cid', '=', 'submission.cid')
1919
            ->join('group_member', 'users.id', '=', 'group_member.uid')
1920
            ->where('submission.cid', $cid)->select('users.id as uid','users.name as name','group_member.nick_name as nick_name')
1921
            ->groupBy('uid')->get()->all();
1922
        $submissions = DB::table("submission")
1923
            ->where('cid', $cid)
1924
            ->select('sid', 'verdict', 'submission_date', 'pid', 'uid')
1925
            ->orderBy('submission_date')
1926
            ->get()->all();
1927
        $problems = DB::table('contest_problem')
1928
            ->where('cid', $cid)
1929
            ->select('ncode','pid')
1930
            ->orderBy('ncode')
1931
            ->get()->all();
1932
        $contest = DB::table('contest')
1933
            ->where('cid',$cid)
1934
            ->select('begin_time','end_time','froze_length')
1935
            ->first();
1936
        return [
1937
            'members' => $members,
1938
            'submissions' => $submissions,
1939
            'problems' => $problems,
1940
            'contest' => $contest,
1941
        ];
1942
    }
1943
1944
    public function judgeOver($cid)
1945
    {
1946
        $submissions =  DB::table('submission')
1947
            ->where(['cid' => $cid])
1948
            ->whereIn('verdict',['Waiting','Pending'])
1949
            ->select('sid')
1950
            ->get()->all();
1951
        if(empty($submissions)){
1952
            return [
1953
                'result' => true
1954
            ];
1955
        }else{
1956
            return [
1957
                'result' => false,
1958
                'sid' => $submissions
1959
            ];
1960
        }
1961
    }
1962
}
1963