-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathProblemController.php
482 lines (432 loc) · 18.9 KB
/
ProblemController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
<?php declare(strict_types=1);
namespace App\Controller\API;
use App\DataTransferObject\ContestProblemArray;
use App\DataTransferObject\ContestProblemPut;
use App\DataTransferObject\ContestProblemWrapper;
use App\Entity\Contest;
use App\Entity\ContestProblem;
use App\Entity\Problem;
use App\Service\ConfigurationService;
use App\Service\DOMJudgeService;
use App\Service\EventLogService;
use App\Service\ImportExportService;
use App\Service\ImportProblemService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\QueryBuilder;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\Model;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Yaml\Yaml;
/**
* @extends AbstractRestController<ContestProblem, ContestProblem|ContestProblemWrapper>
*/
#[Rest\Route('/contests/{cid}/problems')]
#[OA\Tag(name: 'Problems')]
#[OA\Parameter(ref: '#/components/parameters/cid')]
#[OA\Parameter(ref: '#/components/parameters/strict')]
#[OA\Response(ref: '#/components/responses/InvalidResponse', response: 400)]
#[OA\Response(ref: '#/components/responses/Unauthenticated', response: 401)]
#[OA\Response(ref: '#/components/responses/Unauthorized', response: 403)]
#[OA\Response(ref: '#/components/responses/NotFound', response: 404)]
class ProblemController extends AbstractRestController implements QueryObjectTransformer
{
public function __construct(
EntityManagerInterface $entityManager,
DOMJudgeService $DOMJudgeService,
ConfigurationService $config,
EventLogService $eventLogService,
protected readonly ImportProblemService $importProblemService,
protected readonly ImportExportService $importExportService
) {
parent::__construct($entityManager, $DOMJudgeService, $config, $eventLogService);
}
/**
* Add one or more problems.
*
* @return int[]
* @throws BadRequestHttpException
* @throws NonUniqueResultException
*/
#[IsGranted('ROLE_API_PROBLEM_EDITOR')]
#[Rest\Post('/add-data')]
#[OA\RequestBody(
required: true,
content: new OA\MediaType(
mediaType: 'multipart/form-data',
schema: new OA\Schema(
properties: [
new OA\Property(
property: 'data',
description: 'The problems.yaml or problems.json file to import.',
type: 'string',
format: 'binary'
),
]
)
)
)]
#[OA\Response(response: 200, description: "Returns the API ID's of the added problems.")]
public function addProblemsAction(Request $request): array
{
// Note we use /add-data as URL here since we already have a route listening
// on POST /, which is to add a problem ZIP.
$contestId = $this->getContestId($request);
/** @var Contest $contest */
$contest = $this->em->getRepository(Contest::class)->find($contestId);
if ($contest->isLocked()) {
$contestUrl = $this->generateUrl('jury_contest', ['contestId' => $contestId], UrlGeneratorInterface::ABSOLUTE_URL);
throw new AccessDeniedHttpException('Contest is locked, go to ' . $contestUrl . ' to unlock it.');
}
/** @var UploadedFile|null $file */
$file = $request->files->get('data');
if (!$file) {
throw new BadRequestHttpException("Data field is missing.");
}
// Note: we read the JSON as YAML, since any JSON is also YAML and this allows us
// to import files with YAML inside them that match the JSON format
$data = Yaml::parseFile($file->getRealPath(), Yaml::PARSE_DATETIME);
if ($this->importExportService->importProblemsData($contest, $data, $ids, $messages)) {
return $ids;
}
$message = "Error while adding problems";
if (!empty($messages)) {
$message .= ': ' . $this->dj->jsonEncode($messages);
}
throw new BadRequestHttpException($message);
}
/**
* Get all the problems for this contest.
* @throws NonUniqueResultException
*/
#[Rest\Get('')]
#[OA\Response(
response: 200,
description: 'Returns all the problems for this contest',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: ContestProblem::class))
)
)]
#[OA\Parameter(ref: '#/components/parameters/idlist')]
public function listAction(Request $request): Response
{
// Make sure we clear the entity manager class, for when this method is called multiple times
// by internal requests.
$this->em->clear();
// This method is overwritten, because we need to add ordinal values.
$queryBuilder = $this->getQueryBuilder($request);
$objects = $queryBuilder
->getQuery()
->getResult();
if (empty($objects)) {
return $this->renderData($request, []);
}
$objects = array_map($this->transformObject(...), $objects);
$ordinalArray = new ContestProblemArray($objects);
$objects = $ordinalArray->getItems();
if ($request->query->has('ids')) {
$ids = $request->query->all('ids');
$ids = array_unique($ids);
$objects = [];
foreach ($ordinalArray->getItems() as $item) {
/** @var ContestProblemWrapper|ContestProblem $contestProblem */
$contestProblem = $item->getContestProblemWrapper();
if ($contestProblem instanceof ContestProblemWrapper) {
$contestProblem = $contestProblem->getContestProblem();
}
if (in_array($contestProblem->getExternalId(), $ids)) {
$objects[] = $item;
}
}
if (count($objects) !== count($ids)) {
throw new NotFoundHttpException('One or more objects not found');
}
}
return $this->renderData($request, $objects);
}
/**
* Add a problem to this contest.
* @return array{problem_id: string, messages: array<string, string[]>}
* @throws NonUniqueResultException
*/
#[IsGranted('ROLE_API_PROBLEM_EDITOR')]
#[Rest\Post('')]
#[OA\RequestBody(
required: true,
content: new OA\MediaType(
mediaType: 'multipart/form-data',
schema: new OA\Schema(
required: ['zip'],
properties: [
new OA\Property(
property: 'zip',
description: 'The problem archive to import',
type: 'string',
format: 'binary'
),
new OA\Property(
property: 'problem',
description: 'Optional: problem id to update.',
type: 'string'
),
]
)
)
)]
#[OA\Response(
response: 200,
description: 'Returns the ID of the imported problem and any messages produced',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'problem_id',
description: 'The ID of the imported problem',
type: 'integer'
),
new OA\Property(
property: 'messages',
type: 'array',
items: new OA\Items(
description: 'Messages produced while adding problems',
type: 'string'
)
),
],
type: 'object'
)
)]
public function addProblemAction(Request $request): array
{
$contestId = $this->getContestId($request);
/** @var Contest $contest */
$contest = $this->em->getRepository(Contest::class)->find($contestId);
if ($contest->isLocked()) {
$contestUrl = $this->generateUrl('jury_contest', ['contestId' => $contestId], UrlGeneratorInterface::ABSOLUTE_URL);
throw new AccessDeniedHttpException('Contest is locked, go to ' . $contestUrl . ' to unlock it.');
}
return $this->importProblemService->importProblemFromRequest($request, $contestId);
}
/**
* Unlink a problem from this contest.
*/
#[IsGranted('ROLE_API_PROBLEM_EDITOR')]
#[Rest\Delete('/{id}')]
#[OA\Response(response: 204, description: 'Problem unlinked from contest succeeded')]
#[OA\Parameter(ref: '#/components/parameters/id')]
public function unlinkProblemAction(Request $request, string $id): Response
{
$problem = $this->em->createQueryBuilder()
->from(Problem::class, 'p')
->select('p')
->andWhere(sprintf('%s = :id', $this->getIdField()))
->setParameter('id', $id)
->getQuery()
->getOneOrNullResult();
if (empty($problem)) {
throw new NotFoundHttpException(sprintf('Object with ID \'%s\' not found', $id));
}
$cid = $this->getContestId($request);
/** @var ContestProblem|null $contestProblem */
$contestProblem = $this->em->createQueryBuilder()
->from(ContestProblem::class, 'cp')
->select('cp')
->andWhere('cp.contest = :contest')
->andWhere('cp.problem = :problem')
->setParameter('contest', $cid)
->setParameter('problem', $problem)
->getQuery()
->getOneOrNullResult();
if (empty($contestProblem)) {
throw new NotFoundHttpException(sprintf('Object with ID \'%s\' not found', $id));
}
$contest = $contestProblem->getContest();
if ($contest->isLocked()) {
$contestUrl = $this->generateUrl('jury_contest', ['contestId' => $contest->getCid()], UrlGeneratorInterface::ABSOLUTE_URL);
throw new AccessDeniedHttpException('Contest is locked, go to ' . $contestUrl . ' to unlock it.');
}
$this->em->remove($contestProblem);
$id = [$contestProblem->getCid(), $contestProblem->getProbid()];
$this->dj->auditlog('contest_problem', implode(', ', $id), 'deleted');
$this->eventLogService->log('problem', $contestProblem->getProbid(),
EventLogService::ACTION_DELETE, $cid,
null, null, false);
return new Response('', Response::HTTP_NO_CONTENT);
}
/**
* Link an existing problem to this contest.
*/
#[IsGranted('ROLE_API_PROBLEM_EDITOR')]
#[Rest\Put('/{id}')]
#[OA\Response(
response: 200,
description: 'Returns the linked problem for this contest',
content: new OA\JsonContent(ref: new Model(type: ContestProblem::class))
)]
#[OA\Parameter(ref: '#/components/parameters/id')]
public function linkProblemAction(
#[MapRequestPayload(validationFailedStatusCode: Response::HTTP_BAD_REQUEST)]
ContestProblemPut $contestProblemPut,
Request $request,
string $id
): Response {
$problem = $this->em->createQueryBuilder()
->from(Problem::class, 'p')
->select('p')
->andWhere(sprintf('%s = :id', $this->getIdField()))
->setParameter('id', $id)
->getQuery()
->getOneOrNullResult();
if (empty($problem)) {
throw new NotFoundHttpException(sprintf('Object with ID \'%s\' not found', $id));
}
$cid = $this->getContestId($request);
$contest = $this->em->getRepository(Contest::class)->find($cid);
if ($contest->isLocked()) {
$contestUrl = $this->generateUrl('jury_contest', ['contestId' => $contest->getCid()], UrlGeneratorInterface::ABSOLUTE_URL);
throw new AccessDeniedHttpException('Contest is locked, go to ' . $contestUrl . ' to unlock it.');
}
/** @var ContestProblem|null $contestProblem */
$contestProblem = $this->em->createQueryBuilder()
->from(ContestProblem::class, 'cp')
->select('cp')
->andWhere('cp.contest = :contest')
->andWhere('cp.problem = :problem')
->setParameter('contest', $cid)
->setParameter('problem', $problem)
->getQuery()
->getOneOrNullResult();
if (!empty($contestProblem)) {
throw new BadRequestHttpException('Problem already linked to contest');
}
$contest = $this->em->getRepository(Contest::class)->find($this->getContestId($request));
$contestProblem = (new ContestProblem())
->setContest($contest)
->setProblem($problem)
->setShortname($contestProblemPut->label)
->setColor($contestProblemPut->rgb ?? $contestProblemPut->color)
->setPoints($contestProblemPut->points)
->setLazyEvalResults($contestProblemPut->lazyEvalResults);
$this->em->persist($contestProblem);
$this->em->flush();
$fullId = [$contestProblem->getCid(), $contestProblem->getProbid()];
$this->dj->auditlog('contest_problem', implode(', ', $fullId), 'added');
$this->eventLogService->log('problem', $contestProblem->getProbid(),
EventLogService::ACTION_CREATE, $cid,
null, null, false);
return $this->singleAction($request, $id);
}
/**
* Get the given problem for this contest.
* @throws NonUniqueResultException
*/
#[Rest\Get('/{id}')]
#[OA\Response(
response: 200,
description: 'Returns the given problem for this contest',
content: new OA\JsonContent(ref: new Model(type: ContestProblem::class))
)]
#[OA\Parameter(ref: '#/components/parameters/id')]
public function singleAction(Request $request, string $id): Response
{
$ordinalArray = new ContestProblemArray($this->listActionHelper($request));
$object = null;
foreach ($ordinalArray->getItems() as $item) {
/** @var ContestProblemWrapper|ContestProblem $contestProblem */
$contestProblem = $item->getContestProblemWrapper();
if ($contestProblem instanceof ContestProblemWrapper) {
$contestProblem = $contestProblem->getContestProblem();
}
if ($contestProblem->getExternalId() == $id) {
$object = $item;
break;
}
}
if ($object === null) {
throw new NotFoundHttpException(sprintf('Object with ID \'%s\' not found', $id));
}
return $this->renderData($request, $object);
}
/**
* Get the statement for given problem for this contest.
* @throws NonUniqueResultException
*/
#[Rest\Get('/{id}/statement')]
#[OA\Response(
response: 200,
description: 'Returns the given problem statement for this contest',
content: new OA\MediaType(mediaType: 'application/pdf')
)]
#[OA\Parameter(ref: '#/components/parameters/id')]
public function statementAction(Request $request, string $id): Response
{
$queryBuilder = $this->getQueryBuilder($request)
->leftJoin('p.problemStatementContent', 'content')
->addSelect('content')
->setParameter('id', $id)
->andWhere(sprintf('%s = :id', $this->getIdField()));
// Get the one result; we know it's only one since we filter on ID
$contestProblemData = $queryBuilder->getQuery()->getOneOrNullResult();
if (empty($contestProblemData)) {
throw new NotFoundHttpException(sprintf('Problem with ID \'%s\' not found', $id));
}
// The result contains the contest problem as well as the test data
// count which should not be disclosed to the contestants; so get only
// the problem.
/** @var ContestProblem $contestProblem */
$contestProblem = $contestProblemData[0];
if ($contestProblem->getProblem()->getProblemstatementType() !== 'pdf') {
throw new NotFoundHttpException(sprintf('Problem with ID \'%s\' has no PDF statement', $id));
}
return $contestProblem->getProblem()->getProblemStatementStreamedResponse();
}
protected function getQueryBuilder(Request $request): QueryBuilder
{
$contestId = $this->getContestId($request);
/** @var Contest $contest */
$contest = $this->em->getRepository(Contest::class)->find($contestId);
$queryBuilder = $this->em->createQueryBuilder()
->from(ContestProblem::class, 'cp')
->join('cp.problem', 'p')
->leftJoin('p.testcases', 'tc')
->select('cp, p, COUNT(tc.testcaseid) AS testdatacount')
->andWhere('cp.contest = :cid')
->andWhere('cp.allowSubmit = 1')
->setParameter('cid', $contestId)
->orderBy('cp.shortname')
->groupBy('cp.problem');
// For non-API-reader users, only expose the problems after the contest has started.
if (!$this->dj->checkrole('api_reader') && $contest->getStartTimeObject()->getTimestamp() > time()) {
$queryBuilder->andWhere('1 = 0');
}
return $queryBuilder;
}
protected function getIdField(): string
{
return 'p.externalid';
}
/**
* Transform the given object before returning it from the API.
* @param array{0: ContestProblem, testdatacount: int} $object
*/
public function transformObject($object): ContestProblem|ContestProblemWrapper
{
/** @var ContestProblem $problem */
$problem = $object[0];
$testDataCount = (int)$object['testdatacount'];
if ($this->dj->checkrole('jury')) {
return new ContestProblemWrapper($problem, $testDataCount);
} else {
return $problem;
}
}
}