aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Courseware/CertificateShow.php
blob: 4a88b9b49a4718a54831332f6fb5026380ef41b4 (plain)
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
<?php

namespace JsonApi\Routes\Courseware;

use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\Errors\UnsupportedRequestError;
use JsonApi\NonJsonApiController;
use Courseware\Unit;
use Courseware\Certificate;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Displays a certificate for a given courseware.
 */
class CertificateShow extends NonJsonApiController
{
    protected $allowedIncludePaths = [];

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        if (!\Config::get()->COURSEWARE_CERTIFICATES_ENABLE) {
            throw new UnsupportedRequestError();
        }

        $unit = Unit::find($args['id']);
        if (!$unit) {
            throw new RecordNotFoundException('Unit could not be found');
        }

        $user = null;
        if (isset($args['user'])) {
            $user = \User::find($args['user']);
            if (!$user) {
                throw new RecordNotFoundException('User could not be found');
            }
        }

        $config = $unit->config;

        // No user given: create a preview PDF certificate
        if (!$user) {
            $file = Certificate::createPDF($unit, time(), null, $config['certificate']['image'] ?? '');

            $response->getBody()->write(file_get_contents($file));

            return $response->withHeader('Content-type', 'application/pdf');
        // User ID given: check if a certificate exists for the given unit and output the file ID.
        } else {
            $certificate = Certificate::findOneBySQL(
                "`unit_id` = :unit AND `user_id` = :user",
                ['unit' => $unit->id, 'user' => $user->id]
            );
            if (!$certificate) {
                throw new RecordNotFoundException();
            }

            $response->getBody()->write($certificate->fileref_id);

            return $response->withHeader('Content-type', 'text/plain');
        }
    }
}