-
Notifications
You must be signed in to change notification settings - Fork 767
/
DiscussionsApiController.php
805 lines (700 loc) · 31.1 KB
/
DiscussionsApiController.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
<?php
/**
* @author Todd Burry <todd@vanillaforums.com>
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
use Garden\Schema\Schema;
use Garden\Web\Data;
use Garden\Web\Exception\NotFoundException;
use Garden\Web\Exception\ServerException;
use Vanilla\DateFilterSchema;
use Vanilla\ApiUtils;
/**
* API Controller for the `/discussions` resource.
*/
class DiscussionsApiController extends AbstractApiController {
use \Vanilla\Formatting\FormatCompatTrait;
/** @var CategoryModel */
private $categoryModel;
/** @var DiscussionModel */
private $discussionModel;
/** @var Schema */
private $discussionSchema;
/** @var Schema */
private $discussionPostSchema;
/** @var Schema */
private $discussionPutCanonicalSchema;
/** @var Schema */
private $idParamSchema;
/** @var UserModel */
private $userModel;
/** @var CommentModel */
private $commentModel;
/**
* DiscussionsApiController constructor.
*
* @param DiscussionModel $discussionModel
* @param UserModel $userModel
* @param CategoryModel $categoryModel
* @param CommentModel $commentModel
*/
public function __construct(
DiscussionModel $discussionModel,
UserModel $userModel,
CategoryModel $categoryModel,
CommentModel $commentModel
) {
$this->categoryModel = $categoryModel;
$this->discussionModel = $discussionModel;
$this->userModel = $userModel;
$this->commentModel = $commentModel;
}
/**
* Get a list of the current user's bookmarked discussions.
*
* @param array $query The request query.
* @return Data
*/
public function get_bookmarked(array $query) {
$this->permission('Garden.SignIn.Allow');
$in = $this->schema([
'page:i?' => [
'description' => 'Page number. See [Pagination](https://docs.vanillaforums.com/apiv2/#pagination).',
'default' => 1,
'minimum' => 1,
'maximum' => $this->discussionModel->getMaxPages()
],
'limit:i?' => [
'description' => 'Desired number of items per page.',
'default' => $this->discussionModel->getDefaultLimit(),
'minimum' => 1,
'maximum' => 100
],
'expand?' => ApiUtils::getExpandDefinition(['insertUser', 'lastUser', 'lastPost', 'lastPost.body', 'lastPost.insertUser'])
], 'in')->setDescription('Get a list of the current user\'s bookmarked discussions.');
$out = $this->schema([':a' => $this->discussionSchema()], 'out');
$query = $in->validate($query);
list($offset, $limit) = offsetLimit("p{$query['page']}", $query['limit']);
$rows = $this->discussionModel->get($offset, $limit, [
'w.Bookmarked' => 1,
'w.UserID' => $this->getSession()->UserID
])->resultArray();
// Expand associated rows.
$this->userModel->expandUsers(
$rows,
$this->resolveExpandFields($query, ['insertUser' => 'InsertUserID', 'lastUser' => 'LastUserID', 'lastPost.insertUser' => 'LastUserID']),
['expand' => $query['expand']]
);
foreach ($rows as &$currentRow) {
$currentRow = $this->normalizeOutput($currentRow, $query['expand'] ?? []);
}
$this->expandLastCommentBody($rows, $query['expand']);
$result = $out->validate($rows);
$paging = ApiUtils::morePagerInfo($result, '/api/v2/discussions/bookmarked', $query, $in);
return new Data($result, ['paging' => $paging]);
}
/**
* Delete a discussion.
*
* @param int $id The ID of the discussion.
*/
public function delete($id) {
$this->permission('Garden.SignIn.Allow');
$in = $this->idParamSchema()->setDescription('Delete a discussion.');
$out = $this->schema([], 'out');
$row = $this->discussionByID($id);
if ($row['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Delete', $row['CategoryID']);
}
$this->discussionModel->deleteID($id);
}
/**
* Get a discussion by its numeric ID.
*
* @param int $id The discussion ID.
* @throws NotFoundException if the discussion could not be found.
* @return array
*/
public function discussionByID($id) {
$row = $this->discussionModel->getID($id, DATASET_TYPE_ARRAY);
if (!$row) {
throw new NotFoundException('Discussion');
}
return $row;
}
/**
* Get a discussion schema with minimal add/edit fields.
*
* @param string $type The type of schema.
* @return Schema Returns a schema object.
*/
public function discussionPostSchema($type = '') {
if ($this->discussionPostSchema === null) {
$this->discussionPostSchema = $this->schema(
Schema::parse([
'name',
'body',
'format:s' => 'The input format of the discussion.',
'categoryID',
'closed?',
'sink?',
'pinned?',
'pinLocation?',
])->add($this->fullSchema()),
'DiscussionPost'
);
}
return $this->schema($this->discussionPostSchema, $type);
}
/**
* Get a discussion set canonical url schema.
*
* @param string $type The type of schema.
* @return Schema Returns a schema object.
*/
public function discussionPutCanonicalSchema($type = '') {
if ($this->discussionPutCanonicalSchema === null) {
$this->discussionPutCanonicalSchema = $this->schema(
Schema::parse([
'canonicalUrl',
])->add($this->fullSchema()),
'DiscussionPutCanonical'
);
}
return $this->schema($this->discussionPutCanonicalSchema, $type);
}
/**
* Get the full discussion schema.
*
* @param string $type The type of schema.
* @return Schema Returns a schema object.
*/
public function discussionSchema($type = '') {
if ($this->discussionSchema === null) {
$this->discussionSchema = $this->schema($this->fullSchema(), 'Discussion');
}
return $this->schema($this->discussionSchema, $type);
}
/**
* Get a schema instance comprised of all available discussion fields.
*
* @return Schema Returns a schema object.
*/
protected function fullSchema() {
return Schema::parse([
'discussionID:i' => 'The ID of the discussion.',
'type:s|n' => [
//'enum' => [] // Let's find a way to fill that properly.
'description' => 'The type of this discussion if any.',
],
'name:s' => 'The title of the discussion.',
'body:s' => 'The body of the discussion.',
'categoryID:i' => 'The category the discussion is in.',
'category?' => $this->getCategoryFragmentSchema(),
'dateInserted:dt' => 'When the discussion was created.',
'dateUpdated:dt|n' => 'When the discussion was last updated.',
'dateLastComment:dt|n' => 'When the last comment was posted.',
'insertUserID:i' => 'The user that created the discussion.',
'insertUser?' => $this->getUserFragmentSchema(),
'lastUser?' => $this->getUserFragmentSchema(),
'pinned:b?' => 'Whether or not the discussion has been pinned.',
'pinLocation:s|n' => [
'enum' => ['category', 'recent'],
'description' => 'The location for the discussion, if pinned. "category" are pinned to their own category. "recent" are pinned to the recent discussions list, as well as their own category.'
],
'closed:b' => 'Whether the discussion is closed or open.',
'sink:b' => 'Whether or not the discussion has been sunk.',
'countComments:i' => 'The number of comments on the discussion.',
'countViews:i' => 'The number of views on the discussion.',
'score:i|n' => 'Total points associated with this post.',
'url:s?' => 'The full URL to the discussion.',
'canonicalUrl:s' => 'The full canonical URL to the discussion.',
'lastPost?' => $this->getPostFragmentSchema(),
'bookmarked:b' => 'Whether or not the discussion is bookmarked by the current user.',
'unread:b' => 'Whether or not the discussion should have an unread indicator.',
'countUnread:i?' => 'The number of unread comments.',
]);
}
/**
* Get a discussion.
*
* @param int $id The ID of the discussion.
* @param array $query The request query.
* @throws NotFoundException if the discussion could not be found.
* @return array
*/
public function get($id, array $query) {
$this->permission();
$this->idParamSchema();
$in = $this->schema([
'expand?' => ApiUtils::getExpandDefinition(['lastPost', 'lastPost.body', 'lastPost.insertUser']) // Allow addons to expand additional fields.
], ['DiscussionGet', 'in'])->setDescription('Get a discussion.');
$out = $this->schema($this->discussionSchema(), 'out');
$query = $in->validate($query);
$this->getEventManager()->fireFilter('discussionsApiController_getFilters', $this, $id, $query);
$row = $this->discussionByID($id);
if (!$row) {
throw new NotFoundException('Discussion');
}
$this->discussionModel->categoryPermission('Vanilla.Discussions.View', $row['CategoryID']);
$this->userModel->expandUsers($row, ['InsertUserID', 'LastUserID'], ['expand' => true]);
$row = $this->normalizeOutput($row, $query["expand"] ?? []);
$rows = [&$row];
$this->expandLastCommentBody($rows, $query['expand'] ?? []);
$result = $out->validate($row);
// Allow addons to modify the result.
$result = $this->getEventManager()->fireFilter('discussionsApiController_getOutput', $result, $this, $in, $query, $row);
return $result;
}
/**
* Normalize a database record to match the Schema definition.
*
* @param array $dbRecord Database record.
* @param array|bool $expand
* @return array Return a Schema record.
*/
public function normalizeOutput(array $dbRecord, $expand = []) {
$dbRecord['Announce'] = (bool)$dbRecord['Announce'];
$dbRecord['Bookmarked'] = (bool)$dbRecord['Bookmarked'];
$dbRecord['Url'] = discussionUrl($dbRecord);
$this->formatField($dbRecord, 'Body', $dbRecord['Format']);
$dbRecord['Attributes'] = new \Vanilla\Attributes($dbRecord['Attributes']);
if ($this->getSession()->User) {
$dbRecord['unread'] = $dbRecord['CountUnreadComments'] !== 0
&& ($dbRecord['CountUnreadComments'] !== true || dateCompare(val('DateFirstVisit', $this->getSession()->User), $dbRecord['DateInserted']) <= 0);
if ($dbRecord['CountUnreadComments'] !== true && $dbRecord['CountUnreadComments'] > 0) {
$dbRecord['countUnread'] = $dbRecord['CountUnreadComments'];
}
} else {
$dbRecord['unread'] = false;
}
if ($this->isExpandField('lastPost', $expand)) {
$lastPost = [
'discussionID' => $dbRecord['DiscussionID'],
'dateInserted' => $dbRecord['DateLastComment'],
"insertUserID" => $dbRecord["LastUserID"],
];
if ($dbRecord['LastCommentID']) {
$lastPost['CommentID'] = $dbRecord['LastCommentID'];
$lastPost['name'] = sprintft('Re: %s', $dbRecord['Name']);
$lastPost['url'] = commentUrl($lastPost, true);
} else {
$lastPost['name'] = $dbRecord['Name'];
$lastPost['url'] = $dbRecord['Url'];
}
if ($this->isExpandField('lastPost.insertUser', $expand) || $this->isExpandField('lastUser', $expand) && array_key_exists('LastUser', $dbRecord)) {
$lastPost['insertUser'] = $dbRecord['LastUser'];
if (!$this->isExpandField('lastUser', $expand)) {
unset($dbRecord['LastUser']);
}
}
$dbRecord['lastPost'] = $lastPost;
}
// This shouldn't be necessary, but the db allows nulls for dateLastComment.
if (empty($dbRecord['DateLastComment'])) {
$dbRecord['DateLastComment'] = $dbRecord['DateInserted'];
}
// The Category key will hold a category fragment in API responses. Ditch the default string.
if (array_key_exists('Category', $dbRecord) && !is_array($dbRecord['Category'])) {
unset($dbRecord['Category']);
}
$schemaRecord = ApiUtils::convertOutputKeys($dbRecord);
$schemaRecord['type'] = isset($schemaRecord['type']) ? lcfirst($schemaRecord['type']) : null;
// Allow addons to hook into the normalization process.
$options = ['expand' => $expand];
$result = $this->getEventManager()->fireFilter('discussionsApiController_normalizeOutput', $schemaRecord, $this, $options);
return $result;
}
/**
* Get a discussion's quote data.
*
* @param int $id The ID of the discussion.
*
* @return array The discussion quote data.
*
* @throws NotFoundException If the record with the given ID can't be found.
* @throws \Exception if no session is available.
* @throws \Vanilla\Exception\PermissionException if the user does not have the specified permission(s).
* @throws \Garden\Schema\ValidationException If the output schema is configured incorrectly.
*/
public function get_quote($id) {
$this->permission();
$this->idParamSchema();
$in = $this->schema([], ['in'])->setDescription('Get a discussions embed data.');
$out = $this->schema($this->quoteSchema(), 'out');
$discussion = $this->discussionByID($id);
$discussion['Url'] = discussionUrl($discussion);
if ($discussion['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.View', $discussion['CategoryID']);
}
$isRich = $discussion['Format'] === 'Rich';
$discussion['bodyRaw'] = $isRich ? json_decode($discussion['Body'], true) : $discussion['Body'];
$this->userModel->expandUsers($discussion, ['InsertUserID'], ['expand' => true]);
$result = $out->validate($discussion);
return $result;
}
/**
* Get the schema for discussion quote data.
*
* @return Schema
*/
private function quoteSchema(): Schema {
return Schema::parse([
'discussionID:i' => 'The ID of the discussion.',
'name:s' => 'The title of the discussion',
'bodyRaw:s|a' => 'The raw body of the discussion. This can be an array of rich operations or a string for other formats',
'dateInserted:dt' => 'When the discussion was created.',
'dateUpdated:dt|n' => 'When the discussion was last updated.',
'insertUser' => $this->getUserFragmentSchema(),
'url:s' => 'The full URL to the discussion.',
'format:s' => 'The original format of the discussion',
]);
}
/**
* Get a discussion for editing.
*
* @param int $id The ID of the discussion.
* @throws NotFoundException if the discussion could not be found.
* @return array
*/
public function get_edit($id) {
$this->permission('Garden.SignIn.Allow');
$this->idParamSchema()->setDescription('Get a discussion for editing.');
$out = $this->schema(
Schema::parse([
'discussionID',
'name',
'body',
'format:s' => 'The input format of the discussion.',
'categoryID',
'sink',
'closed',
'pinned',
'pinLocation',
])->add($this->fullSchema()),
['DiscussionGetEdit', 'out']
)->addFilter('', [\Vanilla\Formatting\Formats\RichFormat::class, 'editBodyFilter']);
$row = $this->discussionByID($id);
$row['Url'] = discussionUrl($row);
if ($row['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Edit', $row['CategoryID']);
}
$result = $out->validate($row);
$this->applyFormatCompatibility($result, 'body', 'format');
return $result;
}
/**
* Get an ID-only discussion record schema.
*
* @param string $type The type of schema.
* @return Schema Returns a schema object.
*/
public function idParamSchema($type = 'in') {
if ($this->idParamSchema === null) {
$this->idParamSchema = $this->schema(
Schema::parse(['id:i' => 'The discussion ID.']),
$type
);
}
return $this->schema($this->idParamSchema, $type);
}
/**
* List discussions.
*
* @param array $query The query string.
* @return Data
*/
public function index(array $query) {
$this->permission();
$in = $this->schema([
'categoryID:i?' => [
'description' => 'Filter by a category.',
'x-filter' => [
'field' => 'd.CategoryID'
],
],
'dateInserted?' => new DateFilterSchema([
'description' => 'When the discussion was created.',
'x-filter' => [
'field' => 'd.DateInserted',
'processor' => [DateFilterSchema::class, 'dateFilterField'],
],
]),
'dateUpdated?' => new DateFilterSchema([
'description' => 'When the discussion was updated.',
'x-filter' => [
'field' => 'd.DateUpdated',
'processor' => [DateFilterSchema::class, 'dateFilterField'],
],
]),
'dateLastComment?' => new DateFilterSchema([
'description' => 'When the last comment was posted.',
'x-filter' => [
'field' => 'd.DateLastComment',
'processor' => [DateFilterSchema::class, 'dateFilterField'],
],
]),
'type:s?' => [
'description' => 'Filter by discussion type.',
'x-filter' => [
'field' => 'd.Type'
],
],
'followed:b' => [
'default' => false,
'description' => 'Only fetch discussions from followed categories. Pinned discussions are mixed in.'
],
'pinned:b?' => 'Whether or not to include pinned discussions. If true, only return pinned discussions. Cannot be used with the pinOrder parameter.',
'pinOrder:s?' => [
'default' => 'first',
'description' => 'If including pinned posts, in what order should they be integrated? When "first", discussions pinned to a specific category will only be affected if the discussion\'s category is passed as the categoryID parameter. Cannot be used with the pinned parameter.',
'enum' => ['first', 'mixed'],
],
'page:i?' => [
'description' => 'Page number. See [Pagination](https://docs.vanillaforums.com/apiv2/#pagination).',
'default' => 1,
'minimum' => 1,
'maximum' => $this->discussionModel->getMaxPages()
],
'limit:i?' => [
'description' => 'Desired number of items per page.',
'default' => $this->discussionModel->getDefaultLimit(),
'minimum' => 1,
'maximum' => 100
],
'insertUserID:i?' => [
'description' => 'Filter by author.',
'x-filter' => [
'field' => 'd.InsertUserID',
],
],
'expand?' => ApiUtils::getExpandDefinition(['category', 'insertUser', 'lastUser', 'lastPost', 'lastPost.body', 'lastPost.insertUser'])
], ['DiscussionIndex', 'in'])->setDescription('List discussions.');
$out = $this->schema([':a' => $this->discussionSchema()], 'out');
$query = $this->filterValues($query);
$query = $in->validate($query);
$where = ApiUtils::queryToFilters($in, $query);
list($offset, $limit) = offsetLimit("p{$query['page']}", $query['limit']);
if (array_key_exists('categoryID', $where)) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.View', $where['categoryID']);
}
// Allow addons to update the where clause.
$where = $this->getEventManager()->fireFilter('discussionsApiController_indexFilters', $where, $this, $in, $query);
if ($query['followed']) {
$where['Followed'] = true;
$query['pinOrder'] = 'mixed';
}
$pinned = array_key_exists('pinned', $query) ? $query['pinned'] : null;
if ($pinned === true) {
$announceWhere = array_merge($where, ['d.Announce >' => '0']);
$rows = $this->discussionModel->getAnnouncements($announceWhere, $offset, $limit)->resultArray();
} else {
$pinOrder = array_key_exists('pinOrder', $query) ? $query['pinOrder'] : null;
if ($pinOrder == 'first') {
$announcements = $this->discussionModel->getAnnouncements($where, $offset, $limit)->resultArray();
$discussions = $this->discussionModel->getWhereRecent($where, $limit, $offset, false)->resultArray();
$rows = array_merge($announcements, $discussions);
} else {
$where['Announce'] = 'all';
$rows = $this->discussionModel->getWhereRecent($where, $limit, $offset, false)->resultArray();
}
}
// Expand associated rows.
$this->userModel->expandUsers(
$rows,
$this->resolveExpandFields($query, ['insertUser' => 'InsertUserID', 'lastUser' => 'LastUserID', 'lastPost.insertUser' => 'LastUserID']),
['expand' => $query['expand']]
);
if ($this->isExpandField('category', $query['expand'])) {
$this->categoryModel->expandCategories($rows);
}
foreach ($rows as &$currentRow) {
$currentRow = $this->normalizeOutput($currentRow, $query['expand']);
}
$this->expandLastCommentBody($rows, $query['expand']);
$result = $out->validate($rows, true);
// Allow addons to modify the result.
$result = $this->getEventManager()->fireFilter('discussionsApiController_indexOutput', $result, $this, $in, $query, $rows);
$whereCount = count($where);
$isWhereOptimized = (isset($where['d.CategoryID']) && ($whereCount === 1 || ($whereCount === 2 && isset($where['Announce']))));
if ($whereCount === 0 || $isWhereOptimized) {
$paging = ApiUtils::numberedPagerInfo($this->discussionModel->getCount($where), '/api/v2/discussions', $query, $in);
} else {
$paging = ApiUtils::morePagerInfo($rows, '/api/v2/discussions', $query, $in);
}
return new Data($result, ['paging' => $paging]);
}
/**
* Update a discussion.
*
* @param int $id The ID of the discussion.
* @param array $body The request body.
* @throws NotFoundException if unable to find the discussion.
* @return array
*/
public function patch($id, array $body) {
$this->permission('Garden.SignIn.Allow');
$this->idParamSchema('in');
$in = $this->discussionPostSchema('in')->setDescription('Update a discussion.');
$out = $this->schema($this->discussionSchema(), 'out');
$body = $in->validate($body, true);
$row = $this->discussionByID($id);
$discussionData = ApiUtils::convertInputKeys($body);
$discussionData['DiscussionID'] = $id;
$categoryID = $row['CategoryID'];
if ($row['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Edit', $categoryID);
}
if (array_key_exists('CategoryID', $discussionData) && $categoryID !== $discussionData['CategoryID']) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Add', $discussionData['CategoryID']);
$categoryID = $discussionData['CategoryID'];
}
$this->fieldPermission($body, 'closed', 'Vanilla.Discussions.Close', $categoryID);
$this->fieldPermission($body, 'pinned', 'Vanilla.Discussions.Announce', $categoryID);
$this->fieldPermission($body, 'sink', 'Vanilla.Discussions.Sink', $categoryID);
$this->discussionModel->save($discussionData);
$this->validateModel($this->discussionModel);
$result = $this->discussionByID($id);
$result = $this->normalizeOutput($result);
return $out->validate($result);
}
/**
* Add a discussion.
*
* @param array $body The request body.
* @throws ServerException if the discussion could not be created.
* @return array
*/
public function post(array $body) {
$this->permission('Garden.SignIn.Allow');
$in = $this->discussionPostSchema('in')->setDescription('Add a discussion.');
$out = $this->discussionSchema('out');
$body = $in->validate($body);
$categoryID = $body['categoryID'];
$this->discussionModel->categoryPermission('Vanilla.Discussions.Add', $categoryID);
$this->fieldPermission($body, 'closed', 'Vanilla.Discussions.Close', $categoryID);
$this->fieldPermission($body, 'pinned', 'Vanilla.Discussions.Announce', $categoryID);
$this->fieldPermission($body, 'sink', 'Vanilla.Discussions.Sink', $categoryID);
$discussionData = ApiUtils::convertInputKeys($body);
$id = $this->discussionModel->save($discussionData);
$this->validateModel($this->discussionModel);
if (!$id) {
throw new ServerException('Unable to insert discussion.', 500);
}
$row = $this->discussionByID($id);
$this->userModel->expandUsers($row, ['InsertUserID', 'LastUserID']);
$row = $this->normalizeOutput($row);
$result = $out->validate($row);
return $result;
}
/**
* Bookmark a discussion.
*
* @param int $id The ID of the discussion.
* @param array $body The request body.
* @return array
*/
public function put_bookmark($id, array $body) {
$this->permission('Garden.SignIn.Allow');
$this->idParamSchema('in');
$in = $this
->schema(['bookmarked:b' => 'Pass true to bookmark or false to remove bookmark.'], 'in')
->setDescription('Bookmark a discussion.');
$out = $this->schema(['bookmarked:b' => 'The current bookmark value.'], 'out');
$body = $in->validate($body);
$row = $this->discussionByID($id);
$bookmarked = intval($body['bookmarked']);
$this->discussionModel->categoryPermission('Vanilla.Discussions.View', $row['CategoryID']);
$this->discussionModel->bookmark($id, $this->getSession()->UserID, $bookmarked);
$result = $this->discussionByID($id);
return $out->validate($result);
}
/**
* Set canonical url for a discussion.
*
* @param int $id The ID of the discussion.
* @param array $body The request body.
* Ex: ["canonicalUrl" => "https://mydomain.com/some+path/"]
* @throws NotFoundException If unable to find the discussion.
* @return array
*/
public function put_canonicalUrl($id, array $body) {
$this->permission('Garden.SignIn.Allow');
$this->idParamSchema('in');
$in = $this->discussionPutCanonicalSchema('in')->setDescription('Set canonical url for a discussion.');
$out = $this->schema($this->discussionSchema(), 'out');
$body = $in->validate($body);
$row = $this->discussionByID($id);
if (!empty($row['Attributes']['CanonicalUrl'] ?? '')) {
throw new \Garden\Web\Exception\ClientException('Canonical url already set for this discussion.', 409);
};
$categoryID = $row['CategoryID'];
if ($row['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Edit', $categoryID);
}
$attributes = $row['Attributes'] ?? [];
$attributes['CanonicalUrl'] = $body['canonicalUrl'];
$this->discussionModel->setProperty($id, 'Attributes', dbencode($attributes));
$result = $this->discussionByID($id);
$result = $this->normalizeOutput($result);
return $out->validate($result);
}
/**
* Remove canonical url for a discussion.
*
* @param int $id The ID of the discussion.
* @throws NotFoundException If unable to find the discussion.
* @return array
*/
public function delete_canonicalUrl($id) {
$this->permission('Garden.SignIn.Allow');
$in =$this->schema(
Schema::parse(['id:i' => 'The discussion ID.']),
'in'
);
$out = $this->schema([], 'out');
$row = $this->discussionByID($id);
$categoryID = $row['CategoryID'];
if ($row['InsertUserID'] !== $this->getSession()->UserID) {
$this->discussionModel->categoryPermission('Vanilla.Discussions.Edit', $categoryID);
}
$attributes = $row['Attributes'];
if (!empty($attributes['CanonicalUrl'] ?? '')) {
unset($attributes['CanonicalUrl']);
$this->discussionModel->setProperty($id, 'Attributes', dbencode($attributes));
}
}
/**
* Expand the body of the last comment.
*
* @param array $rows
* @param array|bool $expand
*/
private function expandLastCommentBody(array &$rows, $expand): void {
if (!$this->isExpandField('lastPost', $expand) || !$this->isExpandField('lastPost.body', $expand)) {
return;
}
$commentIDs = [];
foreach ($rows as $row) {
$id = $row['lastPost']['commentID'] ?? null;
if (is_int($id)) {
$commentIDs[] = $id;
}
}
if (!empty($commentIDs)) {
$comments = $this->commentModel->getWhere(['commentID' => $commentIDs], '', 'asc', count($commentIDs))->resultArray();
$comments = array_column($comments, null, 'CommentID');
} else {
$comments = [];
}
foreach ($rows as &$row) {
$id = $row['lastPost']['commentID'] ?? null;
if (isset($comments[$id])) {
$row['lastPost']['body'] = \Gdn::formatService()->renderHTML($comments[$id]['Body'], $comments[$id]['Format']);
} else {
$row['lastPost']['body'] = $row['body'];
}
}
}
}