forked from learnweb/moodle-mod_moodleoverflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
1829 lines (1520 loc) · 64.4 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
*/
defined('MOODLE_INTERNAL') || die();
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;
$params = array($cm->instance);
// User must have the permission to view the discussions.
$modcontext = context_module::instance($cm->id);
if (!has_capability('mod/moodleoverflow:viewdiscussion', $modcontext)) {
return array();
}
// 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.
$allnames = get_all_user_name_fields(true, 'u');
$postdata = 'p.id, p.modified, p.discussion, p.userid';
$discussiondata = 'd.name, d.timemodified, d.timestart, d.usermodified';
$userdata = 'u.email, u.picture, u.imagealt';
$usermodifiedfields = get_all_user_name_fields(true, 'um', null, 'um') .
', um.email AS umemail, um.picture AS umpicture, um.imagealt AS umimagealt';
$usermodifiedtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
// 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
$usermodifiedtable
WHERE d.moodleoverflow = ? AND p.parent = 0
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)) {
print_error('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);
// 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 moodleoverflowaddnew';
$button->formid = 'newdiscussionform';
echo $OUTPUT->render($button);
}
// 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($moodleoverflow->id);
// Check whether the moodleoverflow instance can be tracked and is tracked.
if ($cantrack = \mod_moodleoverflow\readtracking::moodleoverflow_can_track_moodleoverflows($moodleoverflow)) {
$istracked = \mod_moodleoverflow\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 = array();
$markallread = null;
}
// Check whether the user can subscribe to the discussion.
$cansubtodiscussion = false;
if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/moodleoverflow:viewdiscussion', $context)) {
$cansubtodiscussion = true;
}
// Iterate through every visible discussion.
$i = 0;
$rowcount = 0;
$preparedarray = array();
foreach ($discussions as $discussion) {
$preparedarray[$i] = array();
// 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.
$statusstarter = \mod_moodleoverflow\ratings::moodleoverflow_discussion_is_solved($discussion->discussion, false);
$preparedarray[$i]['starterlink'] = null;
if ($statusstarter) {
$link = '/mod/moodleoverflow/discussion.php?d=';
$preparedarray[$i]['starterlink'] = new moodle_url($link .
$statusstarter->discussionid . '#p' . $statusstarter->postid);
}
// Check if a teacher marked a post as solved.
$statusteacher = \mod_moodleoverflow\ratings::moodleoverflow_discussion_is_solved($discussion->discussion, true);
$preparedarray[$i]['teacherlink'] = null;
if ($statusteacher) {
$link = '/mod/moodleoverflow/discussion.php?d=';
$preparedarray[$i]['teacherlink'] = new moodle_url($link .
$statusteacher->discussionid . '#p' . $statusteacher->postid);
}
// Check if a single post was marked by the question owner and a teacher.
$statusboth = false;
if ($statusstarter AND $statusteacher) {
if ($statusstarter->postid == $statusteacher->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;
// Increase the rowcount.
$rowcount = ($rowcount + 1) % 2;
// 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();
$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) {
// Get his picture, his name and the link to his profile.
$preparedarray[$i]['username'] = get_string('privacy:anonym_user_name', 'mod_moodleoverflow');
$preparedarray[$i]['userlink'] = '#';
} else {
// Get his picture, his name and the link to his profile.
$preparedarray[$i]['picture'] = $OUTPUT->user_picture($startuser, array('courseid' => $moodleoverflow->course));
$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;
// 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 ($startuser->id == 0) {
$preparedarray[$i]['lastpostusername'] = get_string('privacy:anonym_user_name', 'mod_moodleoverflow');
$preparedarray[$i]['lastpostuserlink'] = '#';
} 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)) {
$preparedarray[$i]['discussionsubicon'] = \mod_moodleoverflow\subscriptions::get_discussion_subscription_icon(
$moodleoverflow, $discussion->discussion);
}
}
// Add all created data to an array.
$preparedarray[$i]['rowcount'] = $rowcount;
$preparedarray[$i]['statusstarter'] = $statusstarter;
$preparedarray[$i]['statusteacher'] = $statusteacher;
$preparedarray[$i]['statusboth'] = $statusboth;
$preparedarray[$i]['votes'] = $votes;
// 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->discussions = $preparedarray;
$mustachedata->hasdiscussions = (count($discussions) >= 0) ? true : false;
$mustachedata->istracked = $istracked;
$mustachedata->markallread = $markallread;
$mustachedata->cansubtodiscussion = $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");
}
}
/**
* Returns an array of counts of replies for each discussion.
*
* @param int $moodleoverflowid
*
* @return array
*/
function moodleoverflow_count_discussion_replies($moodleoverflowid) {
global $DB;
$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 p.parent > 0 AND d.moodleoverflow = ?
GROUP BY p.discussion";
return $DB->get_records_sql($sql, array($moodleoverflowid));
}
/**
* 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() or !isloggedin()) {
return false;
}
// Get the coursemodule.
if (!$cm) {
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
print_error('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;
$params = array($cm->instance);
$sql = 'SELECT COUNT(d.id)
FROM {moodleoverflow_discussions} d
JOIN {moodleoverflow_posts} p ON p.discussion = d.id
WHERE d.moodleoverflow = ? AND p.parent = 0';
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.
$params = array();
$now = round(time(), -2);
$cutoffdate = $now - (get_config('moodleoverflow', 'oldpostdays') * 24 * 60 * 60);
// 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 d.moodleoverflow = :instance
AND p.modified >= :cutoffdate AND r.id is NULL
GROUP BY d.id";
$params['userid'] = $USER->id;
$params['instance'] = $cm->instance;
$params['cutoffdate'] = $cutoffdate;
// Return the unread messages as an array.
if ($unreads = $DB->get_records_sql($sql, $params)) {
foreach ($unreads as $unread) {
$unreads[$unread->id] = $unread->unread;
}
return $unreads;
} else {
// If there are no unread messages, return an empty array.
return array();
}
}
/**
* 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;
$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 = array();
$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 null $user
* @param object $cm
*
* @return bool
*/
function moodleoverflow_user_can_see_post($moodleoverflow, $discussion, $post, $user = null, $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', array('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', array('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', array('id' => $post))) {
return false;
}
}
// Get the postid if not set.
if (!isset($post->id) AND 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)) {
print_error('invalidcoursemodule');
}
}
// Make sure a user is set.
if (empty($user) || empty($user->id)) {
$user = $USER;
}
// Check if the user can view the discussion.
$canviewdiscussion = !empty($cm->cache->caps['mod/moodleoverflow:viewdiscussion']) ||
has_capability('mod/moodleoverflow:viewdiscussion', $modulecontext, $user->id);
if (!$canviewdiscussion &&
!has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'),
context_user::instance($post->userid))
) {
return false;
}
// Check the coursemodule settings.
if (isset($cm->uservisible)) {
if (!$cm->uservisible) {
return false;
}
} else {
if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
return false;
}
}
// The user has the capability to see the discussion.
return true;
}
/**
* Check if a user can see a specific discussion.
*
* @param object $moodleoverflow
* @param object $discussion
* @param object $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', array('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', array('id' => $discussion))) {
return false;
}
}
// Retrieve the coursemodule.
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
print_error('invalidcoursemodule');
}
// Check the users capability.
if (!has_capability('mod/moodleoverflow:viewdiscussion', $context)) {
return false;
}
// Allow the user to see the discussion.
return true;
}
/**
* Creates a new moodleoverflow discussion.
*
* @param stdClass $discussion The discussion object
* @param object $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', array('id' => $discussion->moodleoverflow))) {
return false;
}
// Retrieve the coursemodule.
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
print_error('invalidcoursemodule');
}
// 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;
// Submit the post to the database and get its id.
$post->id = $DB->insert_record('moodleoverflow_posts', $post);
// 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, array('id' => $post->id));
moodleoverflow_add_attachment($post, $moodleoverflow, $cm);
// Mark the created post as read.
$cantrack = \mod_moodleoverflow\readtracking::moodleoverflow_can_track_moodleoverflows($moodleoverflow);
$istracked = \mod_moodleoverflow\readtracking::moodleoverflow_is_tracked($moodleoverflow);
if ($cantrack AND $istracked) {
\mod_moodleoverflow\readtracking::moodleoverflow_mark_post_read($post->userid, $post);
}
// Trigger event.
$params = array(
'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 stdClass $moodleoverflow The moodleoverflow object
* @param stdClass $user The user object
* @param object $cm
* @param stdClass $course The course object
* @param context_module $modulecontext The modules context
*
* @return bool Whether the user can reply
*/
function moodleoverflow_user_can_post($moodleoverflow, $user = null, $cm = null, $course = null, $modulecontext = null) {
global $USER, $DB;
// If not user is submitted, use the current one.
if (empty($user)) {
$user = $USER;
}
// Guests can not post.
if (isguestuser($user) OR empty($user->id)) {
return false;
}
// Fetch the coursemodule.
if (!$cm) {
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id, $moodleoverflow->course)) {
print_error('invalidcoursemodule');
}
}
// Fetch the related course.
if (!$course) {
if (!$course = $DB->get_record('course', array('id' => $moodleoverflow->course))) {
print_error('invalidcourseid');
}
}
// Fetch the related modulecontext.
if (!$modulecontext) {
$modulecontext = context_module::instance($cm->id);
}
// Users with temporary guest access can not post.
if (!is_viewing($modulecontext, $user->id) AND !is_enrolled($modulecontext, $user->id, '', true)) {
return false;
}
// Check the users capability.
if (has_capability('mod/moodleoverflow:replypost', $modulecontext, $user->id)) {
return true;
}
// The user does not have the capability.
return false;
}
/**
* 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 boolean $canreply Whether the user can reply in this discussion
*/
function moodleoverflow_print_discussion($course, $cm, $moodleoverflow, $discussion, $post, $canreply) {
global $USER, $OUTPUT;
// Check if the current is the starter of the discussion.
$ownpost = (isloggedin() AND ($USER->id == $post->userid));
// Fetch the modulecontext.
$modulecontext = context_module::instance($cm->id);
// Is the forum tracked?
$istracked = \mod_moodleoverflow\readtracking::moodleoverflow_is_tracked($moodleoverflow);
// Retrieve all posts of the discussion.
$posts = moodleoverflow_get_all_discussion_posts($discussion->id, $istracked);
// Start with the parent post.
$post = $posts[$post->id];
// 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) {
// 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 a button to reply to the discussion.
if ($canreply) {
$buttontext = get_string('addanewreply', 'moodleoverflow');
$buttonurl = new moodle_url('/mod/moodleoverflow/post.php', ['reply' => $post->id]);
$button = new single_button($buttonurl, $buttontext, 'get');
$button->class = 'singlebutton moodleoverflowaddnew';
$button->formid = 'newdiscussionform';
echo $OUTPUT->render($button);
}
// Print the starting post.
echo moodleoverflow_print_post($post, $discussion, $moodleoverflow, $cm, $course,
$ownpost, $canreply, false, '', '', $postread, true, $istracked, 0);
// Print the other posts.
echo moodleoverflow_print_posts_nested($course, $cm, $moodleoverflow, $discussion, $post, $canreply, $istracked, $posts);
}
/**
* Get all posts in discussion inculding the starting post.
*
* @param int $discussionid The ID of the discussion
* @param boolean $tracking Whether tracking is activated
*
* @return array
*/
function moodleoverflow_get_all_discussion_posts($discussionid, $tracking) {
global $DB, $USER;
// Initiate tracking settings.
$params = array();
$trackingselector = "";
$trackingjoin = "";
$params = array();
// If tracking is enabled, another join is needed.
if ($tracking) {
$trackingselector = ", mr.id AS postread";
$trackingjoin = "LEFT JOIN {moodleoverflow_read} mr ON (mr.postid = p.id AND mr.userid = :userid)";
$params['userid'] = $USER->id;
}
// Get all username fields.
$allnames = get_all_user_name_fields(true, 'u');
// Create the sql array.
$sql = "SELECT p.*, m.ratingpreference, $allnames, d.name as subject, u.email, u.picture, u.imagealt $trackingselector
FROM {moodleoverflow_posts} p
LEFT JOIN {user} u ON p.userid = u.id
LEFT JOIN {moodleoverflow_discussions} d ON d.id = p.discussion
LEFT JOIN {moodleoverflow} m on m.id = d.moodleoverflow
$trackingjoin
WHERE p.discussion = :discussion
ORDER BY p.created ASC";
$params['discussion'] = $discussionid;
// Return an empty array, if there are no posts.
if (!$posts = $DB->get_records_sql($sql, $params)) {
return array();
}
// Load all ratings.
$discussionratings = \mod_moodleoverflow\ratings::moodleoverflow_get_ratings_by_discussion($discussionid);
// Assign ratings to the posts.
foreach ($posts as $postid => $post) {
// Assign the ratings to the machting posts.
$posts[$postid]->upvotes = $discussionratings[$post->id]->upvotes;
$posts[$postid]->downvotes = $discussionratings[$post->id]->downvotes;
$posts[$postid]->statusstarter = $discussionratings[$post->id]->ishelpful;
$posts[$postid]->statusteacher = $discussionratings[$post->id]->issolved;
}
// Order the answers by their ratings.
$posts = \mod_moodleoverflow\ratings::moodleoverflow_sort_answers_by_ratings($posts);
// Find all children of this post.
foreach ($posts as $postid => $post) {
// Is it an old post?
if ($tracking) {
if (\mod_moodleoverflow\readtracking::moodleoverflow_is_old_post($post)) {
$posts[$postid]->postread = true;
}
}
// Don't iterate through the parent post.
if (!$post->parent) {
$posts[$postid]->level = 0;
continue;
}
// If the parent post does not exist.
if (!isset($posts[$post->parent])) {
continue;
}
// Create the children array.
if (!isset($posts[$post->parent]->children)) {
$posts[$post->parent]->children = array();
}
// Increase the level of the current post.
$posts[$post->parent]->children[$postid] =& $posts[$postid];
}
// Return the object.
return $posts;
}
/**
* Prints a moodleoverflow post.
*
* @param stdClass $post The post object
* @param stdClass $discussion The discussion object
* @param stdClass $moodleoverflow The moodleoverflow object
* @param object $cm
* @param stdClass $course The course object
* @param bool $ownpost Whether the post was submitted by this user
* @param bool $canreply Whether the user can reply to the post
* @param bool $link Whether there is a link to this post
* @param string $footer A default footer for posts
* @param string $highlight A word to highlight in the post
* @param null $postisread Whether the post has been read
* @param bool $dummyifcantsee Whether to display an empty dummy
* @param bool $istracked Whether the discussion is tracked
* @param bool $iscomment Whether to post is a comment
* @param int $level Determines the level of a post
*
* @return null The output
*/
function moodleoverflow_print_post($post, $discussion, $moodleoverflow, $cm, $course,
$ownpost = false, $canreply = false, $link = false,
$footer = '', $highlight = '', $postisread = null,
$dummyifcantsee = true, $istracked = false,
$iscomment = false, $level = 0) {
global $USER, $CFG, $OUTPUT, $PAGE;
// Require the filelib.
require_once($CFG->libdir . '/filelib.php');
// String cache.
static $str;
// Print the 'unread' only on time.
static $firstunreadanchorprinted = false;
// Declare the modulecontext.
$modulecontext = context_module::instance($cm->id);
// Post was anonymized.
if ($post->userid == 0) {
$post->message = get_string('privacy:anonym_post_message', 'mod_moodleoverflow');
}
// Add some informationto the post.
$post->course = $course->id;
$post->moodleoverflow = $moodleoverflow->id;
$mcid = $modulecontext->id;
$post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $mcid, 'mod_moodleoverflow', 'post', $post->id);
// Caching.
if (!isset($cm->cache)) {
$cm->cache = new stdClass();
}
// Check the cached capabilities.
if (!isset($cm->cache->caps)) {
$cm->cache->caps = array();