-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
7978 lines (6829 loc) · 299 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/>.
/**
* @package mod_cybrary
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** Include required files */
require_once(__DIR__ . '/deprecatedlib.php');
require_once($CFG->libdir.'/filelib.php');
require_once("$CFG->libdir/resourcelib.php");
require_once($CFG->libdir.'/eventslib.php');
require_once('locallib.php');
/// CONSTANTS ///////////////////////////////////////////////////////////
define('CYBRARY_MODE_FLATOLDEST', 1);
define('CYBRARY_MODE_FLATNEWEST', -1);
define('CYBRARY_MODE_THREADED', 2);
define('CYBRARY_MODE_NESTED', 3);
define('CYBRARY_CHOOSESUBSCRIBE', 0);
define('CYBRARY_FORCESUBSCRIBE', 1);
define('CYBRARY_INITIALSUBSCRIBE', 2);
define('CYBRARY_DISALLOWSUBSCRIBE',3);
/**
* CYBRARY_TRACKING_OFF - Tracking is not available for this cybrary.
*/
define('CYBRARY_TRACKING_OFF', 0);
/**
* CYBRARY_TRACKING_OPTIONAL - Tracking is based on user preference.
*/
define('CYBRARY_TRACKING_OPTIONAL', 1);
/**
* CYBRARY_TRACKING_FORCED - Tracking is on, regardless of user setting.
* Treated as CYBRARY_TRACKING_OPTIONAL if $CFG->cybrary_allowforcedreadtracking is off.
*/
define('CYBRARY_TRACKING_FORCED', 2);
define('CYBRARY_MAILED_PENDING', 0);
define('CYBRARY_MAILED_SUCCESS', 1);
define('CYBRARY_MAILED_ERROR', 2);
if (!defined('CYBRARY_CRON_USER_CACHE')) {
/** Defines how many full user records are cached in cybrary cron. */
define('CYBRARY_CRON_USER_CACHE', 5000);
}
/**
* CYBRARY_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
*/
define('CYBRARY_POSTS_ALL_USER_GROUPS', -2);
/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
/**
* 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 $cybrary add cybrary instance
* @param mod_cybrary_mod_form $mform
* @return int intance id
*/
function cybrary_add_instance($cybrary, $mform = null) {
global $CFG, $DB;
$cybrary->timemodified = time();
if (empty($cybrary->assessed)) {
$cybrary->assessed = 0;
}
if (empty($cybrary->ratingtime) or empty($cybrary->assessed)) {
$cybrary->assesstimestart = 0;
$cybrary->assesstimefinish = 0;
}
$parameters = array();
for ($i=0; $i < 100; $i++) {
$parameter = "parameter_$i";
$variable = "variable_$i";
if (empty($cybrary->$parameter) or empty($cybrary->$variable)) {
continue;
}
$parameters[$cybrary->$parameter] = $cybrary->$variable;
}
$cybrary->parameters = serialize($parameters);
$displayoptions = array();
if ($cybrary->display == RESOURCELIB_DISPLAY_POPUP) {
$displayoptions['popupwidth'] = $cybrary->popupwidth;
$displayoptions['popupheight'] = $cybrary->popupheight;
}
if (in_array($cybrary->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) {
$displayoptions['printintro'] = (int)!empty($cybrary->printintro);
}
$cybrary->displayoptions = serialize($displayoptions);
$cybrary->externalurl = url_fix_submitted_url($cybrary->externalurl);
$cybrary->id = $DB->insert_record('cybrary', $cybrary);
$modcontext = context_module::instance($cybrary->coursemodule);
if ($cybrary->type == 'single') { // Create related discussion.
$discussion = new stdClass();
$discussion->course = $cybrary->course;
$discussion->cybrary = $cybrary->id;
$discussion->name = $cybrary->name;
$discussion->assessed = $cybrary->assessed;
$discussion->message = $cybrary->intro;
$discussion->messageformat = $cybrary->introformat;
$discussion->messagetrust = trusttext_trusted(context_course::instance($cybrary->course));
$discussion->mailnow = false;
$discussion->groupid = -1;
$message = '';
$discussion->id = cybrary_add_discussion($discussion, null, $message);
if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
// Ugly hack - we need to copy the files somehow.
$discussion = $DB->get_record('cybrary_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
$post = $DB->get_record('cybrary_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
$options = array('subdirs'=>true); // Use the same options as intro field!
$post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_cybrary', 'post', $post->id, $options, $post->message);
$DB->set_field('cybrary_posts', 'message', $post->message, array('id'=>$post->id));
}
}
cybrary_grade_item_update($cybrary);
return $cybrary->id;
}
/**
* Handle changes following the creation of a cybrary instance.
* This function is typically called by the course_module_created observer.
*
* @param object $context the cybrary context
* @param stdClass $cybrary The cybrary object
* @return void
*/
function cybrary_instance_created($context, $cybrary) {
if ($cybrary->forcesubscribe == CYBRARY_INITIALSUBSCRIBE) {
$users = \mod_cybrary\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
foreach ($users as $user) {
\mod_cybrary\subscriptions::subscribe_user($user->id, $cybrary, $context);
}
}
}
/**
* 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.
*
* @global object
* @param object $cybrary cybrary instance (with magic quotes)
* @return bool success
*/
function cybrary_update_instance($cybrary, $mform) {
global $DB, $OUTPUT, $USER;
$cybrary->timemodified = time();
$cybrary->id = $cybrary->instance;
if (empty($cybrary->assessed)) {
$cybrary->assessed = 0;
}
if (empty($cybrary->ratingtime) or empty($cybrary->assessed)) {
$cybrary->assesstimestart = 0;
$cybrary->assesstimefinish = 0;
}
$oldcybrary = $DB->get_record('cybrary', array('id'=>$cybrary->id));
// MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire cybrary
// if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
// for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
if (($oldcybrary->assessed<>$cybrary->assessed) or ($oldcybrary->scale<>$cybrary->scale)) {
cybrary_update_grades($cybrary); // recalculate grades for the cybrary
}
if ($cybrary->type == 'single') { // Update related discussion and post.
$discussions = $DB->get_records('cybrary_discussions', array('cybrary'=>$cybrary->id), 'timemodified ASC');
if (!empty($discussions)) {
if (count($discussions) > 1) {
echo $OUTPUT->notification(get_string('warnformorepost', 'cybrary'));
}
$discussion = array_pop($discussions);
} else {
// try to recover by creating initial discussion - MDL-16262
$discussion = new stdClass();
$discussion->course = $cybrary->course;
$discussion->cybrary = $cybrary->id;
$discussion->name = $cybrary->name;
$discussion->assessed = $cybrary->assessed;
$discussion->message = $cybrary->intro;
$discussion->messageformat = $cybrary->introformat;
$discussion->messagetrust = true;
$discussion->mailnow = false;
$discussion->groupid = -1;
$message = '';
cybrary_add_discussion($discussion, null, $message);
if (! $discussion = $DB->get_record('cybrary_discussions', array('cybrary'=>$cybrary->id))) {
print_error('cannotadd', 'cybrary');
}
}
if (! $post = $DB->get_record('cybrary_posts', array('id'=>$discussion->firstpost))) {
print_error('cannotfindfirstpost', 'cybrary');
}
$cm = get_coursemodule_from_instance('cybrary', $cybrary->id);
$modcontext = context_module::instance($cm->id, MUST_EXIST);
$post = $DB->get_record('cybrary_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
$post->subject = $cybrary->name;
$post->message = $cybrary->intro;
$post->messageformat = $cybrary->introformat;
$post->messagetrust = trusttext_trusted($modcontext);
$post->modified = $cybrary->timemodified;
$post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
// Ugly hack - we need to copy the files somehow.
$options = array('subdirs'=>true); // Use the same options as intro field!
$post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_cybrary', 'post', $post->id, $options, $post->message);
}
$DB->update_record('cybrary_posts', $post);
$discussion->name = $cybrary->name;
$DB->update_record('cybrary_discussions', $discussion);
}
$DB->update_record('cybrary', $cybrary);
$modcontext = context_module::instance($cybrary->coursemodule);
if (($cybrary->forcesubscribe == CYBRARY_INITIALSUBSCRIBE) && ($oldcybrary->forcesubscribe <> $cybrary->forcesubscribe)) {
$users = \mod_cybrary\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
foreach ($users as $user) {
\mod_cybrary\subscriptions::subscribe_user($user->id, $cybrary, $modcontext);
}
}
cybrary_grade_item_update($cybrary);
return true;
}
/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @global object
* @param int $id cybrary instance id
* @return bool success
*/
function cybrary_delete_instance($id) {
global $DB;
if (!$cybrary = $DB->get_record('cybrary', array('id'=>$id))) {
return false;
}
if (!$cm = get_coursemodule_from_instance('cybrary', $cybrary->id)) {
return false;
}
if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
return false;
}
$context = context_module::instance($cm->id);
// now get rid of all files
$fs = get_file_storage();
$fs->delete_area_files($context->id);
$result = true;
// Delete digest and subscription preferences.
$DB->delete_records('cybrary_digests', array('cybrary' => $cybrary->id));
$DB->delete_records('cybrary_subscriptions', array('cybrary'=>$cybrary->id));
$DB->delete_records('cybrary_discussion_subs', array('cybrary' => $cybrary->id));
if ($discussions = $DB->get_records('cybrary_discussions', array('cybrary'=>$cybrary->id))) {
foreach ($discussions as $discussion) {
if (!cybrary_delete_discussion($discussion, true, $course, $cm, $cybrary)) {
$result = false;
}
}
}
cybrary_tp_delete_read_records(-1, -1, -1, $cybrary->id);
if (!$DB->delete_records('cybrary', array('id'=>$cybrary->id))) {
$result = false;
}
cybrary_grade_item_delete($cybrary);
return $result;
}
/**
* Indicates API features that the cybrary supports.
*
* @uses FEATURE_GROUPS
* @uses FEATURE_GROUPINGS
* @uses FEATURE_MOD_INTRO
* @uses FEATURE_COMPLETION_TRACKS_VIEWS
* @uses FEATURE_COMPLETION_HAS_RULES
* @uses FEATURE_GRADE_HAS_GRADE
* @uses FEATURE_GRADE_OUTCOMES
* @param string $feature
* @return mixed True if yes (some features may use other values)
*/
function cybrary_supports($feature) {
switch($feature) {
case FEATURE_GROUPS: return true;
case FEATURE_GROUPINGS: return true;
case FEATURE_MOD_INTRO: return true;
case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
case FEATURE_COMPLETION_HAS_RULES: return true;
case FEATURE_GRADE_HAS_GRADE: return true;
case FEATURE_GRADE_OUTCOMES: return true;
case FEATURE_RATE: return true;
case FEATURE_BACKUP_MOODLE2: return true;
case FEATURE_SHOW_DESCRIPTION: return true;
case FEATURE_PLAGIARISM: return true;
default: return null;
}
}
/**
* Obtains the automatic completion state for this cybrary based on any conditions
* in cybrary settings.
*
* @global object
* @global object
* @param object $course Course
* @param object $cm Course-module
* @param int $userid User ID
* @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
* @return bool True if completed, false if not. (If no conditions, then return
* value depends on comparison type)
*/
function cybrary_get_completion_state($course,$cm,$userid,$type) {
global $CFG,$DB;
// Get cybrary details
if (!($cybrary=$DB->get_record('cybrary',array('id'=>$cm->instance)))) {
throw new Exception("Can't find cybrary {$cm->instance}");
}
$result=$type; // Default return value
$postcountparams=array('userid'=>$userid,'cybraryid'=>$cybrary->id);
$postcountsql="
SELECT
COUNT(1)
FROM
{cybrary_posts} fp
INNER JOIN {cybrary_discussions} fd ON fp.discussion=fd.id
WHERE
fp.userid=:userid AND fd.cybrary=:cybraryid";
if ($cybrary->completiondiscussions) {
$value = $cybrary->completiondiscussions <=
$DB->count_records('cybrary_discussions',array('cybrary'=>$cybrary->id,'userid'=>$userid));
if ($type == COMPLETION_AND) {
$result = $result && $value;
} else {
$result = $result || $value;
}
}
if ($cybrary->completionreplies) {
$value = $cybrary->completionreplies <=
$DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
if ($type==COMPLETION_AND) {
$result = $result && $value;
} else {
$result = $result || $value;
}
}
if ($cybrary->completionposts) {
$value = $cybrary->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
if ($type == COMPLETION_AND) {
$result = $result && $value;
} else {
$result = $result || $value;
}
}
return $result;
}
/**
* Create a message-id string to use in the custom headers of cybrary notification emails
*
* message-id is used by email clients to identify emails and to nest conversations
*
* @param int $postid The ID of the cybrary post we are notifying the user about
* @param int $usertoid The ID of the user being notified
* @param string $hostname The server's hostname
* @return string A unique message-id
*/
function cybrary_get_email_message_id($postid, $usertoid, $hostname) {
return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
}
/**
* Removes properties from user record that are not necessary
* for sending post notifications.
* @param stdClass $user
* @return void, $user parameter is modified
*/
function cybrary_cron_minimise_user_record(stdClass $user) {
// We store large amount of users in one huge array,
// make sure we do not store info there we do not actually need
// in mail generation code or messaging.
unset($user->institution);
unset($user->department);
unset($user->address);
unset($user->city);
unset($user->url);
unset($user->currentlogin);
unset($user->description);
unset($user->descriptionformat);
}
/**
* Function to be run periodically according to the scheduled task.
*
* Finds all posts that have yet to be mailed out, and mails them
* out to all subscribers as well as other maintance tasks.
*
* NOTE: Since 2.7.2 this function is run by scheduled task rather
* than standard cron.
*
* @todo MDL-44734 The function will be split up into seperate tasks.
*/
function cybrary_cron() {
global $CFG, $USER, $DB, $PAGE;
$site = get_site();
// The main renderers.
$htmlout = $PAGE->get_renderer('mod_cybrary', 'email', 'htmlemail');
$textout = $PAGE->get_renderer('mod_cybrary', 'email', 'textemail');
$htmldigestfullout = $PAGE->get_renderer('mod_cybrary', 'emaildigestfull', 'htmlemail');
$textdigestfullout = $PAGE->get_renderer('mod_cybrary', 'emaildigestfull', 'textemail');
$htmldigestbasicout = $PAGE->get_renderer('mod_cybrary', 'emaildigestbasic', 'htmlemail');
$textdigestbasicout = $PAGE->get_renderer('mod_cybrary', 'emaildigestbasic', 'textemail');
// All users that are subscribed to any post that needs sending,
// please increase $CFG->extramemorylimit on large sites that
// send notifications to a large number of users.
$users = array();
$userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
// Status arrays.
$mailcount = array();
$errorcount = array();
// caches
$discussions = array();
$cybraries = array();
$courses = array();
$coursemodules = array();
$subscribedusers = array();
$messageinboundhandlers = array();
// Posts older than 2 days will not be mailed. This is to avoid the problem where
// cron has not been running for a long time, and then suddenly people are flooded
// with mail from the past few weeks or months
$timenow = time();
$endtime = $timenow - $CFG->maxeditingtime;
$starttime = $endtime - 48 * 3600; // Two days earlier
// Get the list of cybrary subscriptions for per-user per-cybrary maildigest settings.
$digestsset = $DB->get_recordset('cybrary_digests', null, '', 'id, userid, cybrary, maildigest');
$digests = array();
foreach ($digestsset as $thisrow) {
if (!isset($digests[$thisrow->cybrary])) {
$digests[$thisrow->cybrary] = array();
}
$digests[$thisrow->cybrary][$thisrow->userid] = $thisrow->maildigest;
}
$digestsset->close();
// Create the generic messageinboundgenerator.
$messageinboundgenerator = new \core\message\inbound\address_manager();
$messageinboundgenerator->set_handler('\mod_cybrary\message\inbound\reply_handler');
if ($posts = cybrary_get_unmailed_posts($starttime, $endtime, $timenow)) {
// Mark them all now as being mailed. It's unlikely but possible there
// might be an error later so that a post is NOT actually mailed out,
// but since mail isn't crucial, we can accept this risk. Doing it now
// prevents the risk of duplicated mails, which is a worse problem.
if (!cybrary_mark_old_posts_as_mailed($endtime)) {
mtrace('Errors occurred while trying to mark some posts as being mailed.');
return false; // Don't continue trying to mail them, in case we are in a cron loop
}
// checking post validity, and adding users to loop through later
foreach ($posts as $pid => $post) {
$discussionid = $post->discussion;
if (!isset($discussions[$discussionid])) {
if ($discussion = $DB->get_record('cybrary_discussions', array('id'=> $post->discussion))) {
$discussions[$discussionid] = $discussion;
\mod_cybrary\subscriptions::fill_subscription_cache($discussion->cybrary);
\mod_cybrary\subscriptions::fill_discussion_subscription_cache($discussion->cybrary);
} else {
mtrace('Could not find discussion ' . $discussionid);
unset($posts[$pid]);
continue;
}
}
$cybraryid = $discussions[$discussionid]->cybrary;
if (!isset($cybraries[$cybraryid])) {
if ($cybrary = $DB->get_record('cybrary', array('id' => $cybraryid))) {
$cybraries[$cybraryid] = $cybrary;
} else {
mtrace('Could not find cybrary '.$cybraryid);
unset($posts[$pid]);
continue;
}
}
$courseid = $cybraries[$cybraryid]->course;
if (!isset($courses[$courseid])) {
if ($course = $DB->get_record('course', array('id' => $courseid))) {
$courses[$courseid] = $course;
} else {
mtrace('Could not find course '.$courseid);
unset($posts[$pid]);
continue;
}
}
if (!isset($coursemodules[$cybraryid])) {
if ($cm = get_coursemodule_from_instance('cybrary', $cybraryid, $courseid)) {
$coursemodules[$cybraryid] = $cm;
} else {
mtrace('Could not find course module for cybrary '.$cybraryid);
unset($posts[$pid]);
continue;
}
}
// Save the Inbound Message datakey here to reduce DB queries later.
$messageinboundgenerator->set_data($pid);
$messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
// Caching subscribed users of each cybrary.
if (!isset($subscribedusers[$cybraryid])) {
$modcontext = context_module::instance($coursemodules[$cybraryid]->id);
if ($subusers = \mod_cybrary\subscriptions::fetch_subscribed_users($cybraries[$cybraryid], 0, $modcontext, 'u.*', true)) {
foreach ($subusers as $postuser) {
// this user is subscribed to this cybrary
$subscribedusers[$cybraryid][$postuser->id] = $postuser->id;
$userscount++;
if ($userscount > CYBRARY_CRON_USER_CACHE) {
// Store minimal user info.
$minuser = new stdClass();
$minuser->id = $postuser->id;
$users[$postuser->id] = $minuser;
} else {
// Cache full user record.
cybrary_cron_minimise_user_record($postuser);
$users[$postuser->id] = $postuser;
}
}
// Release memory.
unset($subusers);
unset($postuser);
}
}
$mailcount[$pid] = 0;
$errorcount[$pid] = 0;
}
}
if ($users && $posts) {
$urlinfo = parse_url($CFG->wwwroot);
$hostname = $urlinfo['host'];
foreach ($users as $userto) {
// Terminate if processing of any account takes longer than 2 minutes.
core_php_time_limit::raise(120);
mtrace('Processing user ' . $userto->id);
// Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
if (isset($userto->username)) {
$userto = clone($userto);
} else {
$userto = $DB->get_record('user', array('id' => $userto->id));
cybrary_cron_minimise_user_record($userto);
}
$userto->viewfullnames = array();
$userto->canpost = array();
$userto->markposts = array();
// Setup this user so that the capabilities are cached, and environment matches receiving user.
cron_setup_user($userto);
// Reset the caches.
foreach ($coursemodules as $cybraryid => $unused) {
$coursemodules[$cybraryid]->cache = new stdClass();
$coursemodules[$cybraryid]->cache->caps = array();
unset($coursemodules[$cybraryid]->uservisible);
}
foreach ($posts as $pid => $post) {
$discussion = $discussions[$post->discussion];
$cybrary = $cybraries[$discussion->cybrary];
$course = $courses[$cybrary->course];
$cm =& $coursemodules[$cybrary->id];
// Do some checks to see if we can bail out now.
// Only active enrolled users are in the list of subscribers.
// This does not necessarily mean that the user is subscribed to the cybrary or to the discussion though.
if (!isset($subscribedusers[$cybrary->id][$userto->id])) {
// The user does not subscribe to this cybrary.
continue;
}
if (!\mod_cybrary\subscriptions::is_subscribed($userto->id, $cybrary, $post->discussion, $coursemodules[$cybrary->id])) {
// The user does not subscribe to this cybrary, or to this specific discussion.
continue;
}
if ($subscriptiontime = \mod_cybrary\subscriptions::fetch_discussion_subscription($cybrary->id, $userto->id)) {
// Skip posts if the user subscribed to the discussion after it was created.
if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
continue;
}
}
// Don't send email if the cybrary is Q&A and the user has not posted.
// Initial topics are still mailed.
if ($cybrary->type == 'qanda' && !cybrary_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
continue;
}
// Get info about the sending user.
if (array_key_exists($post->userid, $users)) {
// We might know the user already.
$userfrom = $users[$post->userid];
if (!isset($userfrom->idnumber)) {
// Minimalised user info, fetch full record.
$userfrom = $DB->get_record('user', array('id' => $userfrom->id));
cybrary_cron_minimise_user_record($userfrom);
}
} else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
cybrary_cron_minimise_user_record($userfrom);
// Fetch only once if possible, we can add it to user list, it will be skipped anyway.
if ($userscount <= CYBRARY_CRON_USER_CACHE) {
$userscount++;
$users[$userfrom->id] = $userfrom;
}
} else {
mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
continue;
}
// Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
// Setup global $COURSE properly - needed for roles and languages.
cron_setup_user($userto, $course);
// Fill caches.
if (!isset($userto->viewfullnames[$cybrary->id])) {
$modcontext = context_module::instance($cm->id);
$userto->viewfullnames[$cybrary->id] = has_capability('moodle/site:viewfullnames', $modcontext);
}
if (!isset($userto->canpost[$discussion->id])) {
$modcontext = context_module::instance($cm->id);
$userto->canpost[$discussion->id] = cybrary_user_can_post($cybrary, $discussion, $userto, $cm, $course, $modcontext);
}
if (!isset($userfrom->groups[$cybrary->id])) {
if (!isset($userfrom->groups)) {
$userfrom->groups = array();
if (isset($users[$userfrom->id])) {
$users[$userfrom->id]->groups = array();
}
}
$userfrom->groups[$cybrary->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
if (isset($users[$userfrom->id])) {
$users[$userfrom->id]->groups[$cybrary->id] = $userfrom->groups[$cybrary->id];
}
}
// Make sure groups allow this user to see this email.
if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
// Groups are being used.
if (!groups_group_exists($discussion->groupid)) {
// Can't find group - be safe and don't this message.
continue;
}
if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
// Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
continue;
}
}
// Make sure we're allowed to see the post.
if (!cybrary_user_can_see_post($cybrary, $discussion, $post, null, $cm)) {
mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
continue;
}
// OK so we need to send the email.
// Does the user want this post in a digest? If so postpone it for now.
$maildigest = cybrary_get_user_maildigest_bulk($digests, $userto, $cybrary->id);
if ($maildigest > 0) {
// This user wants the mails to be in digest form.
$queue = new stdClass();
$queue->userid = $userto->id;
$queue->discussionid = $discussion->id;
$queue->postid = $post->id;
$queue->timemodified = $post->created;
$DB->insert_record('cybrary_queue', $queue);
continue;
}
// Prepare to actually send the post now, and build up the content.
$cleancybraryname = str_replace('"', "'", strip_tags(format_string($cybrary->name)));
$userfrom->customheaders = array (
// Headers to make emails easier to track.
'List-Id: "' . $cleancybraryname . '" <moodlecybrary' . $cybrary->id . '@' . $hostname.'>',
'List-Help: ' . $CFG->wwwroot . '/mod/cybrary/view.php?f=' . $cybrary->id,
'Message-ID: ' . cybrary_get_email_message_id($post->id, $userto->id, $hostname),
'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',
);
$shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
// Generate a reply-to address from using the Inbound Message handler.
$replyaddress = null;
if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
$messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
$replyaddress = $messageinboundgenerator->generate($userto->id);
}
if (!isset($userto->canpost[$discussion->id])) {
$canreply = cybrary_user_can_post($cybrary, $discussion, $userto, $cm, $course, $modcontext);
} else {
$canreply = $userto->canpost[$discussion->id];
}
$data = new \mod_cybrary\output\cybrary_post_email(
$course,
$cm,
$cybrary,
$discussion,
$post,
$userfrom,
$userto,
$canreply
);
if (!isset($userto->viewfullnames[$cybrary->id])) {
$data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
} else {
$data->viewfullnames = $userto->viewfullnames[$cybrary->id];
}
$a = new stdClass();
$a->courseshortname = $data->get_coursename();
$a->cybraryname = $cleancybraryname;
$a->subject = $data->get_subject();
$postsubject = html_to_text(get_string('postmailsubject', 'cybrary', $a), 0);
$rootid = cybrary_get_email_message_id($discussion->firstpost, $userto->id, $hostname);
if ($post->parent) {
// This post is a reply, so add reply header (RFC 2822).
$parentid = cybrary_get_email_message_id($post->parent, $userto->id, $hostname);
$userfrom->customheaders[] = "In-Reply-To: $parentid";
// If the post is deeply nested we also reference the parent message id and
// the root message id (if different) to aid threading when parts of the email
// conversation have been deleted (RFC1036).
if ($post->parent != $discussion->firstpost) {
$userfrom->customheaders[] = "References: $rootid $parentid";
} else {
$userfrom->customheaders[] = "References: $parentid";
}
}
// MS Outlook / Office uses poorly documented and non standard headers, including
// Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
$a->subject = $discussion->name;
$threadtopic = html_to_text(get_string('postmailsubject', 'cybrary', $a), 0);
$userfrom->customheaders[] = "Thread-Topic: $threadtopic";
$userfrom->customheaders[] = "Thread-Index: " . substr($rootid, 1, 28);
// Send the post now!
mtrace('Sending ', '');
$eventdata = new \core\message\message();
$eventdata->component = 'mod_cybrary';
$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;
$eventdata->replyto = $replyaddress;
if (!empty($replyaddress)) {
// Add extra text to email messages if they can reply back.
$textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_cybrary');
$htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_cybrary'));
$additionalcontent = array('fullmessage' => array('footer' => $textfooter),
'fullmessagehtml' => array('footer' => $htmlfooter));
$eventdata->set_additional_content('email', $additionalcontent);
}
// If cybrary_replytouser is not set then send mail using the noreplyaddress.
if (empty($CFG->cybrary_replytouser)) {
$eventdata->userfrom = core_user::get_noreply_user();
}
$smallmessagestrings = new stdClass();
$smallmessagestrings->user = fullname($userfrom);
$smallmessagestrings->cybraryname = "$shortname: " . format_string($cybrary->name, true) . ": " . $discussion->name;
$smallmessagestrings->message = $post->message;
// Make sure strings are in message recipients language.
$eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'cybrary', $smallmessagestrings, $userto->lang);
$contexturl = new moodle_url('/mod/cybrary/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
$eventdata->contexturl = $contexturl->out();
$eventdata->contexturlname = $discussion->name;
$mailresult = message_send($eventdata);
if (!$mailresult) {
mtrace("Error: mod/cybrary/lib.php cybrary_cron(): 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]++;
// Mark post as read if cybrary_usermarksread is set off.
if (!$CFG->cybrary_usermarksread) {
$userto->markposts[$post->id] = $post->id;
}
}
mtrace('post ' . $post->id . ': ' . $post->subject);
}
// Mark processed posts as read.
cybrary_tp_mark_posts_read($userto, $userto->markposts);
unset($userto);
}
}
if ($posts) {
foreach ($posts as $post) {
mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
if ($errorcount[$post->id]) {
$DB->set_field('cybrary_posts', 'mailed', CYBRARY_MAILED_ERROR, array('id' => $post->id));
}
}
}
// release some memory
unset($subscribedusers);
unset($mailcount);
unset($errorcount);
cron_setup_user();
$sitetimezone = core_date::get_server_timezone();
// Now see if there are any digest mails waiting to be sent, and if we should send them
mtrace('Starting digest processing...');
core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
if (!isset($CFG->digestmailtimelast)) { // To catch the first time
set_config('digestmailtimelast', 0);
}
$timenow = time();
$digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
// Delete any really old ones (normally there shouldn't be any)
$weekago = $timenow - (7 * 24 * 3600);
$DB->delete_records_select('cybrary_queue', "timemodified < ?", array($weekago));
mtrace ('Cleaned old digest records');
if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
mtrace('Sending cybrary digests: '.userdate($timenow, '', $sitetimezone));
$digestposts_rs = $DB->get_recordset_select('cybrary_queue', "timemodified < ?", array($digesttime));
if ($digestposts_rs->valid()) {
// We have work to do
$usermailcount = 0;
//caches - reuse the those filled before too
$discussionposts = array();
$userdiscussions = array();
foreach ($digestposts_rs as $digestpost) {
if (!isset($posts[$digestpost->postid])) {
if ($post = $DB->get_record('cybrary_posts', array('id' => $digestpost->postid))) {
$posts[$digestpost->postid] = $post;
} else {
continue;
}
}
$discussionid = $digestpost->discussionid;
if (!isset($discussions[$discussionid])) {
if ($discussion = $DB->get_record('cybrary_discussions', array('id' => $discussionid))) {
$discussions[$discussionid] = $discussion;
} else {
continue;
}
}
$cybraryid = $discussions[$discussionid]->cybrary;
if (!isset($cybraries[$cybraryid])) {
if ($cybrary = $DB->get_record('cybrary', array('id' => $cybraryid))) {
$cybraries[$cybraryid] = $cybrary;
} else {
continue;
}
}
$courseid = $cybraries[$cybraryid]->course;
if (!isset($courses[$courseid])) {
if ($course = $DB->get_record('course', array('id' => $courseid))) {
$courses[$courseid] = $course;
} else {
continue;
}
}
if (!isset($coursemodules[$cybraryid])) {
if ($cm = get_coursemodule_from_instance('cybrary', $cybraryid, $courseid)) {
$coursemodules[$cybraryid] = $cm;