aboutsummaryrefslogtreecommitdiff
path: root/app/routes/Forum.php
blob: 35aad913afebbddb191db1a0bd91b12bf926a041 (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
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
<?php
namespace RESTAPI\Routes;

/**
 * @author     <mlunzena@uos.de>
 * @license    GPL 2 or later
 * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
 *
 * @condition course_id ^[a-f0-9]{1,32}$
 */
class Forum extends \RESTAPI\RouteMap
{
    /**
     * List all categories of a forum
     *
     * @get /course/:course_id/forum_categories
     */
    public function getForumCategories($course_id)
    {
        if (!\ForumPerm::has('view', $course_id)) {
            $this->error(401);
        }

        $categories = \ForumCat::findBySeminar_id($course_id, 'ORDER BY pos ASC');
        $total      = sizeof($categories);
        $categories = array_splice($categories, (int)$this->offset, (int)$this->limit ?: 10);

        $json = [];
        foreach ($categories as $cat) {
            $json_cat = $cat->toArray();
            $uri = $this->urlf('/forum_category/%s', [htmlReady($json_cat['category_id'])]);
            $json_cat['course_id'] = $json_cat['seminar_id'];
            $json[$uri] = $this->categoryToJson($json_cat);
        }

        $this->etag(md5(serialize($json)));

        return $this->paginated($json, $total, compact('course_id'));
    }

    /**
     * Create a new category
     *
     * @post /course/:course_id/forum_categories
     */
    public function createForumCategory($course_id)
    {
        if (!\ForumPerm::has("add_category", $course_id)) {
            $this->error(401);
        }

        if (!isset($this->data['name']) || !mb_strlen($name = trim($this->data['name']))) {
            $this->error(400, 'Category name required.');
        }

        $category_id = \ForumCat::add($course_id, $name);
        if (!$category_id) {
            $this->error(500, 'Error creating the forum category.');
        }

        $this->redirect('forum_category/' . $category_id, 201, 'ok');
    }

    /**
     * Read a category
     *
     * @get /forum_category/:category_id
     */
    public function getForumCategory($category_id)
    {
        $category = $this->findCategory($category_id);
        $cid = $category['course_id'];

        if (!\ForumPerm::has('view', $cid)) {
            $this->error(401);
        }

        $category_json = $this->categoryToJson($category);
        $this->etag(md5(serialize($category_json)));
        return $category_json;
    }

    /**
     * Update a category
     *
     * @put /forum_category/:category_id
     */
    public function updateForumCategory($category_id)
    {
        $category = $this->findCategory($category_id);

        if (!\ForumPerm::has("edit_category", $category['course_id'])) {
            $this->error(401);
        }

        if (!isset($this->data['name']) || !mb_strlen($name = trim($this->data['name']))) {
            $this->error(400, 'Category name required.');
        }

        \ForumCat::setName($category_id, $this->data['name']);

        $this->status(204);
    }

    /**
     * Delete a category
     *
     * @delete /forum_category/:category_id
     */
    public function deleteForumCategory($category_id)
    {
        $category = $this->findCategory($category_id);
        $cid = $category['course_id'];

        if (!\ForumPerm::has("remove_category", $cid)) {
            $this->error(401);
        }

        \ForumCat::remove($category_id, $cid);

        $this->status(204);
    }

    /**
     * Show entries of a category
     *
     * @get /forum_category/:category_id/areas
     */
    public function getCategoryEntries($category_id)
    {
        $category = $this->findCategory($category_id);

        if (!\ForumPerm::has('view', $category['course_id'])) {
            $this->error(401);
        }

        $areas = $this->getAreas($category_id, $this->offset, $this->limit);

        $this->etag(md5(serialize($areas)));
        return $this->paginated($areas, $this->countAreas($category_id), compact('category_id'));
    }



    /**
     * Add a new forum entry to an existing one
     *
     * @post /forum_category/:category_id/areas
     */
    public function appendForumEntry($category_id)
    {
        $category = $this->findCategory($category_id);
        $cid = $category['course_id'];

        if (!\ForumPerm::has('add_area', $cid)) {
            $this->error(401);
        }

        if (!isset($this->data['subject']) || !mb_strlen($subject = trim($this->data['subject']))) {
            $this->error(400, 'Subject required.');
        }

        if (!isset($this->data['content'])) {
            $this->error(400, 'Content required.');
        }
        $content = trim($this->data['content']);

        $anonymous = isset($this->data['anonymous']) ? intval($this->data['anonymous']) : 0;

        $entry_id = $this->createEntry($cid, $cid, $subject, $content, $anonymous);

        \ForumCat::addArea($category_id, $entry_id);

        $this->redirect('forum_entry/' . $entry_id, 201, "ok");
    }

    /**
     * Get a forum entry
     *
     * @get /forum_entry/:entry_id
     */
    public function getForumEntry($entry_id)
    {
        $entry = \ForumEntry::getConstraints($entry_id);
        $cid   = $entry['seminar_id'];

        if (!\ForumPerm::has('view', $cid)) {
            $this->error(401);
        }

        $entry = $this->findEntry($entry_id);
        $this->lastmodified($entry->chdate);
        $this->etag(md5(serialize($entry)));
        return $entry;
    }

    /**
     * Add a new forum entry to an existing one
     *
     * @post /forum_entry/:entry_id
     */
    public function addForumEntry($parent_id)
    {
        $parent = \ForumEntry::getConstraints($parent_id);
        $cid = $parent['seminar_id'];

        $perm = self::isArea($parent) ? 'add_area' : 'add_entry';

        if (!\ForumPerm::has($perm, $cid)) {
            $this->error(401);
        }

        $subject = (string) trim($this->data['subject']);
        $content = (string) trim($this->data['content']);

        // areas and threads need a subject, postings do not
        if ($parent['depth'] < 3 && !$subject) {
            $this->error(400, 'Subject required.');
        }

        // all entries besides the area need content
        if ($parent['depth'] > 1 && !$content) {
            $this->error(400, 'Content required.');
        }

        if ($parent['depth'] >= 3 && $subject) {
            $this->error(400, 'Must not have subject here.');
        }

        $anonymous = isset($this->data['anonymous']) ? (int) $this->data['anonymous'] : 0;

        $entry_id = $this->createEntry($parent_id, $cid, $subject, $content, $anonymous);

        $this->redirect('forum_entry/' . $entry_id, 201, "ok");
    }

    /**
     * Update an existing one forum entry
     *
     * @put /forum_entry/:entry_id
     */
    public function updateForumEntry($entry_id)
    {
        $entry = \ForumEntry::getConstraints($entry_id);
        $cid = $entry['seminar_id'];

        $perm = self::isArea($entry) ? 'edit_area' : 'edit_entry';

        if (!\ForumPerm::hasEditPerms($entry_id) || !\ForumPerm::has($perm, $cid)) {
            $this->error(401);
        }

        $subject = (string) trim($this->data['subject']);
        $content = (string) trim($this->data['content']);

        // areas and threads need a subject, postings do not
        if ($entry['depth'] < 3 && !$subject) {
            $this->error(400, 'Subject required.');
        }

        // all entries besides the area need content
        if ($entry['depth'] > 1 && !$content) {
            $this->error(400, 'Content required.');
        }

        if ($entry['depth'] >= 3 && $subject) {
            $this->error(400, 'Must not have subject here.');
        }

        \ForumEntry::update($entry_id, $subject, $content);

        $this->status(204);
    }

    /**
     * Delete an entry
     *
     * @delete /forum_entry/:entry_id
     */
    public function deleteForumEntry($entry_id)
    {
        $entry = \ForumEntry::getConstraints($entry_id);
        $cid = $entry['seminar_id'];

        if (!\ForumPerm::hasEditPerms($entry_id) || !\ForumPerm::has('remove_entry', $cid)) {
            $this->error(401);
        }

        \ForumEntry::delete($entry_id);

        $this->status(204);
    }

    /*********************
     *                   *
     * PRIVATE FUNCTIONS *
     *                   *
     *********************/


    private function findEntry($entry_id)
    {
        $raw = \ForumEntry::getConstraints($entry_id);
        if ($raw === false) {
            $this->notFound();
        }

        $entry = $this->convertEntry($raw);

        $children = \ForumEntry::getEntries($entry_id, \ForumEntry::WITHOUT_CHILDS, '', 'ASC', 0, false);

        if (isset($children['list'][$entry_id])) {
            unset($children['list'][$entry_id]);
        }

        $entry['children'] = [];
        foreach (array_values($children['list']) as $childentry) {
            $entry['children'][] = $this->convertEntry($childentry);
        }

        return $entry;
    }

    public function convertEntry($raw)
    {
        $entry = [];
        foreach(words("topic_id mkdate chdate anonymous depth") as $key) {
            $entry[$key] = $raw[$key];
        }

        $hide_user = $entry['anonymous'] && $raw['user_id'] !== $GLOBALS['user']->id;

        $entry['subject']      = $raw['name'];
        $entry['user']         = $hide_user ? null : $this->urlf('/user/%s', [$raw['user_id']]);
        $entry['course']       = $this->urlf('/course/%s', [$raw['seminar_id']]);
        $entry['content_html'] = \ForumEntry::getContentAsHtml($raw['content']);
        $entry['content']      = \ForumEntry::killEdit($raw['content']);

        return $entry;
    }


    private static function isArea($entry)
    {
        return 1 === $entry['depth'];
    }

    private function createEntry($parent_id, $course_id, $subject, $content, $anonymous)
    {
        $topic_id  = self::generateID();

        $data = [
            'topic_id'    => $topic_id,
            'seminar_id'  => $course_id,
            'user_id'     => $GLOBALS['user']->id,
            'name'        => $subject,
            'content'     => $content,
            'author'      => $GLOBALS['user']->getFullName(),
            'author_host' => $_SERVER['REMOTE_ADDR'],
            'anonymous'   => (int) $anonymous
        ];
        \ForumEntry::insert($data, $parent_id);

        return $topic_id;
    }

    private function findCategory($category_id)
    {
        $result = [];

        if ($cat = \ForumCat::get($category_id)) {
            $result = $cat;
            $result['course_id'] = $cat['seminar_id'];
            $result['name']      = $cat['entry_name'];
        } else {
            $this->error(404);
        }

        return $result;
    }

    private function categoryToJson($category)
    {
        $json = $category;

        $json['course'] = $this->urlf('/course/%s', [htmlReady($json['course_id'])]);
        unset($json['course_id']);

        $json['areas'] = $this->urlf('/forum_category/%s/areas', [$json['category_id']]);
        $json['areas_count'] = $this->countAreas($json['category_id']);

        return $json;
    }

    private function countAreas($category_id)
    {
        return sizeof(\ForumCat::getAreas($category_id));
    }

    private function getAreas($category_id, $offset = 0, $limit = 10)
    {
        $offset = (int) $offset;
        $limit  = (int) $limit;

        $areas = [];

        foreach (\ForumCat::getAreas($category_id, $offset, $limit) as $area) {
            $url = $this->urlf('/forum_entry/%s', [htmlReady($area['topic_id'])]);
            $areas[$url] = $this->convertEntry($area);
        }

        return $areas;
    }

    private static function generateID()
    {
        return md5(uniqid(rand()));
    }
}