aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Wiki/WikiCreate.php
blob: 015a16545c3cf95ca6658e2c2c1285be654e7987 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php

namespace JsonApi\Routes\Wiki;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\ConflictException;
use JsonApi\Errors\InternalServerError;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\JsonApiController;
use JsonApi\Routes\ValidationTrait;
use JsonApi\Schemas\WikiPage;


/**
 * Create a news where the range is the user himself.
 */
class WikiCreate extends JsonApiController
{
    use ValidationTrait;

    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameters)
     */
    public function __invoke(Request $request, Response $response, $args)
    {
        $json = $this->validate($request);

        // TODO: has to be Course or Institute
        $range = \RangeFactory::find($args['id']);
        if (!$range || $range instanceof \User) {
            throw new RecordNotFoundException();
        }

        $user = $this->getUser($request);
        if (!Authority::canCreateWiki($user, $range)) {
            throw new AuthorizationFailedException();
        }

        $name = self::arrayGet($json, 'data.attributes.name') ?? self::arrayGet($json, 'data.attributes.keyword');

        if (\WikiPage::findOneBySQL('`range_id` = ? AND `name` = ?', [$range->id, $name])) {
            throw new ConflictException('Wiki page already exists.');
        }

        if (!$wiki = $this->createWikiFromJSON($user, $range, $json)) {
            throw new InternalServerError('Could not create the wiki page.');
        }

        return $this->getCreatedResponse($wiki);
    }

    protected function createWikiFromJSON(\User $user, $range, $json)
    {
        $name    = self::arrayGet($json, 'data.attributes.name') ?? self::arrayGet($json, 'data.attributes.keyword');
        $content = self::arrayGet($json, 'data.attributes.content');
        $content = \Studip\Markup::purifyHtml($content);

        $wiki = new \WikiPage();
        $wiki->name = $name;
        $wiki->content = $content;
        $wiki->chdate = time();
        $wiki->user_id = $user->id;
        $wiki->range_id = $range->id;
        $wiki->store();

        return $wiki;
    }

    protected function validateResourceDocument($json, $data)
    {
        $name = self::arrayGet($json, 'data.attributes.name', '');
        if (empty($name)) {
            return 'Wikis must have a title (keyword)';
        }

        if (!preg_match(WikiPage::REGEXP_KEYWORD, $name)) {
            return 'Malformed wiki keyword.';
        }
    }
}