/
mod_forumng_cron.php
1123 lines (1011 loc) · 51.1 KB
/
mod_forumng_cron.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/>.
require_once(dirname(__FILE__).'/mod_forumng.php');
require_once(dirname(__FILE__).'/mod_forumng_mail_list.php');
require_once(dirname(__FILE__).'/mod_forumng_digest_list.php');
/**
* Utility class handling all cron tasks.
* @package mod
* @subpackage forumng
* @copyright 2011 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mod_forumng_cron {
const DEBUG_VIEW_EMAILS = false;
/** Divider used between sections of email */
const EMAIL_DIVIDER =
"---------------------------------------------------------------------\n";
public static function delete_old_posts() {
global $CFG, $DB;
// Check if deletion is turned off
if (empty($CFG->forumng_permanentdeletion)) {
return;
}
mtrace('Beginning forum deleted/edit message cleanup...');
// Work out how long ago things have to have been 'deleted' before we
// permanently delete them
$deletebefore = time() - $CFG->forumng_permanentdeletion;
// Handle all posts which were deleted (that long ago) or which are in
// discussions which were deleted (that long ago)
$mainparams = array();
$mainquery = "
FROM
{forumng_posts} fp
INNER JOIN {forumng_discussions} fd ON fd.id = fp.discussionid
INNER JOIN {forumng} f ON fd.forumngid = f.id
INNER JOIN {course_modules} cm ON cm.instance = f.id AND cm.module =
(SELECT id FROM {modules} WHERE name='forumng')
INNER JOIN {context} x on x.instanceid=cm.id AND x.contextlevel=?
WHERE
(fp.deleted<>0 AND fp.deleted<? AND
NOT EXISTS (SELECT id from {forumng_posts} where parentpostid = fp.id and deleted = 0))
OR (fp.oldversion<>0 AND fp.modified<?)
OR (fd.deleted<>0 AND fd.deleted<?)";
$idquery = "SELECT fp.id $mainquery ";
$mainparams[] = CONTEXT_MODULE;
$mainparams[] = $deletebefore;
$mainparams[] = $deletebefore;
$mainparams[] = $deletebefore;
$before = microtime(true);
mtrace('Message search: ', '');
$count = $DB->count_records_sql("SELECT COUNT(1) $mainquery", $mainparams);
mtrace(round(microtime(true)-$before, 1) .'s');
if ($count == 0) {
mtrace("No old deleted / edited messages to clean up.");
} else {
mtrace("Permanently deleting $count old deleted / edited messages.");
}
if ($count) {
$before = microtime(true);
mtrace('Database post deletion: ', '');
$transaction = $DB->start_delegated_transaction();
// Delete all ratings
$DB->execute("DELETE FROM {forumng_ratings} WHERE postid IN ($idquery)",
$mainparams);
// Delete all read post records.
$DB->execute("DELETE FROM {forumng_read_posts} WHERE postid IN ($idquery)", $mainparams);
// Find all messages...
$rs = $DB->get_recordset_sql("
SELECT
fp.id AS postid, x.id AS contextid, fp.attachments
$mainquery", $mainparams);
// Delete all attachments - this is very very slow (at least 1 query
// per post being deleted), it could be done faster in the database
// but I thought it might be safer to use the API
$fs = get_file_storage();
foreach ($rs as $attachmentrecord) {
// Delete both attachments & message attachments
if ($attachmentrecord->attachments) {
// Only if marked as existing
$fs->delete_area_files($attachmentrecord->contextid,
'mod_forumng', 'attachment', $attachmentrecord->postid);
}
// Always (there is no marker for this one)
$fs->delete_area_files($attachmentrecord->contextid,
'mod_forumng', 'message', $attachmentrecord->postid);
}
$rs->close();
// Delete all posts
mod_forumng_utils::update_with_subquery_grrr_mysql(
"DELETE FROM {forumng_posts} WHERE id %'IN'%",
$idquery, $mainparams);
// Now delete all discussions
$DB->execute(
"DELETE FROM {forumng_discussions} WHERE deleted<>0 AND deleted<?",
array($deletebefore));
$transaction->allow_commit();
mtrace(round(microtime(true)-$before, 1) .'s');
}
}
/**
* @param string $text Text to output, or none if you only want to check
* the value
* @param string $lf Set to '' if you don't want a linefeed
* @return bool True if debug output is enabled
*/
public static function debug($text = '', $lf = "\n") {
static $checked = false, $debug;
if (!$checked) {
$debug = debugging('', DEBUG_DEVELOPER);
}
if (!$debug) {
return false;
}
if ($text) {
mtrace($text, $lf);
}
return true;
}
public static function email_normal() {
global $USER, $CFG, $PERF;
mod_forumng_mail_list::reset_static_cache();
$exceptioncount = 0;
// Obtain information about all mails that are due for sending.
mtrace('Email processing:');
$before = microtime(true);
if (!empty($PERF->dbqueries)) {
$beforequeries = $PERF->dbqueries;
}
// Cumulative time spent actually sending emails.
$mailtime = 0;
$totalemailcount = 0;
// Cumulative time on other activities.
$getsubscriberstime = 0;
$filtersubscriberstime = 0;
$discussionsubscriberstime = 0;
$buildemailtime = 0;
$eventlogtime = 0;
$totalpostcount = 0;
$listtimes = [];
$endafter = time() + get_config('mod_forumng', 'cronlimit');
while (true) {
$list = new mod_forumng_mail_list(true);
if ($list->is_finished()) {
mtrace('No more forum posts to send.');
self::add_list_times($listtimes, $list);
break;
}
// Forum loop.
while ($list->next_forum($forum, $cm, $context, $course)) {
// Log forum details.
mtrace($course->shortname . ' - ' . $forum->get_name() . ' (cmid ' . $cm->id .
'): ', '');
// We had problems with cron running out of memory when it sends
// a lot of emails. On the basis that the PHP garbage collector
// might have 'issues', perhaps it may help to call it manually.
gc_collect_cycles();
// Set up course details
// Note: This code is a bit sketchy; borrowed from cron_setup_user.
$PAGE = new moodle_page();
$PAGE->set_course($course);
// Count posts and emails just for logging.
$postcount = 0;
$emailcount = 0;
// Get subscribers to forum.
try {
$innerbefore = microtime(true);
$subscribers = $forum->get_subscribers();
$getsubscriberstime += microtime(true) - $innerbefore;
self::debug("DEBUG: Subscribers before filter " . count($subscribers), '');
$innerbefore = microtime(true);
self::email_filter_subscribers($course, $cm, $forum, $subscribers, false);
$filtersubscriberstime += microtime(true) - $innerbefore;
self::debug(", after " . count($subscribers));
if (count($subscribers) == 0) {
continue;
}
} catch (coding_exception $e) {
// If an error occurs while getting subscribers, continue
// to next forum.
mtrace(' Exception while getting subscribers for forum ' .
$forum->get_id());
mtrace($e->__toString());
continue;
}
while ($list->next_discussion($discussion)) {
self::debug("DEBUG: Discussion " . $discussion->get_subject() .
' (' . $discussion->get_id() . ')');
// Evaluate list of users based on this discussion (which holds
// group info). Organise list by language, timezone and email
// type.
$langusers = array();
$innerbefore = microtime(true);
foreach ($subscribers as $subscriber) {
// Conditions for each subscriber to get this discussion.
if (self::subscriber_receives_discussion(
$forum, $discussion, $subscriber)) {
$oldlang = $USER->lang;
$USER->lang = $subscriber->lang;
$lang = current_language();
$USER->lang = $oldlang;
$langusers[$lang][$subscriber->timezone][$subscriber->emailtype][$subscriber->id] = $subscriber;
}
}
$discussionsubscriberstime += microtime(true) - $innerbefore;
if (self::debug()) {
$debugcount = 0;
foreach ($langusers as $lang => $tzusers) {
foreach ($tzusers as $timezone => $typeusers) {
foreach ($typeusers as $emailtype => $users) {
mtrace("DEBUG: Subscribers for lang [$lang] " .
"tz [$timezone] type [$emailtype]: " .
count($users));
$debugcount += count($users);
}
}
}
mtrace("DEBUG: Total discussion subscribers: $debugcount");
}
while ($list->next_post($post, $inreplyto)) {
if (self::debug()) {
mtrace("DEBUG: Post " . $post->get_id(), '');
$debugcount = $emailcount;
}
try {
$from = clone $post->get_user();
// These loops are intended so that we generate identical
// emails once only, and can then send them in batches.
foreach ($langusers as $lang => $tzusers) {
foreach ($tzusers as $timezone => $typeusers) {
foreach ($typeusers as $emailtype => $users) {
// We get both plaintext and html versions.
// The html version will be blank if set to
// plain text mode.
$innerbefore = microtime(true);
if ($CFG->forumng_usebcc && $post->get_asmoderator() == mod_forumng::ASMODERATOR_NO &&
$forum->get_can_post_anon() == mod_forumng::CANPOSTATON_NONMODERATOR) {
$from->maildisplay = false;
$from->firstname = get_string('identityprotected', 'forumng');
$from->lastname = '';
}
if ($post->get_asmoderator() == mod_forumng::ASMODERATOR_ANON) {
$from->maildisplay = false;
$from->firstname = get_string('moderator', 'forumng');
$from->lastname = '';
}
if ($forum->get_can_post_anon() != mod_forumng::CANPOSTATON_NONMODERATOR ||
$CFG->forumng_usebcc) {
$post->build_email($inreplyto, $subject,
$plaintext, $html, $emailtype & 1,
$emailtype & 2, $emailtype & 4, $lang,
$timezone, false, false, ['mailto_userid' => -1]);
}
$buildemailtime += microtime(true) - $innerbefore;
$innerbefore = microtime(true);
// Basic email headers (similar to core forum).
$headers = [
// Headers to make emails easier to track.
'List-Id: "' . str_replace('"', "'", strip_tags($forum->get_name())) .
'" ' . generate_email_messageid('forumng' . $forum->get_id()),
'List-Help: ' . $forum->get_url(\mod_forumng::PARAM_PLAIN),
'Message-ID: ' . generate_email_messageid('forumng_post' . $post->get_id()),
'X-Course-Id: ' . $forum->get_course_id(),
'X-Course-Name: '. format_string($forum->get_course()->shortname, true),
// Headers to help prevent auto-responders.
'Precedence: Bulk',
'X-Auto-Response-Suppress: All',
'Auto-Submitted: auto-generated',
];
if ($CFG->forumng_usebcc) {
// Use BCC to send all emails at once.
$emailcount += self::email_send_bcc(
$users, $from, $subject,
$html, $plaintext,
"post " . $post->get_id(),
$emailtype & 1, $emailtype & 4, $headers);
} else {
$headers[] = 'List-Unsubscribe-Post: List-Unsubscribe=One-Click';
// Loop through subscribers, sending mail to each one.
foreach ($users as $mailto) {
if (\mod_forumng::SUBSCRIPTION_FORCED != $forum->get_effective_subscription_option()) {
$link = "{$CFG->wwwroot}/mod/forumng/subscribe.php";
$link .= '?user=' . $mailto->id;
$usersubtype = $discussion->is_subscribed($mailto->id);
// Add correct unsubscribe params to target the subscription removal.
switch ($usersubtype) {
case \mod_forumng::PARTIALLY_SUBSCRIBED:
$link .= '&d=' . $discussion->get_id();
$link .= '&submitunsubscribe=y';
$link .= '&key=' . $forum->get_feed_key($discussion->get_group_id(), $mailto->id);
break;
case \mod_forumng::THIS_GROUP_SUBSCRIBED:
$link .= '&' . $forum->get_link_params(\mod_forumng::PARAM_PLAIN);
$link .= '&g=' . $discussion->get_group_id();
$link .= '&submitunsubscribe_thisgroup=y';
$link .= '&key=' . $forum->get_feed_key($discussion->get_group_id(), $mailto->id);
break;
default:
$link .= '&' . $forum->get_link_params(\mod_forumng::PARAM_PLAIN);
$link .= '&submitunsubscribe=y';
// For simplicity use no groups in other cases.
$link .= '&key=' . $forum->get_feed_key(\mod_forumng::NO_GROUPS, $mailto->id);
break;
}
// Add list headers: https://datatracker.ietf.org/doc/html/rfc8058.
$headers[99] = 'List-Unsubscribe: <' . $link . '>';
$from->customheaders = $headers;
}
// We separate in 2 case to improve performance.
if ($forum->get_can_post_anon() == mod_forumng::CANPOSTATON_NONMODERATOR ||
($forum->get_can_post_anon() == mod_forumng::CANPOSTANON_MODERATOR &&
$post->get_asmoderator() == mod_forumng::ASMODERATOR_ANON)) {
if (mod_forumng_utils::display_discussion_author_anonymously($post, $mailto->id)) {
$from = \core_user::get_noreply_user();
$from->customheaders = $headers;
}
$post->build_email($inreplyto, $subject1,
$plaintext1, $html1, $emailtype & 1,
$emailtype & 2, $emailtype & 4, $lang,
$timezone, false, false, ['mailto_userid' => $mailto->id]);
self::email_send($mailto, $from, $subject1, $plaintext1, $html1);
} else {
self::email_send($mailto, $from, $subject, $plaintext, $html);
}
$emailcount++;
}
}
$mailtime += microtime(true) - $innerbefore;
}
}
}
// Reset exception count; while some posts are
// successful, we'll keep trying to send them out.
$exceptioncount = 0;
} catch (Exception $e) {
mtrace(' Exception while sending post ' . $post->get_id());
mtrace($e->__toString());
$exceptioncount++;
if ($exceptioncount > 100) {
throw new moodle_exception('error_system', 'forumng', '',
'Too many post exceptions in a row, aborting');
}
}
$postcount++;
if (self::debug()) {
mtrace(", sent " . ($emailcount - $debugcount) .
" emails");
}
}
}
// Trace and log information.
$counts = "$postcount posts ($emailcount emails) to " .
count($subscribers) . " subscribers";
mtrace("sent $counts");
$innerbefore = microtime(true);
$params = array('other' => array('type' => 'sub', 'count' => $counts),
'context' => $forum->get_context());
$event = \mod_forumng\event\mail_sent::create($params);
$event->trigger();
$eventlogtime += microtime(true) - $innerbefore;
$totalemailcount += $emailcount;
}
self::add_list_times($listtimes, $list);
$totalpostcount += $list->get_post_count_so_far();
if (time() > $endafter) {
mtrace('Stopping (time limit reached).');
break;
}
}
$queryinfo = '';
if (!empty($PERF->dbqueries)) {
$queryinfo = ', ' . ($PERF->dbqueries - $beforequeries) .
' queries';
}
$totaltime = microtime(true) - $before;
mtrace("Email processing ($totalpostcount new posts, $totalemailcount new emails) " .
"complete, total time: " . sprintf('%.1Fs', $totaltime)) . $queryinfo;
self::show_time_with_percentage('Mail sending', $mailtime, $totaltime);
self::show_time_with_percentage('Getting subscribers', $getsubscriberstime, $totaltime);
self::show_time_with_percentage('Filtering subscribers', $filtersubscriberstime, $totaltime);
self::show_time_with_percentage('Discussion subscribers', $discussionsubscriberstime, $totaltime);
self::show_time_with_percentage('Building emails', $buildemailtime, $totaltime);
self::show_time_with_percentage('Logging events', $eventlogtime, $totaltime);
foreach ($listtimes as $key => $time) {
self::show_time_with_percentage($key, $time, $totaltime);
}
}
/**
* Adds time recording from a mod_forumng_mail_list object into an existing array of times,
* if necessary adding new entries into the array.
*
* @param array $listtimes Array of times (input-output parameter)
* @param mod_forumng_mail_list $list List with time data
*/
protected static function add_list_times(array &$listtimes, mod_forumng_mail_list $list) {
if ($listtimes === []) {
$listtimes = $list->get_times();
} else {
foreach ($list->get_times() as $key => $time) {
$listtimes[$key] += $time;
}
}
}
/**
* Utility function to trace out the proportion of time spent doing a thing.
*
* @param string $name Name of thing
* @param float $time Time in seconds
* @param float $totaltime Total time in seconds
*/
protected static function show_time_with_percentage($name, $time, $totaltime) {
// Hack total time so it doesn't divide by zero.
if ($totaltime < 0.1) {
$totaltime = 0.1;
}
mtrace(' ' . $name . ': ' . sprintf('%.1Fs', $time) . ' (' .
sprintf('%.1F', (100.0 * $time / $totaltime)) . '%)');
}
/**
* Shared logic that works out whether a particular subscriber receives a
* discussion or not.
* @param mod_forumng $forum Forum
* @param mod_forumng_discussion $discussion Discussion
* @param object $subscriber Subscriber
*/
private static function subscriber_receives_discussion($forum, $discussion, $subscriber) {
// Did they subscribe specifically to this discussion?
$explicitsubscribed = array_key_exists(
$discussion->get_id(), $subscriber->discussionids);
// Did they subscribe to the group this discussion belongs to
$explicitsubscribedtogroup = in_array($discussion->get_group_id(),
$subscriber->groupids);
$groupid = $discussion->get_group_id();
$visiblegroups = $forum->get_group_mode() == VISIBLEGROUPS;
// Conditions for each subscriber to get this discussion
$result =
// 1. Subscribed to whole forum, or specifically to
// this discussion, or specifically to this group
($subscriber->wholeforum || $explicitsubscribed ||
$explicitsubscribedtogroup) &&
// 2. The discussion has no group id, or they
// belong to the group, or they can access all groups,
// or it's visible-groups
(!$groupid || $subscriber->accessallgroups || $visiblegroups ||
array_key_exists($groupid, $subscriber->groups)) &&
// 3. Forum type allows user to view discussion
$forum->get_type()->can_view_discussion(
$discussion, $subscriber->id);
return $result;
}
public static function email_digest() {
global $PERF;
mod_forumng_mail_list::reset_static_cache();
// Build current digest.
mtrace("Beginning forum digest processing...");
if (!empty($PERF->dbqueries)) {
$beforequeries = $PERF->dbqueries;
}
$before = microtime(true);
mtrace('Initial query: ', '');
$list = new mod_forumng_digest_list(true);
mtrace(round(microtime(true)-$before, 1) .'s');
$userdigests = array();
$oldcourse = null;
// Forum loop.
while ($list->next_forum($forum, $cm, $context, $course)) {
self::debug("DEBUG: Forum " . $forum->get_name() .
" on course {$course->shortname} " .
"(cmid {$cm->id} contextid {$context->id})");
if (!$oldcourse || ($course->id != $oldcourse->id)) {
// Finish off and clear users.
if ($oldcourse) {
self::digest_finish_course($oldcourse, $userdigests);
}
// Set up new course details.
// Note: This code is a bit sketchy; borrowed from cron_setup_user.
$PAGE = new moodle_page();
$PAGE->set_course($course);
$oldcourse = clone($course);
}
// Count posts just for logging.
$postcount = 0;
// Get subscribers to forum.
$subscribers = $forum->get_subscribers();
self::debug("DEBUG: Subscribers before filter " . count($subscribers), '');
self::email_filter_subscribers($course, $cm, $forum, $subscribers, true);
self::debug(", after " . count($subscribers));
if (count($subscribers)==0) {
continue;
}
while ($list->next_discussion($discussion)) {
self::debug("DEBUG: Discussion " . $discussion->get_subject() .
' (' . $discussion->get_id() . ')');
// Evaluate list of users based on this discussion (which holds
// group info). Organise list by language, timezone and email
// type.
$discussionusers = array();
foreach ($subscribers as $subscriber) {
if (self::subscriber_receives_discussion(
$forum, $discussion, $subscriber)) {
$discussionusers[$subscriber->id] = $subscriber;
}
}
while ($list->next_post($post, $inreplyto)) {
// Loop through all digest users.
foreach ($discussionusers as $user) {
// Add to digest. (This will set up the user's
// digest if they don't already have one).
self::digest_add_post_for_user($user, $userdigests,
$post, $inreplyto, $discussion, $forum, $cm,
$course, $context);
}
$postcount++;
}
}
}
if ($oldcourse) {
self::digest_finish_course($oldcourse, $userdigests);
}
$queryinfo = '';
if (!empty($PERF->dbqueries)) {
$queryinfo = ', ' . ($PERF->dbqueries - $beforequeries) .
' queries';
}
$totalpostcount = $list->get_post_count_so_far();
mtrace("Digest processing ($totalpostcount new digest posts) complete, total: "
. round(microtime(true)-$before, 1) . 's' . $queryinfo);
}
/**
* Called at end of processing a single forum. Updates the digest records
* to add footer information for each user who had messages from the forum.
* @param array $userdigests Array of userid => digest info
* @param mod_forumng $forum
* @param object $cm
*/
private static function digest_end_forum(&$userdigests, $forum, $cm) {
global $CFG;
$canunsubscribe = mod_forumng::SUBSCRIPTION_FORCED
!= $forum->get_effective_subscription_option();
foreach ($userdigests as $digest) {
// If there was a message from this forum...
if ($digest->forumngid === $forum->get_id()) {
$digest->html .= "\n<div class='forumng-email-unsubscribe'><small>";
$digest->text .= "\n";
if ($canunsubscribe) {
$digest->html .=
"<a href='$CFG->wwwroot/mod/forum/subscribe.php?" .
$forum->get_link_params(mod_forumng::PARAM_HTML) . "'>" .
get_string("unsubscribe", "forumng") . "</a>";
$digest->text .= get_string("unsubscribe", "forumng") .
": $CFG->wwwroot/mod/forum/subscribe.php" .
$forum->get_link_params(mod_forumng::PARAM_PLAIN);
} else {
$digest->html .= get_string("everyoneissubscribed", "forumng");
$digest->text .= get_string("everyoneissubscribed", "forumng");
}
$digest->html .= '</small></div>';
$digest->text .= "\n\n";
}
}
}
/**
* Updates the in-memory digest records to add a new post to the given
* user's digests.
* @param object $user User object (must include special ->emailtype, etc)
* @param array $userdigests Array of user id => digest information object
* @param mod_forumng_post $post Post object
* @param mod_forumng_post $inreplyto Parent post
* @param mod_forumng_discussion $discussion Discus
* @param mod_forumng $forum
* @param object $cm
* @param object $course
* @param object $context
*/
private static function digest_add_post_for_user(&$user, &$userdigests,
&$post, &$inreplyto, &$discussion, &$forum, &$cm, &$course, &$context) {
global $CFG;
// Set up digest for user if required
if (!array_key_exists($user->id, $userdigests)) {
$userdigests[$user->id] = new StdClass;
$userdigests[$user->id]->discussionid = -1; // So we do header next
$userdigests[$user->id]->user = $user;
$userdigests[$user->id]->forumngid = -1;
// Get header text
$headerdata = new stdClass();
$headerdata->sitename = format_string($course->fullname, true);
$headerdata->userprefs = $CFG->wwwroot . '/user/edit.php?id=' .
$user->id . '&course=' . $course->id;
$userdigests[$user->id]->text = get_string('digestmailheader',
'forumng', $headerdata) . "\n\n";
// Get header HTML
$html = "<body id='forumng-email'>\n";
$headerdata->userprefs = '<a target="_blank" href="' .
$headerdata->userprefs . '">' .
get_string('digestmailprefs', 'forumng') . '</a>';
$html .= '<div class="forumng-emailheader"><p>' .
get_string('digestmailheader', 'forumng', $headerdata).
'</p></div><hr size="1" noshade="noshade" />';
$userdigests[$user->id]->html = $html;
// Get email subject
$userdigests[$user->id]->subject = get_string('digestmailsubject',
'forumng', format_string($course->shortname, true));
}
// New forum?
if ($userdigests[$user->id]->forumngid != $forum->get_id()) {
$userdigests[$user->id]->forumngid = $forum->get_id();
}
// Is this a new discussion?
if ($userdigests[$user->id]->discussionid != $discussion->get_id()) {
$strforums = get_string('forums', 'forumng');
// Per-discussion header (text mode)
$text = "\n \n";
$text .= '=====================================================================';
$text .= "\n \n";
$text .= "$course->shortname -> $strforums -> " .
format_string($forum->get_name(), true);
if ($discussion->get_subject(false) !== $forum->get_name()) {
$text .= " -> " . format_string($discussion->get_subject(false), true);
}
$text .= "\n";
// HTML mode
$html = '<hr size="1" noshade="noshade" />';
$html .= "<div class='forumng-breadcrumbs'>" .
"<a target='_blank' href='$CFG->wwwroot/course/view.php?" .
"id=$course->id'>$course->shortname</a> -> " .
"<a target='_blank' href='$CFG->wwwroot/mod/forumng/index.php?" .
"id=$course->id'>$strforums</a> -> " .
"<a target='_blank' href='$CFG->wwwroot/mod/forumng/view.php?" .
$forum->get_link_params(mod_forumng::PARAM_HTML) . "'>" .
format_string($forum->get_name(), true)."</a>";
if ($discussion->get_subject(false) !== $forum->get_name()) {
$html .= " -> <a target='_blank' href='$CFG->wwwroot/mod/forumng/discuss.php?" .
$discussion->get_link_params(mod_forumng::PARAM_HTML) . "'>" .
format_string($discussion->get_subject(false), true) . "</a>";
}
$html .= '</div>';
$userdigests[$user->id]->text .= $text;
$userdigests[$user->id]->html .= $html;
$userdigests[$user->id]->discussionid = $discussion->get_id();
}
// Get both plaintext and html versions (and subject).
// The html version will be blank if set to
// plain text mode.
$post->build_email($inreplyto, $subject,
$text, $html, $user->emailtype & 1,
$user->emailtype & 2, $user->emailtype & 4,
$user->lang, $user->timezone, true);
$userdigests[$user->id]->text .= $text;
$userdigests[$user->id]->html .= $html;
}
/**
* Actually sends out digest emails to all users (who got something to say)
* because we are moving on to process the next course.
*/
private static function digest_finish_course(&$course, &$userdigests) {
global $CFG;
$from = \core_user::get_noreply_user();
// Headers to match core forum digest... how to support list unsubscribing as not a single list?
$from->customheaders = [
"Precedence: Bulk",
'X-Auto-Response-Suppress: All',
'Auto-Submitted: auto-generated',
];
// Loop around all digests and send them out
foreach ($userdigests as $digest) {
self::email_send($digest->user, $from,
$digest->subject, $digest->text, $digest->html);
}
// Trace and log information
$counts = count($userdigests) . ' digests';
mtrace("Course ".$course->shortname . ": sent $counts");
$params = array('other' => array('type' => 'digest', 'count' => $counts),
'context' => context_course::instance($course->id));
$event = \mod_forumng\event\mail_sent::create($params);
$event->trigger();
// Clear users ready for new course
$userdigests = array();
}
/**
* Filters a list of subscribers to remove those who can't receive email
* etc., and adds extra information to each one.
* @param object $course Course
* @param object $cm Course-module
* @param array $subscribers List of subscribers
* @param bool $digest True if we want digest recipients (only) instead of
* non-digest recipients
*/
private static function email_filter_subscribers($course, $cm, $forum,
&$subscribers, $digest=false) {
foreach ($subscribers as $subscriber) {
// Exclude anyone who has mail disabled for various reasons,
// or is/is not on digest.
// Note that the mail checks here duplicate checks in
// email_to_user; this probably makes it slightly more
// efficient, but is really there because if bcc is enabled
// we don't go through email_to_user at all.
if ($subscriber->emailstop || $subscriber->deleted ||
$subscriber->auth=='nologin' ||
(($digest && !$subscriber->maildigest) ||
(!$digest && $subscriber->maildigest)) ||
over_bounce_threshold($subscriber)) {
unset($subscribers[$subscriber->id]);
continue;
}
// Add information about groups for this user.
$subscriber->groups = groups_get_all_groups(
$course->id, $subscriber->id, $cm->groupingid, 'g.id');
$subscriber->groups = $subscriber->groups
? $subscriber->groups : array();
// Track whether users are allowed to view full names
$subscriber->viewfullnames = has_capability(
'moodle/site:viewfullnames', $forum->get_context(),
$subscriber->id);
$subscriber->canreply = has_capability(
'mod/forumng:replypost', $forum->get_context(),
$subscriber->id);
// Note I don't think the Reply capability is sufficient
// check here, could be restricted by forum type. Maybe it
// will do for now.
// Categorise subscriber by the type of email. There are
// eight types as determined by the two flags above, plus
// HTML vs standard email.
$subscriber->emailtype =
($subscriber->viewfullnames ? 4 : 0) +
($subscriber->canreply ? 2 : 0) +
($subscriber->mailformat ? 1 : 0);
}
}
/**
* Sends an email. (Wrapper around email_to_user.)
* @param object $to User who receives email
* @param mixed $from User or string who sent email
* @param string $subject Subject line
* @param string $text Text of email
* @param string $html HTML of email or '' if plaintext only
*/
private static function email_send($to, $from, $subject, $text, $html) {
global $CFG;
if (self::DEBUG_VIEW_EMAILS) {
print "<div style='margin:4px; border:1px solid blue; padding:4px;'>";
print "<h3>Email sent</h3>";
print "<ul><li>From: <strong>" . (is_object($from) ? $from->email : $from) .
"</strong></li>";
print "<li>To: <strong>$to->email</strong></li>";
print "<li>Subject: <strong>" . htmlspecialchars($subject) .
"</strong></li></ul>";
print $html;
print "<pre style='border-top: 1px solid blue; padding-top: 4px; margin-top:4px;'>";
print htmlspecialchars($text);
print "</pre></div>";
return;
}
email_to_user($to, $from, $subject, $text, $html, '', '',
$CFG->forumng_replytouser);
}
/**
* Sends an email to lots of people using BCC.
* @param array $targets List of target user objects (email, name fields
* required)
* @param mixed $from User or string who sent email
* @param string $subject Subject of email
* @param string $html HTML version of email (blank if none)
* @param string $text Plain text version of email
* @param string $showerrortext If set, mtraces errors and includes this
* extra string about where the error was.
* @param bool $ishtml If true, email is in HTML format
* @param bool $viewfullnames If true, these recipients have access to
* see the full name
* @param array $headers Custom headers to send in the mail (must not be user specific).
* @return int Number of emails sent
*/
private static function email_send_bcc($targets, $from, $subject, $html, $text,
$showerrortext, $ishtml, $viewfullnames, array $headers = []) {
if (self::DEBUG_VIEW_EMAILS) {
print "<div style='border:1px solid blue; padding:4px;'>";
print "<h3>Bulk email sent</h3>";
print "<ul><li>To: ";
$first = true;
foreach ($targets as $target) {
if ($first) {
$first = false;
} else {
print ', ';
}
print "<strong>$target->email</strong>";
}
print "</li><li>Subject: <strong>" . htmlspecialchars($subject) .
"</strong></li>";
print $html;
print "<pre style='border-top: 1px solid blue; padding-top: 4px;'>";
print htmlspecialchars($text);
print "</pre></div>";
return;
}
global $CFG;
$emailcount = 0;
// Loop through in batches of specified size
$copy = array();
foreach ($targets as $key => $target) {
$copy[$key] = $target;
}
while (count($copy)>0) {
$batch = array_splice($copy, 0,
$CFG->forumng_usebcc);
// Prepare email
$mail = get_mailer();
// Trim subject length (not sure why but
// email_to_user does); note that I did it more
// aggressively due to use of textlib.
$mail->Subject = core_text::substr($subject, 0, 200);
// From support user
static $supportuser;
if (!$supportuser) {
$supportuser = core_user::get_support_user();
}
$mail->Sender = $supportuser->email;
// Set the From details similar to email_to_user
if ($CFG->forumng_replytouser &&
$from->maildisplay) {
$mail->From = $from->email;
$mail->FromName = fullname($from, $viewfullnames);
} else {
$mail->From = $CFG->noreplyaddress;
$mail->FromName = fullname($from, $viewfullnames);
}
$mail->Subject = $subject;
if ($ishtml) {
$mail->IsHTML(true);
$mail->Encoding = 'quoted-printable';
$mail->Body = $html;
$mail->AltBody = "\n$text\n";
} else {
$mail->IsHTML(false);
$mail->Body = "\n$text\n";
}
foreach ($batch as $user) {
$mail->AddBCC($user->email);
}
foreach ($headers as $customheader) {
$mail->addCustomHeader($customheader);
}
if (PHPUNIT_TEST) {
// Need a To for unit tests.
$mail->addAddress($CFG->noreplyaddress);
}
$emailcount++;
if (!$mail->Send()) {
$users = '';
foreach ($batch as $user) {
if ($users) {
$users.=', ';
}
$users .= $user->id;
}
if ($showerrortext) {
mtrace('Error sending email "'. $subject .
'": "'. $mail->ErrorInfo . '" (' . $showerrortext .
'). Users affected: ' . $users);
}
} else {
// Mail send successful; log all users
foreach ($batch as $user) {
// Note this log entry is in the same format as the
// main mail function
$params = array('other' => array('username' => $user->username, 'subject' => $subject, 'type' => ''),
'context' => context_system::instance(), 'relateduserid' => $user->id);
$event = \mod_forumng\event\mail_sent::create($params);
$event->trigger();
}
}
}
return $emailcount;
}
/**
* Checks whether current hour is between two specified hours.
* @param int $starthour Hour to start running at (inclusive) e.g. 23
* @param int $stophour Hour to stop running at (exclusive) e.g. 4
* @return boolean True if it should currently run
*/
public static function is_between_hours($starthour, $stophour) {
$hour = (int)date('G');
if ($starthour < $stophour) {
// Hours are in numerical order e.g. 0-6
return ($hour >= $starthour && $hour < $stophour);