owned this note
owned this note
Published
Linked with GitHub
# Judge0 IDE整合
將Judge0 IDE與Domjudge進行整合,能在Domjudge上進行程式碼編輯,並且讓Judge0 IDE以submit的方式,讓Judgehost可以去做執行。

Judge IDE功能如下:
* **Submit** :與Domjudge的submit機制相同。
* **Run** :讓使用者能夠測試自己所撰寫的程式碼。
* **Change code** :能夠替換先前送出的程式碼。
* **stdin** :能夠輸入input測資。
* **stdout** :顯示執行(Run)結果。
1.新增Judge0 IDE頁面
===
# 後端
## src/Controller/Team/MiscController.php
在MiscControoler.php中新增兩個頁面,分別是compile與compile_api。
```
compile頁面 : 為Judge0 IDE的基礎頁面,並且於後端中處理submission與history的資料。
compile_api頁面 : 用於查詢該submission的output。
```
```php=
/*-----CCU-----*/
/**
* @Route("/compile", name="team_compile")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Exception
*/
public function compileAction(Request $request){
$user = $this->dj->getUser();
$team = $user->getTeam();
$team1 = $team ;
$teamId = $team->getTeamid();
$contest = $this->dj->getCurrentContest($teamId);
$problem = $this->em->getRepository(Problem::class)->findAll();
$formData = [];
$formData['problem'] = $problem;
$form = $this->formFactory
->createBuilder(CompileType::class)
->setAction('')->setData($formData)
->getForm();
$form->handleRequest($request);
$data = [
'team' => $team,
'contest' => $contest,
'refresh' => [
'after' => 30,
'url' => $this->generateUrl('team_index'),
'ajax' => true,
],
'maxWidth' => $this->dj->dbconfig_get('team_column_width', 0),
'form' => $form->createView()
];
//find history data
$submit_history = $this->em->createQueryBuilder()
->from(Submission::class, 's')
->select('s')
->andWhere('s.submit_type != :submit_type')
->andWhere('s.teamid = :teamid')
->setParameter(':submit_type', 0)
->setParameter(':teamid', $teamId)
->addOrderBy('s.submitid ','DESC')
->setMaxResults(30)
->getQuery()
->getResult();
$historys = array();
$times = array();
//save history name = problem_name + time , and value = sourcecode
foreach ($submit_history as $history)
{
$files = $history->getFiles();
$name = $history->getProblem()->getName();
$sourcecode = $files[0]->getSourcecode();
$date = date("Y-m-d H:i:s", (int)$history->getSubmitTime());
$historys[$name." ".$date] = $sourcecode;
}
$data['historys'] = $historys;
// if use ajax to post data, then check the code is not null
if ($request->isXmlHttpRequest()) {
if($request->request->get('code') != null)
{if ($contest === null) {
$this->addFlash('danger', 'No active contest');
} elseif (!$this->dj->checkrole('jury') && !$contest->getFreezeData()->started()) {
$this->addFlash('danger', 'Contest has not yet started');
} else {
$code = str_replace("\n","\r\n",$request->request->get('code'));
$probid = $request->request->get('problem');
$stdin = $request->request->get('stdin');
$compile_run = $request->request->get('compile_run');
$problem = $this->em->createQueryBuilder()
->from(Problem::class, 'p')
->select('p')
->andWhere('p.probid = :probid')
->setParameter(':probid', $probid)
->getQuery()
->getResult();
$language = $request->request->get('language');
$entryPoint = $form->get('entry_point')->getData() ?: null;
$files = [];
$team = $user->getTeam();
$compile_submit = [];
$compile_submit['stdin'] = $stdin;
$compile_submit['code'] = $code;
$compile_submit['name'] = 'main.'.$language;
$compile_submit['compile_run'] = $compile_run;
$submission = $this->submissionService->submitSolution(
$team, $probid, $contest, $language, $files,
null, $entryPoint, null, null, $message,$compile_submit
);
//if submission success,return submission id
if ($submission) {
$this->dj->auditlog('submission', $submission->getSubmitid(), 'added',
'via teampage', null, $contest->getCid());
$this->addFlash(
'success',
'<strong>Submission done!</strong> Watch for the verdict in the list below.'
);
$submitid = $submission->getSubmitid();
$jsonData[1] = $submitid;
return new JsonResponse($jsonData);
} else {
$this->addFlash('danger', $message);
}
}
}
return $this->render('team/compile.html.twig', $data);
} else {
return $this->render('team/compile.html.twig', $data);
}
}
/**
* @Route("/compile_api", name="team_compile_api")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Exception
*/
//use submitid to find the output
public function compileAction1(Request $request){
$submitid = $request->request->get('submitid');
$judging = $this->em->createQueryBuilder()
->from(Judging::class, 'jud')
->select('jud')
->andWhere('jud.submitid = :id')
->setParameter(':id', $submitid)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if($judging)
{
$judging_run = $this->em->createQueryBuilder()
->from(JudgingRun::class, 'run')
->select('run')
->andWhere('run.judgingid = :id')
->setParameter(':id', $judging->getJudgingid())
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
else
{
return 0 ;
}
if($judging_run)
{
$run_output = $this->em->createQueryBuilder()
->from(JudgingRunOutput::class, 'out')
->select('out')
->andWhere('out.run = :id')
->setParameter(':id', $judging_run->getRunid())
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
else
{
return 0 ;
}
$jsonData[1] = $run_output->getOutputRun();
return new JsonResponse($jsonData);
}
}
/*-----CCU-----*/
```
## src/Form/Type/CompileType.php
新增用於Judge0 IDE submit的表單,並且增加語言限制,讓語言會隨著題目的語言限制而改動。
```php=
<?php declare(strict_types=1);
namespace App\Form\Type;
use App\Entity\Language;
use App\Entity\Problem;
use App\Service\DOMJudgeService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
//新增函式庫
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormInterface;
class CompileType extends AbstractType
{
/**
* @var DOMJudgeService
*/
protected $dj;
/**
* @var EntityManagerInterface
*/
protected $em;
public function __construct(DOMJudgeService $dj, EntityManagerInterface $em)
{
$this->dj = $dj;
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->dj->getUser();
$contest = $this->dj->getCurrentContest($user->getTeamid());
$builder->add('problem', EntityType::class, [
'class' => Problem::class,
'label' => false,
'query_builder' => function (EntityRepository $er) use ($contest) {
return $er->createQueryBuilder('p')
->join('p.contest_problems', 'cp', Join::WITH, 'cp.contest = :contest')
->select('p', 'cp')
->andWhere('cp.allowSubmit = 1')
->setParameter(':contest', $contest)
->addOrderBy('cp.shortname');
},
'choice_label' => function (Problem $problem) {
return sprintf('%s - %s', $problem->getContestProblems()->first()->getShortName(), $problem->getName());
},
'placeholder' => 'Select a problem',
]);
$builder->add('language', EntityType::class, [
'class' => Language::class,
'label' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('l')
->andWhere('l.allowSubmit = 1');
},
'choice_label' => 'name',
'placeholder' => 'Select a language',
]);
$builder->add('entry_point', TextType::class, [
'label' => 'Entry point',
'required' => false,
'help' => 'The entry point for your code.',
'constraints' => [
new Callback(function ($value, ExecutionContextInterface $context) {
/** @var Form $form */
$form = $context->getRoot();
/** @var Language $language */
$langid = $form->get('language')->getData();
dump($langid);
if($langid != null)
{
$language = $this->em->createQueryBuilder()
->from(Language::class, 'l')
->select('l')
->andWhere('l.langid = :langid')
->setParameter(':langid', $langid)
->getQuery()
->getResult();
if ($language[0]->getRequireEntryPoint() && empty($value)) {
$message = sprintf('%s required, but not specified',
$language[0]->getEntryPointDescription() ?: 'Entry point');
$context
->buildViolation($message)
->atPath('entry_point')
->addViolation();
}
}
}),
]
]);
$formProblemModifier = function (FormInterface $form, $contests = []) {
/** @var Contest[] $contests */
$problems = $this->em->createQueryBuilder()
->from(Problem::class, 'p')
->join('p.contest_problems', 'cp')
->select('p')
->andWhere('cp.problem IN (:contests)')
->setParameter(':contests', $contests)
->addOrderBy('p.name')
->getQuery()
->getResult();
$problem2 = $this->em->createQueryBuilder()
->from(Language::class, 'l')
->select('l')
->andWhere('l.allowSubmit = 1')
->getQuery()
->getResult();
foreach ($problems as $problem){
$ids = $problem->getRestrictionLanguages();
}
if($ids == [])
{
$i = 0;
$problems = $this->em->createQueryBuilder()
->from(Language::class, 'l')
->select('l')
->andWhere('l.allowSubmit = 1')
->getQuery()
->getResult();
$ids= [];
foreach ($problem2 as $problem){
array_push($ids,$problem->getName());
}
}
$newid = [];
foreach ($ids as $id)
{
$problem3 = $this->em->createQueryBuilder()
->from(Language::class, 'l')
->select('l')
->andWhere('l.allowSubmit = 1')
->andWhere('l.name = :id')
->setParameter(':id', $id)
->getQuery()
->getResult();
$newid = $newid + array($id => $problem3[0]->getLangid());
}
$form->add('language', ChoiceType::class, [
'required' => false,
'choices' => $newid,
'placeholder' => 'Select a language',
]);
$builder->get('problem')->addEventListener(FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formProblemModifier) {
$contests = $event->getForm()->getData();
dump($contests);
$formProblemModifier($event->getForm()->getParent(), $contests);
});
}
public function onPreSetData(FormEvent $event)
{
$product = $event->getData();
$form = $event->getForm();
if (!$product || null === $product->getId()) {
$form->add('name', TextType::class);
}
}
public function configureOptions(OptionsResolver $resolver)
{
// $resolver->setDefaults(['data_class' => Problem::class]);
}
}
```
# 前端
```
若要實現Judge IDE功能,需要於donjudge/domserver/etc/nginx-conf-inner檔案中設定CSP政策。
```
## templates/team/menu.html.twig
於Domjudge的menu中新增IDE的按鈕。
```htmlmixed=
{#-----CCU-----#}
<li class="nav-item {% if current_route in ['team_scoreboard', 'team_team'] %}active{% endif %}">
<a class="nav-link" href="{{ path('team_compile') }}"><i class="fa fa-window-maximize"></i> IDE</a>
</li>
{#-----CCU-----#}
{#-----CCU-----#}
{#close the submit button if the page is in team_compile#}
{% if is_granted('ROLE_JURY') or current_team_contest.freezeData.started %}
<a class="nav-link justify-content-center " data-ajax-modal data-ajax-modal-after="initSubmitModal" href="{{ path('team_submit') }}">
<button type="button" class="btn btn-success btn-sm"{% if current_route == 'team_compile' %} style="visibility: hidden"{% endif %}>
<i class="fas fa-cloud-upload-alt"></i> Submit
</button>
</a>
{% else %}
<a class="nav-link justify-content-center">
<button type="button" class="btn btn-success btn-sm disabled" disabled>
<i class="fas fa-cloud-upload-alt"></i> Submit
</button>
</a>
{% endif %}
{#-----CCU-----#}
```
## templates/team/compile.html.twig
IDE主頁面,導入Judge0 IDE內容。
```php=
{% extends 'team/base.html.twig' %}
{% block title %}{{ team.name }} - {{ parent() }}{% endblock %}
{% block messages %}{% endblock %}
{% block content %}
{% endblock %}
{% block extrafooter %}
<script>
var $flash = null;
function saveFlash() {
$flash = $('[data-flash-messages]').children();
}
function setFlashAndProgress() {
var $newProgress = $('[data-ajax-refresh-target] > [data-progress-bar]');
if ($newProgress.length) {
var $oldProgress = $('body > [data-progress-bar]');
$oldProgress.html($newProgress.children());
$newProgress.remove();
}
$('[data-flash-messages]').html($flash);
}
function markSeen($elem) {
$elem.closest('tr').removeClass('unseen');
}
</script>
{% include 'team/partials/compiler_content.html.twig' %}
{% endblock %}
```
## templates/team/partials/compiler_content.html.twig
新增Judge0 IDE內容頁面,刪除過多的語言和廣告後,將submit表單、CSS、Javascript置入頁面之中。
```htmlmixed=
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Free and open-source online code editor that allows you to write and execute code from a rich set of languages.">
<meta name="keywords" content="online editor, online code editor, online ide, online compiler, online interpreter, run code online, learn programming online,
online debugger, programming in browser, online code runner, online code execution, debug online, debug C code online, debug C++ code online,
programming online, snippet, snippets, code snippet, code snippets, pastebin, execute code, programming in browser, run c online, run C++ online,
run java online, run python online, run ruby online, run c# online, run rust online, run pascal online, run basic online">
<meta name="author" content="Herman Zvonimir Došilović">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta property="og:title" content="Judge0 IDE - Free and open-source online code editor">
<meta property="og:description" content="Free and open-source online code editor that allows you to write and execute code from a rich set of languages.">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/golden-layout/1.5.9/goldenlayout.min.js" integrity="sha256-NhJAZDfGgv4PiB+GVlSrPdh3uc75XXYSM4su8hgTchI=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/golden-layout/1.5.9/css/goldenlayout-base.css" integrity="sha256-oIDR18yKFZtfjCJfDsJYpTBv1S9QmxYopeqw2dO96xM=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/golden-layout/1.5.9/css/goldenlayout-dark-theme.css" integrity="sha256-ygw8PvSDJJUGLf6Q9KIQsYR3mOmiQNlDaxMLDOx9xL0=" crossorigin="anonymous" />
<script>
var require = {
paths: {
"vs": "https://unpkg.com/monaco-editor/min/vs",
"monaco-vim": "https://unpkg.com/monaco-vim/dist/monaco-vim",
"monaco-emacs": "https://unpkg.com/monaco-emacs/dist/monaco-emacs"
}
};
</script>
<script src="https://unpkg.com/monaco-editor/min/vs/loader.js"></script>
<script src="https://unpkg.com/monaco-editor@0.18.1/min/vs/editor/editor.main.nls.js"></script>
<script src="https://unpkg.com/monaco-editor@0.18.1/min/vs/editor/editor.main.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha256-9mbkOfVho3ZPXfM7W8sV2SndrGDuh7wuyLjtsWeTI1Q=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js" integrity="sha256-t8GepnyPmw9t+foMh3mKNvcorqNHamSKtKRxxpUEgFI=" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">
<title>Judge0 IDE - Free and open-source online code editor</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-83802640-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-83802640-2');
</script>
<script type="text/javascript">window.$crisp=[];window.CRISP_WEBSITE_ID="ee4621ff-c682-44ac-8cfa-1835beddb98a";(function(){d=document;s=d.createElement("script");s.src="https://client.crisp.chat/l.js";s.async=1;d.getElementsByTagName("head")[0].appendChild(s);})();</script>
</head>
<body>
<div id="site-navigation" class="ui small inverted menu">
<div id="site-header" class="header item">
<a href="/">
<h2>Judge0 IDE</h2>
</a>
</div>
<div class="left menu">
<div class="ui dropdown item site-links on-hover">
File <i class="dropdown icon"></i>
<div class="menu">
<div class="item" onclick="downloadSource()"><i class="download icon"></i> Download</div>
</div>
</div>
<div class="item borderless">
</div>
<div class="row">
<table class="table table-sm table-striped">
<tr>
<td>
<select id="select-language" class="ui dropdown">
<option value="49" mode="c">C (GCC 8.3.0)</option>
<option selected value="54" mode="cpp">C++ (GCC 9.2.0)</option>
{#
<option value="1004" mode="java">Java (OpenJDK 14.0.1)</option>
<option value="63" mode="javascript">JavaScript (Node.js 12.14.0)</option>
<option value="68" mode="php">PHP (7.4.1)</option>
<option value="70" mode="python">Python (2.7.17)</option>
#}
</select></td>
{# add the compileType form #}
<td> {{ form_row(form.problem) }}</td>
<td>{{ form_row(form.language, {'label':false}) }}</td>
<div class="form-group" data-entry-point>
{{ form_label(form.entry_point) }}
{{ form_widget(form.entry_point) }}
{{ form_help(form.entry_point) }}
</div>
<td>
<div class="form-group">
<button type="submit" id="compile_submit" class="btn-success btn" ><i class="fas fa-cloud-upload-alt"></i> Submit
</button>
</div>
</td>
<td><button class="btn-danger btn" id="compile_run"><i class="play icon"></i>Run (F9) </button></td>
{# add the history selected #}
<td><select id = "historys" class="form-control custom-select form-control">
<option >Select history sumbit</option>
{% for key,value in historys %}
<option value=" {{ value }} ">{{ key }}
{% endfor %}
</select>
</td>
<td><button class="btn-primary btn" id="change_code"><i class="fas fa-book"></i> Change code</button></td>
</tr>
</table>
</div>
<div class="item fitted borderless wide screen only">
<div class="ui input">
<input id="compiler-options" type="hidden" placeholder="Compiler options"></input>
</div>
</div>
<div class="item borderless wide screen only">
<div class="ui input">
<input id="command-line-arguments" type="hidden" placeholder="Command line arguments"></input>
</div>
</div>
</div>
<div class="right menu">
</div>
</div>
<div id="site-content"></div>
<div id="site-modal" class="ui modal">
<div class="header">
<i class="close icon"></i>
<span id="title"></span>
</div>
<div class="scrolling content"></div>
<div class="actions">
<div class="ui small labeled icon cancel button">
<i class="remove icon"></i>
Close (ESC)
</div>
</div>
</div>
<div id="site-settings" class="ui modal">
<i class="close icon"></i>
<div class="header">
<i class="cog icon"></i>
Settings
</div>
<div class="content">
<div class="ui form">
<div class="inline fields">
<label>Editor Mode</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="editor-mode" value="normal" checked="checked">
<label>Normal</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="editor-mode" value="vim">
<label>Vim</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="editor-mode" value="emacs">
<label>Emacs</label>
</div>
</div>
</div>
<div class="inline field">
<div class="ui checkbox">
<input type="checkbox" name="redirect-output">
<label>Redirect stderr to stdout</label>
</div>
</div>
</div>
</div>
</div>
<div id="site-footer">
<span id="donate-line">
<a class="item" target="_blank" href="https://www.patreon.com/hermanzdosilovic"><i class="patreon icon" style="color: #f06553;"></i> Become a Patron</a>
·
<a class="item" target="_blank" href="https://paypal.me/hermanzdosilovic"><i class="paypal icon" style="color: #00457c;"></i></i> Donate with PayPal</a>
</span>
<div id="editor-status-line"></div>
<span>© 2016-2021 <a href="https://judge0.com">Judge0</a> · Powered by <a href="https://rapidapi.com/hermanzdosilovic/api/judge0">the most advanced open-source online code execution system</a>
<span id="status-line"></span>
</div>
<script>
let CLF_config = {
selector: ".changelogfy-widget",
app_id: "f6f982d0-3d91-4b1c-a3ce-b0eb54606c4e"
};
</script>
<script async src="https://widget.changelogfy.com/index.js"></script>
</body>
<style>
{% include "team/partials/css/compiler_ide.css" %}
</style>
<script>
{% include "team/partials/js/ide.js" %}
{% include "team/partials/js/download.js" %}
</script>
</html>
```
2.submission函式修改
===
## src/Entity/Submission.php
新增`$input(blobtext)`與`$submit_type(int)`欄位於submission資料表,將submission進行分類。
```
$input : 儲存從IDE送出的input
$submit_type : 儲存submission的種類
```
```
submission種類:
0 : 原先Domjudge的submit
1 : 從IDE送出的submit
2 : 在IDE中進行測試的submit
```
```php=
/*-----CCU-----*/
/**
* @ORM\Column(type="blobtext", length=4294967295, options={"comment"="input data","default"="NULL"},nullable=true)
* @Serializer\Exclude()
*/
private $input;
/**
* @var int
* @ORM\Column(type="integer", name="submit_type",
* options={"comment"="If submission is run test form IDE ",
* "default"="0"},
* nullable=false)
* @Serializer\Exclude()
*/
private $submit_type = false;
/*-----CCU-----*/
/*-----CCU-----*/
public function getInput(): ?string
{
return $this->input;
}
public function setInput(?string $input): self
{
$this->input = $input;
return $this;
}
public function getSubmitType(): ?int
{
return $this->submit_type;
}
public function setSubmitType(?int $submit_type): self
{
$this->submit_type = $submit_type;
return $this;
}
/*-----CCU-----*/
```
當新增完後,於terminal中執行資料庫更新指令
```
php bin/console doctrine:schema:update --force
```
## src/Service/SubmissionService.php
>## function submitSloution
於函式參數中新增`$compile_submit`陣列,將IDE傳送過來的資料包裝成`$compile_submit`陣列後,送給函式進行後續處理。
```php=
/*-----CCU-----*/
array $compile_submit = null
/*-----CCU-----*/
```
```
$compile_submit陣列由四個資料組成:
1.$compile_submit['stdin'] : 儲存input
2.$compile_submit['code'] : 儲存原始碼
3.$compile_submit['name'] : 儲存檔案名稱(統一為main.xx)
4.$compile_submit['compile_run'] : 儲存送出種類
```
將submission中所有處理input、sourcecode、file的內容進行替換,並且新增當`$compile_submit`資料存在時的判斷及除錯。
```php=
/*-----CCU-----*/
if (count($files) == 0 && $compile_submit == null ) {
throw new BadRequestHttpException("No files specified.");
}
/*-----CCU-----*/
/*-----CCU-----*/
//add new judge by $compile_submit
if($compile_submit == null)
{
foreach ($files as $file) {
if (!$file->isValid() && $compile_submit == null) {
$message = $file->getErrorMessage();
return null;
}
$filenames[$file->getClientOriginalName()] = $file->getClientOriginalName();
}
}
if (count($files) != count($filenames) && $compile_submit == null ) {
$message = "Duplicate filenames detected.";
return null;
}
/*-----CCU-----*/
/*-----CCU-----*/
if($compile_submit == null)
{
foreach ($files as $file) {
if (!$file->isReadable() && $compile_submit == null ) {
$message = sprintf("File '%s' not found (or not readable).", $file->getRealPath());
return null;
}
if (!preg_match(self::FILENAME_REGEX, $file->getClientOriginalName()) && $compile_submit == null ) {
$message = sprintf("Illegal filename '%s'.", $file->getClientOriginalName());
return null;
}
$totalSize += $file->getSize();
}
}
else
{
//totalSize = code string length
$totalSize = strlen($compile_submit['code']);
}
if ($language->getFilterCompilerFiles()) {
$matchesExtension = false;
foreach ($language->getExtensions() as $extension) {
$extensionLength = strlen($extension);
//need to change cpp
if($compile_submit == null)
{
if (substr($file->getClientOriginalName(), -$extensionLength) === $extension) {
$matchesExtension = true;
break;
}
}
else
{
if (substr($compile_submit['code'], -$extensionLength) === $extension) {
$matchesExtension = true;
break;
}
}
}
if ($matchesExtension) {
$extensionMatchCount++;
}
}
if ($language->getFilterCompilerFiles() && $extensionMatchCount === 0 && $compile_submit == null) {
$message = sprintf(
"None of the submitted files match any of the allowed " .
"extensions for %s (allowed: %s)",
$language->getName(), implode(', ', $language->getExtensions())
);
return null;
}
/*-----CCU-----*/
// First look up any expected results in file, so as to minimize the
// SQL transaction time below.
/*-----CCU-----*/
if ($this->dj->checkrole('jury')) {
if($compile_submit == null)
{
$results = self::getExpectedResults(file_get_contents($files[0]->getRealPath()),
$this->dj->dbconfig_get('results_remap', []));
}
else
{
$results = self::getExpectedResults($compile_submit['code'],
$this->dj->dbconfig_get('results_remap', []));
}
}
/*-----CCU-----*/
/*-----CCU-----*/
if($compile_submit['stdin']!= null )
{
$submission->setInput($compile_submit['stdin']);
}
if($compile_submit['compile_run']!= null )
{
$submission->setSubmitType((int)$compile_submit['compile_run']);
}
// Add expected results from source. We only do this for jury submissions
// to prevent accidental auto-verification of team submissions.
if ($this->dj->checkrole('jury') && !empty($results)) {
$submission->setExpectedResults($results);
}
//丟進submission(insert)
$this->em->persist($submission);
//設定+丟進 submissionFile(insert) 對應submission id
if($compile_submit == null)
{
foreach ($files as $rank => $file) {
$submissionFile = new SubmissionFile();
$submissionFile
->setFilename($file->getClientOriginalName())
->setRank($rank)
->setSourcecode(file_get_contents($file->getRealPath()));
$submissionFile->setSubmission($submission);
$this->em->persist($submissionFile);
}
}
else
{
//set the ide code to file and sourcecode
$submissionFile = new SubmissionFile();
$submissionFile
->setFilename($compile_submit['name'])
->setRank(0)
->setSourcecode($compile_submit['code']);
$submissionFile->setSubmission($submission);
$this->em->persist($submissionFile);
}
/*-----CCU-----*/
```
3.修改Judgehost中讀取測資的函式及API
===
# 後端
## judgehost/lib/judge/judgedaemon.main.php
>## function fetchTestcase
於**Judgehost**中,當輸入與輸出的測資為首次讀取,會將測資**再次比對**後儲存成檔案至Judgehost,若測資為IDE傳送的submission類別,則要更改測資設定,因此將submitid傳送給API進行處理,判斷是否有input。
```php=
/*-----CCU-----*/
$url = sprintf('testcases/%s/file/%s/%s', $tc['testcaseid'], $inout, $row['submitid']);
$content = request($url, 'GET', '', FALSE);
/*-----CCU-----*/
```
## src/Controller/API/JudgehostController.php
>## function getNextJudgingAction
負責處理Judging的API(getNextJudgingAction)。
當有submission有input時,要進行測資的替換,將輸入測資替換IDE的input並且給一個假的輸出測資,假的輸出測資必須與。
```php=
/*-----CCU-----*/
if($submission->getInput() == null )
{
foreach ($testcases as $testcase) {
$testcase_md5s[$testcase->getRank()] = array(
'md5sum_input' => $testcase->getMd5sumInput(),
'md5sum_output' => $testcase->getMd5sumOutput(),
'testcaseid' => $testcase->getTestcaseid(),
'rank' => $testcase->getRank(),
'task' => $testcase->getTask(),
);
}
}
else
{
//change input to submission input and change output to any string (need to same with getFileAction)
$testcase_md5s[1] = array(
'md5sum_input' => md5($submission->getInput()),
'md5sum_output' => md5("compiler4"),
'testcaseid' => $testcases[0]->getTestcaseid(),
'rank' => 1,
);
}
/*-----CCU-----*/
```
## src/Controller/API/JudgehostController.php
>## function getFileAction
於fetchTestcase中比對測資時,用於取得資料庫中測資的API。
新增submitid參數,並且判斷submission是否有從IDE送出的input進行替換,假輸出測資需要和getNextJudgingAction中的假輸出測資一樣。
```php=
/*-----CCU-----*/
/**
* Get the input or output file for the given testcase
* @param string $id
* @param string $type
* @param string $submitid
* @return string
* @throws \Doctrine\ORM\NonUniqueResultException
* @IsGranted({"ROLE_JURY", "ROLE_JUDGEHOST"})
* @Rest\Get("/{id}/file/{type}/{submitid}")
* @SWG\Parameter(ref="#/parameters/id")
* @SWG\Parameter(
* name="type",
* type="string",
* in="path",
* enum={"input", "output"},
* description="Type of file to get",
* required=true
* )
* @SWG\Response(
* response="200",
* description="Information about the file of the given testcase",
* @SWG\Schema(type="string", description="Base64-encoded file contents")
* )
*/
public function getFileAction(string $id, string $type , string $submitid)
{
if (!in_array($type, ['input', 'output'])) {
throw new BadRequestHttpException('Only \'input\' or \'output\' file allowed');
}
/** @var TestcaseContent|null $testcaseContent */
$testcaseContent = $this->em->createQueryBuilder()
->from(TestcaseContent::class, 'tcc')
->select('tcc')
->andWhere('tcc.testcase = :id')
->setParameter(':id', $id)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
$stdin = $this->em->createQueryBuilder()
->from(Submission::class, 'st')
->select('st')
->andWhere('st.submitid = :id')
->setParameter(':id', $submitid)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if ($testcaseContent === null) {
throw new NotFoundHttpException(sprintf('Cannot find testcase \'%s\'', $id));
}
$contents = $type === 'input'
? $testcaseContent->getInput()
: $testcaseContent->getOutput();
$input = $stdin->getInput();
if($input != null)
{
//change input to submission input and change output to any string (need to same with getNextJudgingAction)
$contents = $type === 'input'
? $input
: "compiler4";
}
else
{
$contents = $type === 'input'
? $testcaseContent->getInput()
: $testcaseContent->getOutput();
}
if ($contents === null) {
throw new NotFoundHttpException(sprintf('Cannot find the ' . $type . ' of testcase \'%s\'', $id));
}
return base64_encode($contents);
}
/*-----CCU-----*/
```