-
Notifications
You must be signed in to change notification settings - Fork 23
/
locallib.php
2282 lines (1920 loc) · 83.1 KB
/
locallib.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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Internal library of functions for module moodleoverflow
*
* All the moodleoverflow specific functions, needed to implement the module
* logic, should go here. Never include this file from your lib.php!
*
* @package mod_moodleoverflow
* @copyright 2017 Kennet Winter <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use mod_moodleoverflow\anonymous;
use mod_moodleoverflow\capabilities;
use mod_moodleoverflow\event\post_deleted;
use mod_moodleoverflow\readtracking;
use mod_moodleoverflow\review;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once(dirname(__FILE__) . '/lib.php');
/**
* Get all discussions in a moodleoverflow instance.
*
* @param object $cm
* @param int $page
* @param int $perpage
*
* @return array
*/
function moodleoverflow_get_discussions($cm, $page = -1, $perpage = 0) {
global $DB, $CFG, $USER;
// User must have the permission to view the discussions.
$modcontext = context_module::instance($cm->id);
if (!capabilities::has(capabilities::VIEW_DISCUSSION, $modcontext)) {
return [];
}
// Filter some defaults.
if ($perpage <= 0) {
$limitfrom = 0;
$limitamount = $perpage;
} else if ($page != -1) {
$limitfrom = $page * $perpage;
$limitamount = $perpage;
} else {
$limitfrom = 0;
$limitamount = 0;
}
// Get all name fields as sql string snippet.
if ($CFG->branch >= 311) {
$allnames = \core_user\fields::for_name()->get_sql('u', false, '', '', false)->selects;
} else {
$allnames = get_all_user_name_fields(true, 'u');
}
$postdata = 'p.id, p.modified, p.discussion, p.userid, p.reviewed';
$discussiondata = 'd.name, d.timemodified, d.timestart, d.usermodified, d.firstpost';
$userdata = 'u.email, u.picture, u.imagealt';
if ($CFG->branch >= 311) {
$usermodifiedfields = \core_user\fields::for_name()->get_sql('um', false, 'um',
'', false)->selects .
', um.email AS umemail, um.picture AS umpicture, um.imagealt AS umimagealt';
} else {
$usermodifiedfields = get_all_user_name_fields(true, 'um', null, 'um') .
', um.email AS umemail, um.picture AS umpicture, um.imagealt AS umimagealt';
}
$params = [$cm->instance];
$whereconditions = ['d.moodleoverflow = ?', 'p.parent = 0'];
if (!capabilities::has(capabilities::REVIEW_POST, $modcontext)) {
$whereconditions[] = '(p.reviewed = 1 OR p.userid = ?)';
$params[] = $USER->id;
}
$wheresql = join(' AND ', $whereconditions);
// Retrieve and return all discussions from the database.
$sql = "SELECT $postdata, $discussiondata, $allnames, $userdata, $usermodifiedfields
FROM {moodleoverflow_discussions} d
JOIN {moodleoverflow_posts} p ON p.discussion = d.id
LEFT JOIN {user} u ON p.userid = u.id
LEFT JOIN {user} um ON d.usermodified = um.id
WHERE $wheresql
ORDER BY d.timestart DESC, d.id DESC";
return $DB->get_records_sql($sql, $params, $limitfrom, $limitamount);
}
/**
* Prints latest moodleoverflow discussions.
*
* @param object $moodleoverflow MoodleOverflow to be printed.
* @param object $cm
* @param int $page Page mode, page to display (optional).
* @param int $perpage The maximum number of discussions per page (optional).
*/
function moodleoverflow_print_latest_discussions($moodleoverflow, $cm, $page = -1, $perpage = 25) {
global $CFG, $USER, $OUTPUT, $PAGE;
// Check if the course supports the module.
if (!$cm) {
if (!$cm = get_course_and_cm_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
throw new moodle_exception('invalidcoursemodule');
}
}
// Set the context.
$context = context_module::instance($cm->id);
// If the perpage value is invalid, deactivate paging.
if ($perpage <= 0) {
$perpage = 0;
$page = -1;
}
// Check some capabilities.
$canstartdiscussion = moodleoverflow_user_can_post_discussion($moodleoverflow, $cm, $context);
$canviewdiscussions = has_capability('mod/moodleoverflow:viewdiscussion', $context);
$canreviewposts = has_capability('mod/moodleoverflow:reviewpost', $context);
$canseeuserstats = has_capability('mod/moodleoverflow:viewanyrating', $context);
// Print a button if the user is capable of starting
// a new discussion or if the selfenrol is aviable.
if ($canstartdiscussion) {
$buttontext = get_string('addanewdiscussion', 'moodleoverflow');
$buttonurl = new moodle_url('/mod/moodleoverflow/post.php', ['moodleoverflow' => $moodleoverflow->id]);
$button = new single_button($buttonurl, $buttontext, 'get');
$button->class = 'singlebutton align-middle m-2';
$button->formid = 'newdiscussionform';
echo $OUTPUT->render($button);
}
// Print a button if the user is capable of seeing the user stats.
if ($canseeuserstats && get_config('moodleoverflow', 'showuserstats')) {
$userstatsbuttontext = get_string('seeuserstats', 'moodleoverflow');
$userstatsbuttonurl = new moodle_url('/mod/moodleoverflow/userstats.php', ['id' => $cm->id,
'courseid' => $moodleoverflow->course,
'mid' => $moodleoverflow->id, ]);
$userstatsbutton = new single_button($userstatsbuttonurl, $userstatsbuttontext, 'get');
$userstatsbutton->class = 'singlebutton align-middle m-2';
echo $OUTPUT->render($userstatsbutton);
}
// Get all the recent discussions the user is allowed to see.
$discussions = moodleoverflow_get_discussions($cm, $page, $perpage);
// Get the number of replies for each discussion.
$replies = moodleoverflow_count_discussion_replies($cm);
// Check whether the moodleoverflow instance can be tracked and is tracked.
if ($cantrack = readtracking::moodleoverflow_can_track_moodleoverflows($moodleoverflow)) {
$istracked = readtracking::moodleoverflow_is_tracked($moodleoverflow);
} else {
$istracked = false;
}
// Get an array of unread messages for the current user if the moodleoverflow instance is tracked.
if ($istracked) {
$unreads = moodleoverflow_get_discussions_unread($cm);
$markallread = $CFG->wwwroot . '/mod/moodleoverflow/markposts.php?m=' . $moodleoverflow->id;
} else {
$unreads = [];
$markallread = null;
}
if ($markallread && $unreads) {
echo html_writer::link(new moodle_url($markallread),
get_string('markallread_forum', 'mod_moodleoverflow'),
['class' => 'btn btn-secondary my-2']
);
}
// Get all the recent discussions the user is allowed to see.
$discussions = moodleoverflow_get_discussions($cm, $page, $perpage);
// If we want paging.
if ($page != -1) {
// Get the number of discussions.
$numberofdiscussions = moodleoverflow_get_discussions_count($cm);
// Show the paging bar.
echo $OUTPUT->paging_bar($numberofdiscussions, $page, $perpage, "view.php?id=$cm->id");
}
// Get the number of replies for each discussion.
$replies = moodleoverflow_count_discussion_replies($cm);
// Check whether the user can subscribe to the discussion.
$cansubtodiscussion = false;
if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/moodleoverflow:viewdiscussion', $context)
&& \mod_moodleoverflow\subscriptions::is_subscribable($moodleoverflow, $context)) {
$cansubtodiscussion = true;
}
// Check wether the user can move a topic.
$canmovetopic = false;
if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/moodleoverflow:movetopic', $context)) {
$canmovetopic = true;
}
// Iterate through every visible discussion.
$i = 0;
$preparedarray = [];
foreach ($discussions as $discussion) {
$preparedarray[$i] = [];
// Handle anonymized discussions.
if ($discussion->userid == 0) {
$discussion->name = get_string('privacy:anonym_discussion_name', 'mod_moodleoverflow');
}
// Set the amount of replies for every discussion.
if (!empty($replies[$discussion->discussion])) {
$discussion->replies = $replies[$discussion->discussion]->replies;
$discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
} else {
$discussion->replies = 0;
}
// Set the right text.
$preparedarray[$i]['answertext'] = ($discussion->replies == 1) ? 'answer' : 'answers';
// Set the amount of unread messages for each discussion.
if (!$istracked) {
$discussion->unread = '-';
} else if (empty($USER)) {
$discussion->unread = 0;
} else {
if (empty($unreads[$discussion->discussion])) {
$discussion->unread = 0;
} else {
$discussion->unread = $unreads[$discussion->discussion];
}
}
// Check if the question owner marked the question as helpful.
$markedhelpful = \mod_moodleoverflow\ratings::moodleoverflow_discussion_is_solved($discussion->discussion, false);
$preparedarray[$i]['starterlink'] = null;
if ($markedhelpful) {
$link = '/mod/moodleoverflow/discussion.php?d=';
$markedhelpful = $markedhelpful[array_key_first($markedhelpful)];
$preparedarray[$i]['starterlink'] = new moodle_url($link .
$markedhelpful->discussionid . '#p' . $markedhelpful->postid);
}
// Check if a teacher marked a post as solved.
$markedsolution = \mod_moodleoverflow\ratings::moodleoverflow_discussion_is_solved($discussion->discussion, true);
$preparedarray[$i]['teacherlink'] = null;
if ($markedsolution) {
$link = '/mod/moodleoverflow/discussion.php?d=';
$markedsolution = $markedsolution[array_key_first($markedsolution)];
$preparedarray[$i]['teacherlink'] = new moodle_url($link .
$markedsolution->discussionid . '#p' . $markedsolution->postid);
}
// Check if a single post was marked by the question owner and a teacher.
$statusboth = false;
if ($markedhelpful && $markedsolution) {
if ($markedhelpful->postid == $markedsolution->postid) {
$statusboth = true;
}
}
// Get the amount of votes for the discussion.
$votes = \mod_moodleoverflow\ratings::moodleoverflow_get_ratings_by_discussion($discussion->discussion, $discussion->id);
$votes = $votes->upvotes - $votes->downvotes;
$preparedarray[$i]['votetext'] = ($votes == 1) ? 'vote' : 'votes';
// Use the discussions name instead of the subject of the first post.
$discussion->subject = $discussion->name;
// Format the subjectname and the link to the topic.
$preparedarray[$i]['subjecttext'] = format_string($discussion->subject);
$preparedarray[$i]['subjectlink'] = $CFG->wwwroot . '/mod/moodleoverflow/discussion.php?d=' . $discussion->discussion;
// Get information about the user who started the discussion.
$startuser = new stdClass();
if ($CFG->branch >= 311) {
$startuserfields = \core_user\fields::get_picture_fields();
} else {
$startuserfields = explode(',', user_picture::fields());
}
$startuser = username_load_fields_from_object($startuser, $discussion, null, $startuserfields);
$startuser->id = $discussion->userid;
// Discussion was anonymized.
if ($startuser->id == 0 || $moodleoverflow->anonymous != anonymous::NOT_ANONYMOUS) {
// Get his picture, his name and the link to his profile.
if ($startuser->id == $USER->id) {
$preparedarray[$i]['username'] = get_string('anonym_you', 'mod_moodleoverflow');
// Needs to be included for reputation to update properly.
$preparedarray[$i]['userlink'] = $CFG->wwwroot . '/user/view.php?id=' .
$discussion->userid . '&course=' . $moodleoverflow->course;
} else {
$preparedarray[$i]['username'] = get_string('privacy:anonym_user_name', 'mod_moodleoverflow');
$preparedarray[$i]['userlink'] = null;
}
} else {
// Get his picture, his name and the link to his profile.
$preparedarray[$i]['picture'] = $OUTPUT->user_picture($startuser, ['courseid' => $moodleoverflow->course,
'link' => false, ]);
$preparedarray[$i]['username'] = fullname($startuser, has_capability('moodle/site:viewfullnames', $context));
$preparedarray[$i]['userlink'] = $CFG->wwwroot . '/user/view.php?id=' .
$discussion->userid . '&course=' . $moodleoverflow->course;
}
// Get the amount of replies and the link to the discussion.
$preparedarray[$i]['replyamount'] = $discussion->replies;
$preparedarray[$i]['questionunderreview'] = $discussion->reviewed == 0;
// Are there unread messages? Create a link to them.
$preparedarray[$i]['unreadamount'] = $discussion->unread;
$preparedarray[$i]['unread'] = ($preparedarray[$i]['unreadamount'] > 0) ? true : false;
$preparedarray[$i]['unreadlink'] = $CFG->wwwroot .
'/mod/moodleoverflow/discussion.php?d=' . $discussion->discussion . '#unread';
$link = '/mod/moodleoverflow/markposts.php?m=';
$preparedarray[$i]['markreadlink'] = $CFG->wwwroot . $link . $moodleoverflow->id . '&d=' . $discussion->discussion;
// Check the date of the latest post. Just in case the database is not consistent.
$usedate = (empty($discussion->timemodified)) ? $discussion->modified : $discussion->timemodified;
// Get the name and the link to the profile of the user, that is related to the latest post.
$usermodified = new stdClass();
$usermodified->id = $discussion->usermodified;
if ($usermodified->id == 0 || $moodleoverflow->anonymous) {
if ($usermodified->id == $USER->id) {
$preparedarray[$i]['lastpostusername'] = null;
$preparedarray[$i]['lastpostuserlink'] = null;
} else {
$preparedarray[$i]['lastpostusername'] = null;
$preparedarray[$i]['lastpostuserlink'] = null;
}
} else {
$usermodified = username_load_fields_from_object($usermodified, $discussion, 'um');
$preparedarray[$i]['lastpostusername'] = fullname($usermodified);
$preparedarray[$i]['lastpostuserlink'] = $CFG->wwwroot . '/user/view.php?id=' .
$discussion->usermodified . '&course=' . $moodleoverflow->course;
}
// Get the date of the latest post of the discussion.
$parenturl = (empty($discussion->lastpostid)) ? '' : '&parent=' . $discussion->lastpostid;
$preparedarray[$i]['lastpostdate'] = userdate($usedate, get_string('strftimerecentfull'));
$preparedarray[$i]['lastpostlink'] = $preparedarray[$i]['subjectlink'] . $parenturl;
// Check whether the discussion is subscribed.
$preparedarray[$i]['discussionsubicon'] = false;
if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/moodleoverflow:viewdiscussion', $context)) {
// Discussion subscription.
if (\mod_moodleoverflow\subscriptions::is_subscribable($moodleoverflow, $context)) {
$preparedarray[$i]['discussionsubicon'] = \mod_moodleoverflow\subscriptions::get_discussion_subscription_icon(
$moodleoverflow, $context, $discussion->discussion);
}
}
if ($canreviewposts) {
$reviewinfo = review::get_short_review_info_for_discussion($discussion->discussion);
$preparedarray[$i]['needreview'] = $reviewinfo->count;
$preparedarray[$i]['reviewlink'] = (new moodle_url('/mod/moodleoverflow/discussion.php', [
'd' => $discussion->discussion,
], 'p' . $reviewinfo->first))->out(false);
}
// Build linktopopup to move a topic.
$linktopopup = $CFG->wwwroot . '/mod/moodleoverflow/view.php?id=' . $cm->id . '&movetopopup=' . $discussion->discussion;
$preparedarray[$i]['linktopopup'] = $linktopopup;
// Add all created data to an array.
$preparedarray[$i]['markedhelpful'] = $markedhelpful;
$preparedarray[$i]['markedsolution'] = $markedsolution;
$preparedarray[$i]['statusboth'] = $statusboth;
$preparedarray[$i]['votes'] = $votes;
// Did the user rated this post?
$rating = \mod_moodleoverflow\ratings::moodleoverflow_user_rated($discussion->firstpost);
$firstpost = moodleoverflow_get_post_full($discussion->firstpost);
$preparedarray[$i]['userupvoted'] = ($rating->rating ?? null) == RATING_UPVOTE;
$preparedarray[$i]['userdownvoted'] = ($rating->rating ?? null) == RATING_DOWNVOTE;
$preparedarray[$i]['canchange'] = \mod_moodleoverflow\ratings::moodleoverflow_user_can_rate($firstpost, $context) &&
$startuser->id != $USER->id;
$preparedarray[$i]['postid'] = $discussion->firstpost;
// Go to the next discussion.
$i++;
}
// Include the renderer.
$renderer = $PAGE->get_renderer('mod_moodleoverflow');
// Collect the needed data being submitted to the template.
$mustachedata = new stdClass();
$mustachedata->cantrack = $cantrack;
$mustachedata->canviewdiscussions = $canviewdiscussions;
$mustachedata->canreview = $canreviewposts;
$mustachedata->discussions = $preparedarray;
$mustachedata->hasdiscussions = (count($discussions) >= 0) ? true : false;
$mustachedata->istracked = $istracked;
$mustachedata->markallread = $markallread;
$mustachedata->cansubtodiscussion = $cansubtodiscussion;
$mustachedata->canmovetopic = $canmovetopic;
$mustachedata->cannormoveorsub = ((!$canmovetopic) && (!$cansubtodiscussion));
// Print the template.
echo $renderer->render_discussion_list($mustachedata);
// Show the paging bar if paging is activated.
if ($page != -1) {
echo $OUTPUT->paging_bar($numberofdiscussions, $page, $perpage, "view.php?id=$cm->id");
}
}
/**
* Prints a popup with a menu of other moodleoverflow in the course.
* Menu to move a topic to another moodleoverflow forum.
*
* @param object $course
* @param object $cm
* @param int $movetopopup forum where forum list is being printed.
*/
function moodleoverflow_print_forum_list($course, $cm, $movetopopup) {
global $CFG, $DB, $PAGE;
$forumarray = [[]];
$currentforum = $DB->get_record('moodleoverflow_discussions', ['id' => $movetopopup], 'moodleoverflow');
$currentdiscussion = $DB->get_record('moodleoverflow_discussions', ['id' => $movetopopup], 'name');
// If the currentforum is anonymous, only show forums that have a higher anonymous setting.
$anonymoussetting = $DB->get_field('moodleoverflow', 'anonymous', ['id' => $currentforum->moodleoverflow]);
if ($anonymoussetting == anonymous::QUESTION_ANONYMOUS || $anonymoussetting == anonymous::EVERYTHING_ANONYMOUS) {
$params = ['course' => $course->id, 'anonymous' => $anonymoussetting,
'currentforumid' => $currentforum->moodleoverflow, ];
$sql = "SELECT *
FROM {moodleoverflow}
WHERE course = :course
AND anonymous >= :anonymous
AND id != :currentforumid";
$forums = $DB->get_records_sql($sql, $params);
} else {
$forums = $DB->get_records('moodleoverflow', ['course' => $course->id]);
}
$amountforums = count($forums);
if ($amountforums >= 1) {
// Write the moodleoverflow-names in an array.
$i = 0;
foreach ($forums as $forum) {
if ($forum->id == $currentforum->moodleoverflow) {
continue;
} else {
$forumarray[$i]['name'] = $forum->name;
$movetoforum = $CFG->wwwroot . '/mod/moodleoverflow/view.php?id=' . $cm->id . '&movetopopup='
. $movetopopup . '&movetoforum=' . $forum->id;
$forumarray[$i]['movetoforum'] = $movetoforum;
}
$i++;
}
$amountforums = true;
} else {
$amountforums = false;
}
// Build popup.
$renderer = $PAGE->get_renderer('mod_moodleoverflow');
$mustachedata = new stdClass();
$mustachedata->hasforums = $amountforums;
$mustachedata->forums = $forumarray;
$mustachedata->currentdiscussion = $currentdiscussion->name;
echo $renderer->render_forum_list($mustachedata);
}
/**
* Returns an array of counts of replies for each discussion.
*
* @param object $cm coursemodule
*
* @return array
*/
function moodleoverflow_count_discussion_replies($cm) {
global $DB, $USER;
$modcontext = context_module::instance($cm->id);
$params = [$cm->instance];
$whereconditions = ['d.moodleoverflow = ?', 'p.parent > 0'];
if (!has_capability('mod/moodleoverflow:reviewpost', $modcontext)) {
$whereconditions[] = '(p.reviewed = 1 OR p.userid = ?)';
$params[] = $USER->id;
}
$wheresql = join(' AND ', $whereconditions);
$sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
FROM {moodleoverflow_posts} p
JOIN {moodleoverflow_discussions} d ON p.discussion = d.id
WHERE $wheresql
GROUP BY p.discussion";
return $DB->get_records_sql($sql, $params);
}
/**
* Check if the user is capable of starting a new discussion.
*
* @param object $moodleoverflow
* @param object $cm
* @param object $context
*
* @return bool
*/
function moodleoverflow_user_can_post_discussion($moodleoverflow, $cm = null, $context = null) {
// Guests an not-logged-in users can not psot.
if (isguestuser() || !isloggedin()) {
return false;
}
// Get the coursemodule.
if (!$cm) {
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
throw new moodle_exception('invalidcoursemodule');
}
}
// Get the context if not set in the parameters.
if (!$context) {
$context = context_module::instance($cm->id);
}
// Check the capability.
if (has_capability('mod/moodleoverflow:startdiscussion', $context)) {
return true;
} else {
return false;
}
}
/**
* Returns the amount of discussions of the given context module.
*
* @param object $cm
*
* @return array
*/
function moodleoverflow_get_discussions_count($cm) {
global $DB, $USER;
$modcontext = context_module::instance($cm->id);
$params = [$cm->instance];
$whereconditions = ['d.moodleoverflow = ?', 'p.parent = 0'];
if (!has_capability('mod/moodleoverflow:reviewpost', $modcontext)) {
$whereconditions[] = '(p.reviewed = 1 OR p.userid = ?)';
$params[] = $USER->id;
}
$wheresql = join(' AND ', $whereconditions);
$sql = 'SELECT COUNT(d.id)
FROM {moodleoverflow_discussions} d
JOIN {moodleoverflow_posts} p ON p.discussion = d.id
WHERE ' . $wheresql;
return $DB->get_field_sql($sql, $params);
}
/**
* Returns an array of unread messages for the current user.
*
* @param object $cm
*
* @return array
*/
function moodleoverflow_get_discussions_unread($cm) {
global $DB, $USER;
// Get the current timestamp and the oldpost-timestamp.
$now = round(time(), -2);
$cutoffdate = $now - (get_config('moodleoverflow', 'oldpostdays') * 24 * 60 * 60);
$modcontext = context_module::instance($cm->id);
$whereconditions = ['d.moodleoverflow = :instance', 'p.modified >= :cutoffdate', 'r.id is NULL'];
$params = [
'userid' => $USER->id,
'instance' => $cm->instance,
'cutoffdate' => $cutoffdate,
];
if (!has_capability('mod/moodleoverflow:reviewpost', $modcontext)) {
$whereconditions[] = '(p.reviewed = 1 OR p.userid = :userid2)';
$params['userid2'] = $USER->id;
}
$wheresql = join(' AND ', $whereconditions);
// Define the sql-query.
$sql = "SELECT d.id, COUNT(p.id) AS unread
FROM {moodleoverflow_discussions} d
JOIN {moodleoverflow_posts} p ON p.discussion = d.id
LEFT JOIN {moodleoverflow_read} r ON (r.postid = p.id AND r.userid = :userid)
WHERE $wheresql
GROUP BY d.id";
// Return the unread messages as an array.
if ($unreads = $DB->get_records_sql($sql, $params)) {
$returnarray = [];
foreach ($unreads as $unread) {
$returnarray[$unread->id] = $unread->unread;
}
return $returnarray;
} else {
// If there are no unread messages, return an empty array.
return [];
}
}
/**
* Gets a post with all info ready for moodleoverflow_print_post.
* Most of these joins are just to get the forum id.
*
* @param int $postid
*
* @return mixed array of posts or false
*/
function moodleoverflow_get_post_full($postid) {
global $DB, $CFG;
if ($CFG->branch >= 311) {
$allnames = \core_user\fields::for_name()->get_sql('u', false, '', '', false)->selects;
} else {
$allnames = get_all_user_name_fields(true, 'u');
}
$sql = "SELECT p.*, d.moodleoverflow, $allnames, u.email, u.picture, u.imagealt
FROM {moodleoverflow_posts} p
JOIN {moodleoverflow_discussions} d ON p.discussion = d.id
LEFT JOIN {user} u ON p.userid = u.id
WHERE p.id = :postid";
$params = [];
$params['postid'] = $postid;
$post = $DB->get_record_sql($sql, $params);
if ($post->userid === 0) {
$post->message = get_string('privacy:anonym_post_message', 'mod_moodleoverflow');
}
return $post;
}
/**
* Checks if a user can see a specific post.
*
* @param object $moodleoverflow
* @param object $discussion
* @param object $post
* @param object $cm
*
* @return bool
*/
function moodleoverflow_user_can_see_post($moodleoverflow, $discussion, $post, $cm) {
global $USER, $DB;
// Retrieve the modulecontext.
$modulecontext = context_module::instance($cm->id);
// Fetch the moodleoverflow instance object.
if (is_numeric($moodleoverflow)) {
debugging('missing full moodleoverflow', DEBUG_DEVELOPER);
if (!$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $moodleoverflow])) {
return false;
}
}
// Fetch the discussion object.
if (is_numeric($discussion)) {
debugging('missing full discussion', DEBUG_DEVELOPER);
if (!$discussion = $DB->get_record('moodleoverflow_discussions', ['id' => $discussion])) {
return false;
}
}
// Fetch the post object.
if (is_numeric($post)) {
debugging('missing full post', DEBUG_DEVELOPER);
if (!$post = $DB->get_record('moodleoverflow_posts', ['id' => $post])) {
return false;
}
}
// Get the postid if not set.
if (!isset($post->id) && isset($post->parent)) {
$post->id = $post->parent;
}
// Find the coursemodule.
if (!$cm) {
debugging('missing cm', DEBUG_DEVELOPER);
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
throw new moodle_exception('invalidcoursemodule');
}
}
// Check if the user can view the discussion.
if (!capabilities::has(capabilities::VIEW_DISCUSSION, $modulecontext)) {
return false;
}
if (!($post->reviewed == 1 || $post->userid == $USER->id ||
capabilities::has(capabilities::REVIEW_POST, $modulecontext))) {
return false;
}
// The user has the capability to see the discussion.
return \core_availability\info_module::is_user_visible($cm, $USER->id, false);
}
/**
* Check if a user can see a specific discussion.
*
* @param object $moodleoverflow
* @param object $discussion
* @param context $context
*
* @return bool
*/
function moodleoverflow_user_can_see_discussion($moodleoverflow, $discussion, $context) {
global $DB;
// Retrieve the moodleoverflow object.
if (is_numeric($moodleoverflow)) {
debugging('missing full moodleoverflow', DEBUG_DEVELOPER);
if (!$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $moodleoverflow])) {
return false;
}
}
// Retrieve the discussion object.
if (is_numeric($discussion)) {
debugging('missing full discussion', DEBUG_DEVELOPER);
if (!$discussion = $DB->get_record('moodleoverflow_discussions', ['id' => $discussion])) {
return false;
}
}
// Retrieve the coursemodule.
if (!get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
throw new moodle_exception('invalidcoursemodule');
}
return capabilities::has(capabilities::VIEW_DISCUSSION, $context);
}
/**
* Creates a new moodleoverflow discussion.
*
* @param stdClass $discussion The discussion object
* @param context_module $modulecontext
* @param int $userid The user ID
*
* @return bool|int The id of the created discussion
*/
function moodleoverflow_add_discussion($discussion, $modulecontext, $userid = null) {
global $DB, $USER;
// Get the current time.
$timenow = time();
// Get the current user.
if (is_null($userid)) {
$userid = $USER->id;
}
// The first post of the discussion is stored
// as a real post. The discussion links to it.
// Retrieve the module instance.
if (!$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $discussion->moodleoverflow])) {
return false;
}
// Retrieve the coursemodule.
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
throw new moodle_exception('invalidcoursemodule');
}
$context = context_module::instance($cm->id);
// Create the post-object.
$post = new stdClass();
$post->discussion = 0;
$post->parent = 0;
$post->userid = $userid;
$post->created = $timenow;
$post->modified = $timenow;
$post->message = $discussion->message;
$post->attachments = $discussion->attachments;
$post->moodleoverflow = $moodleoverflow->id;
$post->course = $moodleoverflow->course;
// Set to not reviewed, if questions should be reviewed, and user is not a reviewer themselves.
if (review::get_review_level($moodleoverflow) >= review::QUESTIONS &&
!capabilities::has(capabilities::REVIEW_POST, $modulecontext, $userid)) {
$post->reviewed = 0;
}
// Submit the post to the database and get its id.
$post->id = $DB->insert_record('moodleoverflow_posts', $post);
// Save draft files to permanent file area.
$post->message = file_save_draft_area_files($discussion->draftideditor, $context->id, 'mod_moodleoverflow', 'post',
$post->id, mod_forum_post_form::editor_options($context, null), $post->message);
$DB->set_field('moodleoverflow_posts', 'message', $post->message, ['id' => $post->id]);
// Create the discussion object.
$discussionobject = new stdClass();
$discussionobject->course = $discussion->course;
$discussionobject->moodleoverflow = $discussion->moodleoverflow;
$discussionobject->name = $discussion->name;
$discussionobject->firstpost = $post->id;
$discussionobject->userid = $post->userid;
$discussionobject->timemodified = $timenow;
$discussionobject->timestart = $timenow;
$discussionobject->usermodified = $post->userid;
// Submit the discussion to the database and get its id.
$post->discussion = $DB->insert_record('moodleoverflow_discussions', $discussionobject);
// Link the post to the discussion.
$DB->set_field('moodleoverflow_posts', 'discussion', $post->discussion, ['id' => $post->id]);
moodleoverflow_add_attachment($post, $moodleoverflow, $cm);
// Mark the created post as read.
$cantrack = readtracking::moodleoverflow_can_track_moodleoverflows($moodleoverflow);
$istracked = readtracking::moodleoverflow_is_tracked($moodleoverflow);
if ($cantrack && $istracked) {
readtracking::moodleoverflow_mark_post_read($post->userid, $post);
}
// Trigger event.
$params = [
'context' => $modulecontext,
'objectid' => $post->discussion,
];
$event = \mod_moodleoverflow\event\discussion_viewed::create($params);
$event->trigger();
// Return the id of the discussion.
return $post->discussion;
}
/**
* Modifies the session to return back to where the user is coming from.
*
* @param object $default
*
* @return mixed
*/
function moodleoverflow_go_back_to($default) {
global $SESSION;
if (!empty($SESSION->fromdiscussion)) {
$returnto = $SESSION->fromdiscussion;
unset($SESSION->fromdiscussion);
return $returnto;
} else {
return $default;
}
}
/**
* Checks whether the user can reply to posts in a discussion.
*
* @param object $modulecontext
* @param object $posttoreplyto
* @param bool $considerreviewstatus
* @param int $userid
* @return bool Whether the user can reply
* @throws coding_exception
*/
function moodleoverflow_user_can_post($modulecontext, $posttoreplyto, $considerreviewstatus = true, $userid = null) {
global $USER;
// If not user is submitted, use the current one.
if (empty($userid)) {
$userid = $USER->id;
}
// Check the users capability.
if (!has_capability('mod/moodleoverflow:replypost', $modulecontext, $userid)) {
return false;
}
return !$considerreviewstatus || $posttoreplyto->reviewed == 1;
}
/**
* Prints a moodleoverflow discussion.
*
* @param stdClass $course The course object
* @param object $cm
* @param stdClass $moodleoverflow The moodleoverflow object
* @param stdClass $discussion The discussion object
* @param stdClass $post The post object
* @param bool $multiplemarks The setting of multiplemarks (default: multiplemarks are not allowed)
*/
function moodleoverflow_print_discussion($course, $cm, $moodleoverflow, $discussion, $post, $multiplemarks = false) {
global $USER;
// Check if the current is the starter of the discussion.
$ownpost = (isloggedin() && ($USER->id == $post->userid));
// Fetch the modulecontext.
$modulecontext = context_module::instance($cm->id);
// Is the forum tracked?
$istracked = readtracking::moodleoverflow_is_tracked($moodleoverflow);
// Retrieve all posts of the discussion.
$posts = moodleoverflow_get_all_discussion_posts($discussion->id, $istracked, $modulecontext);
$usermapping = anonymous::get_userid_mapping($moodleoverflow, $discussion->id);
// Start with the parent post.
$post = $posts[$post->id];
$answercount = 0;
// Lets clear all posts above level 2.
// Check if there are answers.
if (isset($post->children)) {
// Itereate through all answers.
foreach ($post->children as $aid => $a) {
$answercount += 1;
// Check for each answer if they have children as well.
if (isset($post->children[$aid]->children)) {
// Iterate through all comments.
foreach ($post->children[$aid]->children as $cid => $c) {
// Delete the children of the comments.
if (isset($post->children[$aid]->children[$cid]->children)) {
unset($post->children[$aid]->children[$cid]->children);
}
}
}
}
}
// Format the subject.
$post->moodleoverflow = $moodleoverflow->id;
$post->subject = format_string($post->subject);
// Check if the post was read.
$postread = !empty($post->postread);
// Print the starting post.
echo moodleoverflow_print_post($post, $discussion, $moodleoverflow, $cm, $course,
$ownpost, false, '', '', $postread, true, $istracked, 0, $usermapping, 0, $multiplemarks);
// Print answer divider.
if ($answercount == 1) {
$answerstring = get_string('answer', 'moodleoverflow', $answercount);
} else {
$answerstring = get_string('answers', 'moodleoverflow', $answercount);
}
echo "<br><h2>$answerstring</h2>";
echo '<div id="moodleoverflow-posts">';
// Print the other posts.