-
Notifications
You must be signed in to change notification settings - Fork 23
/
lib.php
1272 lines (1073 loc) · 47.5 KB
/
lib.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/>.
/**
* Library of interface functions and constants for module moodleoverflow
*
* All the core Moodle functions, neeeded to allow the module to work
* integrated in Moodle should be placed here.
*
* All the moodleoverflow specific functions, needed to implement all the module
* logic, should go to locallib.php. This will help to save some memory when
* Moodle is performing actions across all modules.
*
* @package mod_moodleoverflow
* @copyright 2017 Kennet Winter <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core\context\course;
defined('MOODLE_INTERNAL') || die();
require_once(dirname(__FILE__) . '/locallib.php');
// Readtracking constants.
define('MOODLEOVERFLOW_TRACKING_OFF', 0);
define('MOODLEOVERFLOW_TRACKING_OPTIONAL', 1);
define('MOODLEOVERFLOW_TRACKING_FORCED', 2);
// Subscription constants.
define('MOODLEOVERFLOW_CHOOSESUBSCRIBE', 0);
define('MOODLEOVERFLOW_FORCESUBSCRIBE', 1);
define('MOODLEOVERFLOW_INITIALSUBSCRIBE', 2);
define('MOODLEOVERFLOW_DISALLOWSUBSCRIBE', 3);
// Mailing state constants.
define('MOODLEOVERFLOW_MAILED_PENDING', 0);
define('MOODLEOVERFLOW_MAILED_SUCCESS', 1);
define('MOODLEOVERFLOW_MAILED_ERROR', 2);
define('MOODLEOVERFLOW_MAILED_REVIEW_SUCCESS', 3);
// Constants for the post rating.
define('MOODLEOVERFLOW_PREFERENCE_STARTER', 0);
define('MOODLEOVERFLOW_PREFERENCE_TEACHER', 1);
// Reputation constants.
define('MOODLEOVERFLOW_REPUTATION_MODULE', 0);
define('MOODLEOVERFLOW_REPUTATION_COURSE', 1);
// Allow ratings?
define('MOODLEOVERFLOW_RATING_FORBID', 0);
define('MOODLEOVERFLOW_RATING_ALLOW', 1);
// Allow reputations?
define('MOODLEOVERFLOW_REPUTATION_FORBID', 0);
define('MOODLEOVERFLOW_REPUTATION_ALLOW', 1);
// Allow negative reputations?
define('MOODLEOVERFLOW_REPUTATION_POSITIVE', 0);
define('MOODLEOVERFLOW_REPUTATION_NEGATIVE', 1);
// Rating constants.
define('RATING_NEUTRAL', 0);
define('RATING_DOWNVOTE', 1);
define('RATING_REMOVE_DOWNVOTE', 10);
define('RATING_UPVOTE', 2);
define('RATING_REMOVE_UPVOTE', 20);
define('RATING_SOLVED', 3);
define('RATING_REMOVE_SOLVED', 30);
define('RATING_HELPFUL', 4);
define('RATING_REMOVE_HELPFUL', 40);
/* Moodle core API */
/**
* Returns the information on whether the module supports a feature.
*
* See {plugin_supports()} for more info.
*
* @param string $feature FEATURE_xx constant for requested feature
*
* @return mixed true if the feature is supported, null if unknown
*/
function moodleoverflow_supports($feature) {
if (defined('FEATURE_MOD_PURPOSE')) {
if ($feature == FEATURE_MOD_PURPOSE) {
return MOD_PURPOSE_COLLABORATION;
}
}
switch ($feature) {
case FEATURE_MOD_INTRO:
return true;
case FEATURE_SHOW_DESCRIPTION:
return true;
case FEATURE_BACKUP_MOODLE2:
return true;
case FEATURE_GRADE_HAS_GRADE:
return true;
default:
return null;
}
}
/**
* Saves a new instance of the moodleoverflow into the database.
*
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will create a new instance and return the id number
* of the new instance.
*
* @param stdClass $moodleoverflow Submitted data from the form in mod_form.php
* @param mod_moodleoverflow_mod_form $mform The form instance itself (if needed)
*
* @return int The id of the newly inserted moodleoverflow record
*/
function moodleoverflow_add_instance(stdClass $moodleoverflow, ?mod_moodleoverflow_mod_form $mform = null) {
global $DB;
// Set the current time.
$moodleoverflow->timecreated = time();
// You may have to add extra stuff in here.
$moodleoverflow->id = $DB->insert_record('moodleoverflow', $moodleoverflow);
return $moodleoverflow->id;
}
/**
* Handle changes following the creation of a moodleoverflow instance.
* This function is typically called by the course_module_created observer.
*
* @param object $context The context of the moodleoverflow
* @param stdClass $moodleoverflow The moodleoverflow object
*/
function moodleoverflow_instance_created($context, $moodleoverflow) {
// Check if users are forced to be subscribed to the moodleoverflow instance.
if ($moodleoverflow->forcesubscribe == MOODLEOVERFLOW_INITIALSUBSCRIBE) {
// Get a list of all potential subscribers.
$users = \mod_moodleoverflow\subscriptions::get_potential_subscribers($context, 'u.id, u.email');
// Subscribe all potential subscribers to this moodleoverflow.
foreach ($users as $user) {
\mod_moodleoverflow\subscriptions::subscribe_user($user->id, $moodleoverflow, $context);
}
}
}
/**
* Updates an instance of the moodleoverflow in the database.
*
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @param stdClass $moodleoverflow An object from the form in mod_form.php
* @param mod_moodleoverflow_mod_form|null $mform The form instance itself (if needed)
*
* @return boolean Success/Fail
*/
function moodleoverflow_update_instance(stdClass $moodleoverflow, ?mod_moodleoverflow_mod_form $mform = null) {
global $DB;
$moodleoverflow->timemodified = time();
$moodleoverflow->id = $moodleoverflow->instance;
// Get the old record.
$oldmoodleoverflow = $DB->get_record('moodleoverflow', ['id' => $moodleoverflow->id]);
// Find the context of the module.
$modulecontext = context_module::instance($moodleoverflow->coursemodule);
// Check if the subscription state has changed.
if ($moodleoverflow->forcesubscribe != $oldmoodleoverflow->forcesubscribe) {
if ($moodleoverflow->forcesubscribe == MOODLEOVERFLOW_INITIALSUBSCRIBE) {
// Get a list of potential subscribers.
$users = \mod_moodleoverflow\subscriptions::get_potential_subscribers($modulecontext, 'u.id, u.email', '');
// Subscribe all those users to the moodleoverflow instance.
foreach ($users as $user) {
\mod_moodleoverflow\subscriptions::subscribe_user($user->id, $moodleoverflow, $modulecontext);
}
} else if ($moodleoverflow->forcesubscribe == MOODLEOVERFLOW_CHOOSESUBSCRIBE) {
// Delete all current subscribers.
$DB->delete_records('moodleoverflow_subscriptions', ['moodleoverflow' => $moodleoverflow->id]);
}
}
// Update the moodleoverflow instance in the database.
$result = $DB->update_record('moodleoverflow', $moodleoverflow);
moodleoverflow_grade_item_update($moodleoverflow);
// Update all grades.
moodleoverflow_update_all_grades_for_cm($moodleoverflow->id);
return $result;
}
/**
* This standard function will check all instances of this module
* and make sure there are up-to-date events created for each of them.
* If courseid = 0, then every moodleoverflow event in the site is checked, else
* only moodleoverflow events belonging to the course specified are checked.
* This is only required if the module is generating calendar events.
*
* @param int $courseid Course ID
*
* @return bool
*/
function moodleoverflow_refresh_events($courseid = 0) {
global $DB;
if ($courseid == 0) {
if (!$DB->get_records('moodleoverflow')) {
return true;
}
} else {
if (!$DB->get_records('moodleoverflow', ['course' => $courseid])) {
return true;
}
}
return true;
}
/**
* Removes an instance of the moodleoverflow from the database.
*
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @param int $id Id of the module instance
*
* @return boolean Success/Failure
*/
function moodleoverflow_delete_instance($id) {
global $DB;
// Initiate the variables.
$result = true;
// Get the needed objects.
if (!$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $id])) {
return false;
}
if (!$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflow->id)) {
return false;
}
if (!$course = $DB->get_record('course', ['id' => $cm->course])) {
return false;
}
// Get the context module.
$context = context_module::instance($cm->id);
// Delete all connected files.
$fs = get_file_storage();
$fs->delete_area_files($context->id);
// Delete the subscription elements.
$DB->delete_records('moodleoverflow_subscriptions', ['moodleoverflow' => $moodleoverflow->id]);
$DB->delete_records('moodleoverflow_discuss_subs', ['moodleoverflow' => $moodleoverflow->id]);
$DB->delete_records('moodleoverflow_grades', ['moodleoverflowid' => $moodleoverflow->id]);
// Delete the discussion recursivly.
if ($discussions = $DB->get_records('moodleoverflow_discussions', ['moodleoverflow' => $moodleoverflow->id])) {
require_once('locallib.php');
foreach ($discussions as $discussion) {
if (!moodleoverflow_delete_discussion($discussion, $course, $cm, $moodleoverflow)) {
$result = false;
}
}
}
// Delete the read records.
\mod_moodleoverflow\readtracking::moodleoverflow_delete_read_records(-1, -1, -1, $moodleoverflow->id);
// Delete the moodleoverflow instance.
if (!$DB->delete_records('moodleoverflow', ['id' => $moodleoverflow->id])) {
$result = false;
}
// Return whether the deletion was successful.
return $result;
}
/**
* Returns a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
*
* $return->time = the time they did it
* $return->info = a short text description
*
* @param stdClass $course The course record
* @param stdClass $user The user record
* @param cm_info|stdClass $mod The course module info object or record
* @param stdClass $moodleoverflow The moodleoverflow instance record
*
* @return stdClass|null
*/
function moodleoverflow_user_outline($course, $user, $mod, $moodleoverflow) {
$return = new stdClass();
$return->time = 0;
$return->info = '';
return $return;
}
/**
* Given a course and a time, this module should find recent activity
* that has occurred in moodleoverflow activities and print it out.
*
* @param stdClass $course The course record
* @param bool $viewfullnames Should we display full names
* @param int $timestart Print activity since this timestamp
*
* @return boolean True if anything was printed, otherwise false
*/
function moodleoverflow_print_recent_activity($course, $viewfullnames, $timestart) {
return false;
}
/**
* Returns all other caps used in the module.
*
* For example, this could be array('moodle/site:accessallgroups') if the
* module uses that capability.
*
* @return array
*/
function moodleoverflow_get_extra_capabilities() {
return [];
}
/* File API */
/**
* Returns the lists of all browsable file areas within the given module context.
*
* The file area 'intro' for the activity introduction field is added automatically
* by { file_browser::get_file_info_context_module()}
*
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
*
* @return array of [(string)filearea] => (string)description
*/
function moodleoverflow_get_file_areas($course, $cm, $context) {
return [
'attachment' => get_string('areaattachment', 'mod_moodleoverflow'),
'post' => get_string('areapost', 'mod_moodleoverflow'),
];
}
/**
* File browsing support for moodleoverflow file areas.
*
* @package mod_moodleoverflow
* @category files
*
* @param file_browser $browser
* @param array $areas
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @param string $filearea
* @param int $itemid
* @param string $filepath
* @param string $filename
*
* @return file_info instance or null if not found
*/
function moodleoverflow_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
return null;
}
/**
* Serves the files from the moodleoverflow file areas.
*
* @package mod_moodleoverflow
* @category files
*
* @param stdClass $course the course object
* @param stdClass $cm the course module object
* @param stdClass $context the moodleoverflow's context
* @param string $filearea the name of the file area
* @param array $args extra arguments (itemid, path)
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
*/
function moodleoverflow_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = []) {
global $DB, $CFG;
if ($context->contextlevel != CONTEXT_MODULE) {
return false;
}
require_course_login($course, true, $cm);
$areas = moodleoverflow_get_file_areas($course, $cm, $context);
// Filearea must contain a real area.
if (!isset($areas[$filearea])) {
return false;
}
$filename = array_pop($args);
$itemid = array_pop($args);
// Check if post, discussion or moodleoverflow still exists.
if (!$post = $DB->get_record('moodleoverflow_posts', ['id' => $itemid])) {
return false;
}
if (!$discussion = $DB->get_record('moodleoverflow_discussions', ['id' => $post->discussion])) {
return false;
}
if (!$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $cm->instance])) {
return false;
}
if (!$args) {
// Empty path, use root.
$filepath = '/';
} else {
// Assemble filepath.
$filepath = '/' . implode('/', $args) . '/';
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'mod_moodleoverflow', $filearea, $itemid, $filepath, $filename);
// Make sure we're allowed to see it...
if (!moodleoverflow_user_can_see_post($moodleoverflow, $discussion, $post, $cm)) {
return false;
}
// Finally send the file.
send_stored_file($file, 86400, 0, true, $options); // Download MUST be forced - security!
}
/* Navigation API */
/**
* Extends the settings navigation with the moodleoverflow settings.
*
* This function is called when the context for the page is a moodleoverflow module. This is not called by AJAX
* so it is safe to rely on the $PAGE.
*
* @param settings_navigation $settingsnav complete settings navigation tree
* @param navigation_node|null $moodleoverflownode moodleoverflow administration node
*/
function moodleoverflow_extend_settings_navigation(settings_navigation $settingsnav, ?navigation_node $moodleoverflownode = null) {
global $CFG, $DB, $PAGE, $USER;
// Retrieve the current moodle record.
$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $PAGE->cm->instance]);
// Check if the user can subscribe to the instance.
$enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
$activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);
$canmanage = has_capability('mod/moodleoverflow:managesubscriptions', $PAGE->cm->context);
$forcesubscribed = \mod_moodleoverflow\subscriptions::is_forcesubscribed($moodleoverflow);
$subscdisabled = \mod_moodleoverflow\subscriptions::subscription_disabled($moodleoverflow);
$cansubscribe = $activeenrolled && (!$subscdisabled || $canmanage) &&
!($forcesubscribed && has_capability('mod/moodleoverflow:allowforcesubscribe', $PAGE->cm->context));
$cantrack = \mod_moodleoverflow\readtracking::moodleoverflow_can_track_moodleoverflows($moodleoverflow);
// Display a link to the index.
if ($enrolled && $activeenrolled) {
// Generate the text of the link.
$linktext = get_string('gotoindex', 'moodleoverflow');
// Generate the link.
$url = '/mod/moodleoverflow/index.php';
$params = ['id' => $moodleoverflow->course];
$link = new moodle_url($url, $params);
// Add the link to the menu.
$moodleoverflownode->add($linktext, $link, navigation_node::TYPE_SETTING);
}
// Display a link to subscribe or unsubscribe.
if ($cansubscribe) {
// Choose the linktext depending on the current state of subscription.
$issubscribed = \mod_moodleoverflow\subscriptions::is_subscribed($USER->id, $moodleoverflow, $PAGE->cm->context);
if ($issubscribed) {
$linktext = get_string('unsubscribe', 'moodleoverflow');
} else {
$linktext = get_string('subscribe', 'moodleoverflow');
}
// Add the link to the menu.
$url = new moodle_url('/mod/moodleoverflow/subscribe.php', ['id' => $moodleoverflow->id, 'sesskey' => sesskey()]);
$moodleoverflownode->add($linktext, $url, navigation_node::TYPE_SETTING);
}
// Display a link to enable or disable readtracking.
if ($enrolled && $cantrack) {
// Check some basic capabilities.
$isoptional = ($moodleoverflow->trackingtype == MOODLEOVERFLOW_TRACKING_OPTIONAL);
$forceallowed = get_config('moodleoverflow', 'allowforcedreadtracking');
$isforced = ($moodleoverflow->trackingtype == MOODLEOVERFLOW_TRACKING_FORCED);
// Check whether the readtracking state can be changed.
if ($isoptional || (!$forceallowed && $isforced)) {
// Generate the text of the link depending on the current state.
$istracked = \mod_moodleoverflow\readtracking::moodleoverflow_is_tracked($moodleoverflow);
if ($istracked) {
$linktext = get_string('notrackmoodleoverflow', 'moodleoverflow');
} else {
$linktext = get_string('trackmoodleoverflow', 'moodleoverflow');
}
// Generate the link.
$url = '/mod/moodleoverflow/tracking.php';
$params = ['id' => $moodleoverflow->id, 'sesskey' => sesskey()];
$link = new moodle_url($url, $params);
// Add the link to the menu.
$moodleoverflownode->add($linktext, $link, navigation_node::TYPE_SETTING);
}
}
}
/**
* Determine the current context if one wa not already specified.
*
* If a context of type context_module is specified, it is immediately returned and not checked.
*
* @param int $moodleoverflowid The moodleoverflow ID
* @param context_module $context The current context
*
* @return context_module The context determined
*/
function moodleoverflow_get_context($moodleoverflowid, $context = null) {
global $PAGE;
// If the context does not exist, find the context.
if (!$context || !($context instanceof context_module)) {
// Try to take current page context to save on DB query.
if ($PAGE->cm && $PAGE->cm->modname === 'moodleoverflow' && $PAGE->cm->instance == $moodleoverflowid
&& $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id
) {
$context = $PAGE->context;
} else {
// Get the context via the coursemodule.
$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflowid);
$context = \context_module::instance($cm->id);
}
}
// Return the context.
return $context;
}
/**
* Sends mail notifications about new posts.
*
* @return bool
*/
function moodleoverflow_send_mails() {
global $DB, $CFG, $PAGE;
// Get the course object of the top level site.
$site = get_site();
// Get the main renderers.
$htmlout = $PAGE->get_renderer('mod_moodleoverflow', 'email', 'htmlemail');
$textout = $PAGE->get_renderer('mod_moodleoverflow', 'email', 'textemail');
// Initiate the arrays that are saving the users that are subscribed to posts that needs sending.
$users = [];
$userscount = 0; // Count($users) is slow. This avoids using this.
// Status arrays.
$mailcount = [];
$errorcount = [];
// Cache arrays.
$discussions = [];
$moodleoverflows = [];
$courses = [];
$coursemodules = [];
$subscribedusers = [];
// Posts older than x days will not be mailed.
// This will avoid problems with the cron not beeing ran for a long time.
$timenow = time();
$endtime = $timenow - get_config('moodleoverflow', 'maxeditingtime');
$starttime = $endtime - (get_config('moodleoverflow', 'maxmailingtime') * 60 * 60);
// Retrieve all unmailed posts.
$posts = moodleoverflow_get_unmailed_posts($starttime, $endtime);
if ($posts) {
// Mark those posts as mailed.
if (!moodleoverflow_mark_old_posts_as_mailed($endtime)) {
mtrace('Errors occurred while trying to mark some posts as being mailed.');
return false;
}
// Loop through all posts to be mailed.
foreach ($posts as $postid => $post) {
// Check the cache if the discussion exists.
$discussionid = $post->discussion;
if (!isset($discussions[$discussionid])) {
// Retrieve the discussion from the database.
$discussion = $DB->get_record('moodleoverflow_discussions', ['id' => $post->discussion]);
// If there is a record, update the cache. Else ignore the post.
if ($discussion) {
$discussions[$discussionid] = $discussion;
\mod_moodleoverflow\subscriptions::fill_subscription_cache($discussion->moodleoverflow);
\mod_moodleoverflow\subscriptions::fill_discussion_subscription_cache($discussion->moodleoverflow);
} else {
mtrace('Could not find discussion ' . $discussionid);
unset($posts[$postid]);
continue;
}
}
// Retrieve the connected moodleoverflow instance from the database.
$moodleoverflowid = $discussions[$discussionid]->moodleoverflow;
if (!isset($moodleoverflows[$moodleoverflowid])) {
// Retrieve the record from the database and update the cache.
$moodleoverflow = $DB->get_record('moodleoverflow', ['id' => $moodleoverflowid]);
if ($moodleoverflow) {
$moodleoverflows[$moodleoverflowid] = $moodleoverflow;
} else {
mtrace('Could not find moodleoverflow ' . $moodleoverflowid);
unset($posts[$postid]);
continue;
}
}
// Retrieve the connected courses from the database.
$courseid = $moodleoverflows[$moodleoverflowid]->course;
if (!isset($courses[$courseid])) {
// Retrieve the record from the database and update the cache.
$course = $DB->get_record('course', ['id' => $courseid]);
if ($course) {
$courses[$courseid] = $course;
} else {
mtrace('Could not find course ' . $courseid);
unset($posts[$postid]);
continue;
}
}
// Retrieve the connected course modules from the database.
if (!isset($coursemodules[$moodleoverflowid])) {
// Retrieve the coursemodule and update the cache.
$cm = get_coursemodule_from_instance('moodleoverflow', $moodleoverflowid, $courseid);
if ($cm) {
$coursemodules[$moodleoverflowid] = $cm;
} else {
mtrace('Could not find course module for moodleoverflow ' . $moodleoverflowid);
unset($posts[$postid]);
continue;
}
}
// Cache subscribed users of each moodleoverflow.
if (!isset($subscribedusers[$moodleoverflowid])) {
// Retrieve the context module.
$modulecontext = context_module::instance($coursemodules[$moodleoverflowid]->id);
// Retrieve all subscribed users.
$mid = $moodleoverflows[$moodleoverflowid];
$subusers = \mod_moodleoverflow\subscriptions::get_subscribed_users($mid, $modulecontext, 'u.*', true);
if ($subusers) {
// Loop through all subscribed users.
foreach ($subusers as $postuser) {
// Save the user into the cache.
$subscribedusers[$moodleoverflowid][$postuser->id] = $postuser->id;
$userscount++;
moodleoverflow_minimise_user_record($postuser);
$users[$postuser->id] = $postuser;
}
// Release the memory.
unset($subusers);
unset($postuser);
}
}
// Initiate the count of the mails send and errors.
$mailcount[$postid] = 0;
$errorcount[$postid] = 0;
}
}
// Send mails to the users with information about the posts.
if ($users && $posts) {
// Send one mail to every user.
foreach ($users as $userto) {
// Terminate if the process takes more time then two minutes.
core_php_time_limit::raise(120);
// Tracing information.
mtrace('Processing user ' . $userto->id);
// Initiate the user caches to save memory.
$userto = clone($userto);
$userto->ciewfullnames = [];
$userto->canpost = [];
$userto->markposts = [];
// Cache the capabilities of the user.
// Check for moodle version. Version 401 supported until 8 December 2025.
if ($CFG->branch >= 402) {
\core\cron::setup_user($userto);
} else {
cron_setup_user($userto);
}
// Reset the caches.
foreach ($coursemodules as $moodleoverflowid => $unused) {
$coursemodules[$moodleoverflowid]->cache = new stdClass();
$coursemodules[$moodleoverflowid]->cache->caps = [];
unset($coursemodules[$moodleoverflowid]->uservisible);
}
// Loop through all posts of this users.
foreach ($posts as $postid => $post) {
// Initiate variables for the post.
$discussion = $discussions[$post->discussion];
$moodleoverflow = $moodleoverflows[$discussion->moodleoverflow];
$course = $courses[$moodleoverflow->course];
$cm =& $coursemodules[$moodleoverflow->id];
// Check if user wants a resume.
// in this case: make a new dataset in "moodleoverflow_mail_info" to save the posts data.
// Dataset from moodleoverflow_mail_info will be send later in a mail.
$usermailsetting = $userto->maildigest;
if ($usermailsetting != 0) {
$dataobject = new stdClass();
$dataobject->userid = $userto->id;
$dataobject->courseid = $course->id;
$dataobject->forumid = $moodleoverflow->id;
$dataobject->forumdiscussionid = $discussion->id;
$record = $DB->get_record('moodleoverflow_mail_info',
['userid' => $dataobject->userid,
'courseid' => $dataobject->courseid,
'forumid' => $dataobject->forumid,
'forumdiscussionid' => $dataobject->forumdiscussionid, ],
'numberofposts, id');
if (is_object($record)) {
$dataset = $record;
$dataobject->numberofposts = $dataset->numberofposts + 1;
$dataobject->id = $dataset->id;
$DB->update_record('moodleoverflow_mail_info', $dataobject);
} else {
$dataobject->numberofposts = 1;
$DB->insert_record('moodleoverflow_mail_info', $dataobject);
}
continue;
}
// Check whether the user is subscribed.
if (!isset($subscribedusers[$moodleoverflow->id][$userto->id])) {
continue;
}
// Check whether the user is subscribed to the discussion.
$iscm = $coursemodules[$moodleoverflow->id];
$uid = $userto->id;
$did = $post->discussion;
$issubscribed = \mod_moodleoverflow\subscriptions::is_subscribed($uid, $moodleoverflow, $modulecontext, $did);
if (!$issubscribed) {
continue;
}
// Check whether the user unsubscribed to the discussion after it was created.
$subnow = \mod_moodleoverflow\subscriptions::fetch_discussion_subscription($moodleoverflow->id, $userto->id);
if ($subnow && isset($subnow[$post->discussion]) && ($subnow[$post->discussion] > $post->created)) {
continue;
}
if (\mod_moodleoverflow\anonymous::is_post_anonymous($discussion, $moodleoverflow, $post->userid)) {
$userfrom = \core_user::get_noreply_user();
} else {
// Check whether the sending user is cached already.
if (array_key_exists($post->userid, $users)) {
$userfrom = $users[$post->userid];
} else {
// We dont know the the user yet.
// Retrieve the user from the database.
$userfrom = $DB->get_record('user', ['id' => $post->userid]);
if ($userfrom) {
moodleoverflow_minimise_user_record($userfrom);
} else {
$uid = $post->userid;
$pid = $post->id;
mtrace('Could not find user ' . $uid . ', author of post ' . $pid . '. Unable to send message.');
continue;
}
}
}
// Setup roles and languages.
// Check for moodle version. Version 401 supported until 8 December 2025.
if ($CFG->branch >= 402) {
\core\cron::setup_user($userto, $course);
} else {
cron_setup_user($userto, $course);
}
// Cache the users capability to view full names.
if (!isset($userto->viewfullnames[$moodleoverflow->id])) {
// Find the context module.
$modulecontext = context_module::instance($cm->id);
// Check the users capabilities.
$userto->viewfullnames[$moodleoverflow->id] = has_capability('moodle/site:viewfullnames', $modulecontext);
}
// Cache the users capability to post in the discussion.
if (!isset($userto->canpost[$discussion->id])) {
// Find the context module.
$modulecontext = context_module::instance($cm->id);
// Check the users capabilities.
$canpost = moodleoverflow_user_can_post($modulecontext, $post, $userto->id);
$userto->canpost[$discussion->id] = $canpost;
}
// Make sure the current user is allowed to see the post.
if (!moodleoverflow_user_can_see_post($moodleoverflow, $discussion, $post, $cm)) {
mtrace('User ' . $userto->id . ' can not see ' . $post->id . '. Not sending message.');
continue;
}
// Sent the email.
// Preapare to actually send the post now. Build up the content.
$cleanname = str_replace('"', "'", strip_tags(format_string($moodleoverflow->name)));
$coursecontext = context_course::instance($course->id);
$shortname = format_string($course->shortname, true, ['context' => $coursecontext]);
// Define a header to make mails easier to track.
$emailmessageid = generate_email_messageid('moodlemoodleoverflow' . $moodleoverflow->id);
$userfrom->customheaders = [
'List-Id: "' . $cleanname . '" ' . $emailmessageid,
'List-Help: ' . $CFG->wwwroot . '/mod/moodleoverflow/view.php?m=' . $moodleoverflow->id,
'Message-ID: ' . generate_email_messageid(hash('sha256', $post->id . 'to' . $userto->id)),
'X-Course-Id: ' . $course->id,
'X-Course-Name: ' . format_string($course->fullname, true),
// Headers to help prevent auto-responders.
'Precedence: Bulk',
'X-Auto-Response-Suppress: All',
'Auto-Submitted: auto-generated',
];
// Cache the users capabilities.
if (!isset($userto->canpost[$discussion->id])) {
$canreply = moodleoverflow_user_can_post($modulecontext, $post, $userto->id);
} else {
$canreply = $userto->canpost[$discussion->id];
}
// Format the data.
$data = new \mod_moodleoverflow\output\moodleoverflow_email(
$course,
$cm,
$moodleoverflow,
$discussion,
$post,
$userfrom,
$userto,
$canreply
);
// Retrieve the unsubscribe-link.
$userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>', $data->get_unsubscribediscussionlink());
// Check the capabilities to view full names.
if (!isset($userto->viewfullnames[$moodleoverflow->id])) {
$data->viewfullnames = has_capability('moodle/site:viewfullnames', $modulecontext, $userto->id);
} else {
$data->viewfullnames = $userto->viewfullnames[$moodleoverflow->id];
}
// Retrieve needed variables for the mail.
$var = new \stdClass();
$var->subject = $data->get_subject();
$var->moodleoverflowname = $cleanname;
$var->sitefullname = format_string($site->fullname);
$var->siteshortname = format_string($site->shortname);
$var->courseidnumber = $data->get_courseidnumber();
$var->coursefullname = $data->get_coursefullname();
$var->courseshortname = $data->get_coursename();
$postsubject = html_to_text(get_string('postmailsubject', 'moodleoverflow', $var), 0);
$rootid = generate_email_messageid(hash('sha256', $discussion->firstpost . 'to' . $userto->id));
// Check whether the post is a reply.
if ($post->parent) {
// Add a reply header.
$parentid = generate_email_messageid(hash('sha256', $post->parent . 'to' . $userto->id));
$userfrom->customheaders[] = "In-Reply-To: $parentid";
// Comments need a reference to the starting post as well.
if ($post->parent != $discussion->firstpost) {
$userfrom->customheaders[] = "References: $rootid $parentid";
} else {
$userfrom->customheaders[] = "References: $parentid";
}
}
// Send the post now.
mtrace('Sending ', '');
// Create the message event.
$eventdata = new \core\message\message();
$eventdata->courseid = $course->id;
$eventdata->component = 'mod_moodleoverflow';
$eventdata->name = 'posts';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $userto;
$eventdata->subject = $postsubject;
$eventdata->fullmessage = $textout->render($data);
$eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->fullmessagehtml = $htmlout->render($data);
$eventdata->notification = 1;
// Initiate another message array.
$small = new \stdClass();
$small->user = fullname($userfrom);
$formatedstring = format_string($moodleoverflow->name, true);
$small->moodleoverflowname = "$shortname: " . $formatedstring . ": " . $discussion->name;
$small->message = $post->message;
// Make sure the language is correct.
$usertol = $userto->lang;
$eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'moodleoverflow', $small, $usertol);
// Generate the url to view the post.
$url = '/mod/moodleoverflow/discussion.php';
$params = ['d' => $discussion->id];
$contexturl = new moodle_url($url, $params, 'p' . $post->id);
$eventdata->contexturl = $contexturl->out();
$eventdata->contexturlname = $discussion->name;
// Actually send the message.
$mailsent = message_send($eventdata);
// Check whether the sending failed.
if (!$mailsent) {
mtrace('Error: mod/moodleoverflow/classes/task/send_mail.php execute(): ' .
"Could not send out mail for id $post->id to user $userto->id ($userto->email) .. not trying again.");
$errorcount[$post->id]++;
} else {
$mailcount[$post->id]++;
}
// Tracing message.
mtrace('post ' . $post->id . ': ' . $discussion->name);
}
// Release the memory.
unset($userto);