forked from mdjnelson/moodle-mod_certificate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
1507 lines (1330 loc) · 48 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 Certificate module for 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/>.
/**
* Certificate module core interaction API
*
* @package mod
* @subpackage certificate
* @copyright Chardelle Busch, Mark Nelson
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/grade/lib.php');
require_once($CFG->dirroot.'/grade/querylib.php');
/**
* Add certificate instance.
*
* @param stdClass $certificate
* @return int new certificate instance id
*/
function certificate_add_instance($certificate) {
global $DB;
$certificate->timemodified = time();
if ($returnid = $DB->insert_record('certificate', $certificate)) {
$certificate->id = $returnid;
$event = NULL;
$event->name = $certificate->name;
$event->description = '';
$event->courseid = $certificate->course;
$event->groupid = 0;
$event->userid = 0;
$event->eventtype = 'course';
$event->modulename = 'certificate';
$event->instance = $returnid;
add_event($event);
}
return $returnid;
}
/**
* Update certificate instance.
*
* @param stdClass $certificate
* @return bool true
*/
function certificate_update_instance($certificate) {
global $DB;
$certificate->timemodified = time();
$certificate->id = $certificate->instance;
if ($returnid = $DB->update_record('certificate', $certificate)) {
if ($event->id = $DB->get_field('event', 'id', array('modulename'=> 'certificate', 'instance'=> $certificate->id))) {
$event->name = $certificate->name;
update_event($event);
} else {
$event = NULL;
$event->name = $certificate->name;
$event->description = '';
$event->courseid = $certificate->course;
$event->groupid = 0;
$event->userid = 0;
$event->modulename = 'certificate';
$event->instance = $certificate->id;
add_event($event);
}
} else {
$DB->delete_records('event', array('modulename'=>'certificate', 'instance'=> $certificate->id));
}
return $returnid;
}
/**
* 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
* @return bool success
*/
function certificate_delete_instance($id) {
global $CFG, $DB, $USER;
if (!$certificate = $DB->get_record('certificate', array('id'=> $id))) {
return false;
}
// Prepare file record object
if (!$cm = get_coursemodule_from_instance('certificate', $id)) {
return false;
}
$result = true;
$DB->delete_records('certificate_issues', array('certificateid'=> $id));
if (!$DB->delete_records('certificate', array('id'=> $id))) {
$result = false;
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$fs = get_file_storage();
$fs->delete_area_files($context->id);
return $result;
}
/**
* This function is used by the reset_course_userdata function in moodlelib.
* This function will remove all posts from the specified certificate
* and clean up any related data.
*
* Written by Jean-Michel Vedrine
*
* @param $data the data submitted from the reset course.
* @return array status array
*/
function certificate_reset_userdata($data) {
global $CFG, $DB;
$componentstr = get_string('modulenameplural', 'certificate');
$status = array();
if (!empty($data->reset_certificate)) {
$certificatessql = "SELECT cert.id " .
"FROM {certificate} cert " .
"WHERE cert.course = ?";
$DB->delete_records_select('certificate_issues', "certificateid IN ($certificatessql)", array($data->courseid));
$status[] = array('component'=>$componentstr, 'item'=>get_string('certificateremoved', 'certificate'), 'error'=>false);
}
// Updating dates - shift may be negative too
if ($data->timeshift) {
shift_course_mod_dates('certificate', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
$status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
}
return $status;
}
/**
* Implementation of the function for printing the form elements that control
* whether the course reset functionality affects the certificate.
*
* Written by Jean-Michel Vedrine
*
* @param $mform form passed by reference
*/
function certificate_reset_course_form_definition(&$mform) {
$mform->addElement('header', 'certificateheader', get_string('modulenameplural', 'certificate'));
$mform->addElement('advcheckbox', 'reset_certificate', get_string('deletissuedcertificates','certificate'));
}
/**
* Course reset form defaults.
*
* Written by Jean-Michel Vedrine
*
* @param $course
* @return array
*/
function certificate_reset_course_form_defaults($course) {
return array('reset_certificate'=>1);
}
/**
* Returns information about received certificate.
* Used for user activity reports.
*
* @param stdClass $course
* @param stdClass $user
* @param stdClass $mod
* @param stdClass $certificate
* @return object|null
*/
function certificate_user_outline($course, $user, $mod, $certificate) {
global $DB;
if ($issue = $DB->get_record('certificate_issues', array('certificateid' => $certificate->id, 'userid' => $user->id))) {
$result->info = get_string('issued', 'certificate');
$result->time = $issue->certdate;
} else {
$result->info = get_string('notissued', 'certificate');
}
return $result;
}
/**
* Returns information about received certificate.
* Used for user activity reports.
*
* @param stdClass $course
* @param stdClass $user
* @param stdClass $mod
* @param stdClass $page
* @return object|null
*/
function certificate_user_complete($course, $user, $mod, $certificate) {
global $DB;
if ($issue = $DB->get_record('certificate_issues', array('certificateid' => $certificate->id, 'userid' => $user->id))) {
echo $OUTPUT->box_start();
echo get_string('issued', 'certificate').": ";
echo userdate($issue->certdate);
certificate_print_user_files($certificate->id, $user->id);
echo '<br />';
echo $OUTPUT->box_end();
} else {
print_string('notissuedyet', 'certificate');
}
}
/**
* Must return an array of user records (all data) who are participants
* for a given instance of certificate.
*
* @param int $certificateid
* @return object list of participants
*/
function certificate_get_participants($certificateid) {
global $CFG, $DB;
//Get students
$participants = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
FROM {user} u,
{certificate_issues} a
WHERE a.certificateid = ? and
u.id = a.userid", array($certificateid));
return $participants;
}
/**
* @uses FEATURE_GROUPS
* @uses FEATURE_GROUPINGS
* @uses FEATURE_GROUPMEMBERSONLY
* @uses FEATURE_MOD_INTRO
* @uses FEATURE_COMPLETION_TRACKS_VIEWS
* @uses FEATURE_GRADE_HAS_GRADE
* @uses FEATURE_GRADE_OUTCOMES
* @param string $feature FEATURE_xx constant for requested feature
* @return mixed True if module supports feature, null if doesn't know
*/
function certificate_supports($feature) {
switch ($feature) {
case FEATURE_GROUPS: return true;
case FEATURE_GROUPINGS: return true;
case FEATURE_GROUPMEMBERSONLY: return true;
case FEATURE_MOD_INTRO: return true;
case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
case FEATURE_BACKUP_MOODLE2: return true;
default: return null;
}
}
/**
* Prints the header in view. Used to help prevent FPDF header errors.
*
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $cm
* @return null
*/
function view_header($course, $certificate, $cm) {
global $CFG, $DB, $PAGE, $OUTPUT;
$PAGE->set_title(format_string($certificate->name));
$PAGE->set_heading(format_string($course->fullname));
echo $OUTPUT->header();
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (has_capability('mod/certificate:manage', $context)) {
$numusers = count(certificate_get_issues($certificate->id, 'ci.certdate ASC', '', $cm));
echo '<div class="reportlink"><a href="report.php?id='.$cm->id.'">'.
get_string('viewcertificateviews', 'certificate', $numusers).'</a></div>';
}
if (!empty($certificate->intro)) {
echo $OUTPUT->box(format_text($certificate->intro), 'generalbox', 'intro');
}
}
/**
* Function to be run periodically according to the moodle cron
* TODO:This needs to be done
*/
function certificate_cron () {
return true;
}
/**
* Returns a list of teachers by group
* for sending email alerts to teachers
*
* @param stdClass $certificate
* @param stdClass $user
* @param stdClass $course
* @param stdClass $cm
* @return array
*/
function certificate_get_teachers($certificate, $user, $course, $cm) {
global $USER, $DB;
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$potteachers = get_users_by_capability($context, 'mod/certificate:manage', '', '', '', '', '', '', false, false);
if (empty($potteachers)) {
return array();
}
$teachers = array();
if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS) { // Separate groups are being used
if ($groups = groups_get_all_groups($course->id, $user->id)) { // Try to find all groups
foreach ($groups as $group) {
foreach ($potteachers as $t) {
if ($t->id == $user->id) {
continue; // do not send self
}
if (groups_is_member($group->id, $t->id)) {
$teachers[$t->id] = $t;
}
}
}
} else {
// user not in group, try to find teachers without group
foreach ($potteachers as $t) {
if ($t->id == $USER->id) {
continue; // do not send self
}
if (!groups_get_all_groups($course->id, $t->id)) { //ugly hack
$teachers[$t->id] = $t;
}
}
}
} else {
foreach ($potteachers as $t) {
if ($t->id == $USER->id) {
continue; // do not send self
}
$teachers[$t->id] = $t;
}
}
return $teachers;
}
/**
* Alerts teachers by email of received certificates. First checks
* whether the option to email teachers is set for this certificate.
*
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $cm course module
* @return null
*/
function certificate_email_teachers($course, $certificate, $certrecord, $cm) {
global $USER, $CFG, $DB;
if ($certificate->emailteachers == 0) { // No need to do anything
return;
}
$student = $certrecord->studentname;
$user = $DB->get_record('user', array('id'=> $certrecord->userid));
if ($teachers = certificate_get_teachers($certificate, $user, $course, $cm)) {
$strawarded = get_string('awarded', 'certificate');
foreach ($teachers as $teacher) {
unset($info);
$info->student = $student;
$info->course = format_string($course->fullname,true);
$info->certificate = format_string($certificate->name,true);
$info->url = $CFG->wwwroot.'/mod/certificate/report.php?id='.$cm->id;
$from = $student;
$postsubject = $strawarded.': '.$info->student.' -> '.$certificate->name;
$posttext = certificate_email_teachers_text($info);
$posthtml = ($teacher->mailformat == 1) ? certificate_email_teachers_html($info) : '';
@email_to_user($teacher, $from, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
}
}
}
/**
* Alerts others by email of received certificates. First checks
* whether the option to email others is set for this certificate.
* Uses the email_teachers info.
* Code suggested by Eloy Lafuente
*/
function certificate_email_others ($course, $certificate, $certrecord, $cm) {
global $USER, $CFG, $DB;
if ($certificate->emailothers) {
$student = $certrecord->studentname;
$others = explode(',', $certificate->emailothers);
if ($others) {
$strawarded = get_string('awarded', 'certificate');
foreach ($others as $other) {
$other = trim($other);
if (validate_email($other)) {
$destination->email = $other;
unset($info);
$info->student = $student;
$info->course = format_string($course->fullname,true);
$info->certificate = format_string($certificate->name,true);
$info->url = $CFG->wwwroot.'/mod/certificate/report.php?id='.$cm->id;
$from = $student;
$postsubject = $strawarded.': '.$info->student.' -> '.$certificate->name;
$posttext = certificate_email_teachers_text($info);
$posthtml = certificate_email_teachers_html($info);
@email_to_user($destination, $from, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
}
}
}
}
}
/**
* Creates the text content for emails to teachers -- needs to be finished with cron
*
* @param $info object The info used by the 'emailteachermail' language string
* @return string
*/
function certificate_email_teachers_text($info) {
$posttext = get_string('emailteachermail', 'certificate', $info)."\n";
return $posttext;
}
/**
* Creates the html content for emails to teachers
*
* @param $info object The info used by the 'emailteachermailhtml' language string
* @return string
*/
function certificate_email_teachers_html($info) {
$posthtml = '<font face="sans-serif">';
$posthtml .= '<p>'.get_string('emailteachermailhtml', 'certificate', $info).'</p>';
$posthtml .= '</font>';
return $posthtml;
}
/**
* Sends the student their issued certificate from moddata as an email
* attachment.
*
* @param stdClass $user
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $context
*/
function certificate_email_students($user, $course, $certificate, $certrecord, $context) {
global $DB, $USER;
if ($certrecord->mailed > 0) {
return;
}
// Get teachers
if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
'', '', '', '', false, true)) {
$users = sort_by_roleassignment_authority($users, $context);
$teacher = array_shift($users);
}
// If we haven't found a teacher yet, look for a non-editing teacher in this course.
if (empty($teacher) && $users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
'', '', '', '', false, true)) {
$users = sort_by_roleassignment_authority($users, $context);
$teacher = array_shift($users);
}
$info->username = fullname($user);
$info->certificate = format_string($certificate->name,true);
$info->course = format_string($course->fullname,true);
$from = fullname($teacher);
$subject = $info->course.': '.$info->certificate;
$message = get_string('emailstudenttext', 'certificate', $info)."\n";
// Make the HTML version more XHTML happy (&)
$messagehtml = text_to_html(get_string('emailstudenttext', 'certificate', $info));
$user->mailformat = 0; // Always send HTML version as well
$filename = clean_filename($certificate->name.'.pdf');
// Get hashed pathname
$fs = get_file_storage();
$component = 'mod_certificate';
$filearea = 'issue';
$filepath = '/';
$files = $fs->get_area_files($context->id, $component, $filearea, $certificate->id);
foreach ($files as $f) {
$filepathname = $f->get_contenthash();
}
$attachment = 'filedir/'.certificate_path_from_hash($filepathname).'/'.$filepathname;
$attachname = $filename;
$DB->set_field('certificate_issues','mailed','1',array('certificateid'=> $certificate->id, 'userid'=> $user->id));
return email_to_user($user, $from, $subject, $message, $messagehtml, $attachment, $attachname);
}
/**
* Retrieve certificate path from hash
*
* @param array $contenthash
* @return string the path
*/
function certificate_path_from_hash($contenthash) {
$l1 = $contenthash[0].$contenthash[1];
$l2 = $contenthash[2].$contenthash[3];
return "$l1/$l2";
}
/**
* Serves certificate issues and other files.
*
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @param string $filearea
* @param array $args
* @param bool $forcedownload
* @return bool false if file not found, does not return if found - just send the file
*/
function certificate_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
global $CFG, $DB, $USER;
if ($context->contextlevel != CONTEXT_MODULE) {
return false;
}
if (!$certificate = $DB->get_record('certificate', array('id'=>$cm->instance))) {
return false;
}
require_login($course, false, $cm);
require_once($CFG->libdir.'/filelib.php');
if ($filearea === 'issue') {
$certrecord = (int)array_shift($args);
if (!$certrecord = $DB->get_record('certificate_issues', array('id'=>$certrecord))) {
return false;
}
if ($USER->id != $certrecord->userid and !has_capability('mod/certificate:manage', $context)) {
return false;
}
$relativepath = implode('/', $args);
$fullpath = "/{$context->id}/mod_certificate/issue/$certrecord->id/$relativepath";
$fs = get_file_storage();
if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
return false;
}
send_stored_file($file, 0, 0, true); // download MUST be forced - security!
}
}
/**
* This function returns success or failure of file save
*
* @global object
* @param string $pdf is the string contents of the pdf
* @param int $certificateid the certificate id
* @param string $filename pdf filename
* @param int $contextid context id
* @return bool
*/
function certificate_save_pdf($pdf, $certificateid, $filename, $contextid) {
global $DB, $USER;
if (empty($certificateid)) {
return false;
}
if (empty($pdf)) {
return true; // Nothing to do
}
$fs = get_file_storage();
// Prepare file record object
$component = 'mod_certificate';
$filearea = 'issue';
$filepath = '/';
$fileinfo = array(
'contextid' => $contextid, // ID of context
'component' => $component, // usually = table name
'filearea' => $filearea, // usually = table name
'itemid' => $certificateid, // usually = ID of row in table
'filepath' => $filepath, // any path beginning and ending in /
'filename' => $filename, // any filename
'mimetype' => 'application/pdf', // any filename
'userid' => $USER->id);
// Check for file first
if (!$fs->file_exists($contextid, $component, $filearea, $certificateid, $filepath, $filename)) {
$fs->create_file_from_string($fileinfo, $pdf);
}
return true;
}
/**
* Produces a list of links to the issued certificates. Used for report.
*
* @param stdClass $certificate
* @param int $userid optional id of the user. If 0 then $USER->id is used.
* @param stdClass $context
* @return boolean, true if success printing
*/
function certificate_print_user_files($certificate, $userid=0, $context) {
global $CFG, $DB, $OUTPUT;
$output = '';
$sql = "SELECT MAX(timecreated) AS latest " .
"FROM {certificate_issues} " .
"WHERE userid = :userid " .
"AND certificateid = :certificateid";
$params = array(
'userid' => $userid,
'certificateid' => $certificate->id
);
if ($record = $DB->get_record_sql($sql, $params)) {
$latest = $record->latest;
}
$certrecord = $DB->get_record('certificate_issues', array('certificateid'=>$certificate->id, 'userid'=>$userid, 'timecreated'=>$latest));
$fs = get_file_storage();
$browser = get_file_browser();
$component = 'mod_certificate';
$filearea = 'issue';
$files = $fs->get_area_files($context, $component, $filearea, $certrecord->id);
foreach ($files as $file) {
$filename = $file->get_filename();
$mimetype = $file->get_mimetype();
$link = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context.'/mod_certificate/issue/'.$certrecord->id.'/'.$filename);
$output = '<img src="'.$OUTPUT->pix_url(file_mimetype_icon($file->get_mimetype())).'" height="16" width="16" alt="'.$file->get_mimetype().'" /> '.
'<a href="'.$link.'" >'.s($filename).'</a>';
}
$output .= '<br />';
$output = '<div class="files">'.$output.'</div>';
return $output;
}
/**
* Returns a list of issued certificates - sorted for report.
*
* @param stdClass $certificate
* @param string $sort the sort order
* @param boolean $groupmode are we in group mode ?
* @param stdClass $cm the course module
*/
function certificate_get_issues($certificate, $sort="ci.certdate ASC", $groupmode, $cm) {
global $CFG, $DB;
// get all users that can manage this certificate to exclude them from the report.
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$certmanagers = get_users_by_capability($context, 'mod/certificate:manage', 'u.id');
// Get all the users that have certificates issued, first, create subsql
// used in the main sql query, this is used so that we don't get an error
// about the same u.id being returned multiple times due to being in the
// certificate issues table multiple times.
$subsql = "SELECT MAX(ci2.timecreated) as timecreated " .
"FROM {certificate_issues} ci2 " .
"WHERE ci2.certificateid = :certificateid " .
"AND ci2.certdate > 0 " .
"AND ci2.userid = u.id";
$users = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated, ci.certdate, ci.studentname, ci.reportgrade
FROM {user} u
INNER JOIN {certificate_issues} ci
ON u.id = ci.userid
WHERE u.deleted = 0
AND ci.certificateid = :certificate
AND ci.certdate > 0
AND ci.timecreated = ($subsql)
ORDER BY :sort", array('certificate'=>$certificate, 'certificateid'=>$certificate, 'sort'=>$sort));
// now exclude all the certmanagers.
foreach ($users as $id => $user) {
if (isset($certmanagers[$id])) { //exclude certmanagers.
unset($users[$id]);
}
}
// if groupmembersonly used, remove users who are not in any group
if (!empty($users) and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
$users = array_intersect($users, array_keys($groupingusers));
}
}
if (!$groupmode) {
return $users;
} else {
$currentgroup = groups_get_activity_group($cm);
if ($currentgroup) {
$groupusers = groups_get_members($currentgroup, 'u.*');
if (empty($groupusers)) {
return array();
}
foreach($groupusers as $id => $gpuser) {
if (!isset($users[$id])) {
//remove this user as it isn't in the group!
unset($users[$id]);
}
}
}
return $users;
}
}
/**
* Returns a list of previously issued certificates--used for reissue.
*
* @param int $certificateid
* @param int $userid
* @return int the number of attempts
*/
function certificate_get_attempts($certificateid, $userid) {
global $DB;
if ($issues = $DB->get_records('certificate_issues', array('certificateid'=>$certificateid, 'userid'=>$userid))) {
return $issues;
} else {
return 0;
}
}
/**
* Prints a table of previously issued certificates--used for reissue.
*
* @param int $certificate id
* @param int $userid
* @param null
*/
function certificate_print_attempts($certificateid, $userid) {
global $OUTPUT, $DB;
if (!$certificate = $DB->get_record('certificate', array('id'=> $certificateid))) {
return false;
}
$attempts = certificate_get_attempts($certificateid, $userid);
echo $OUTPUT->heading(get_string('summaryofattempts', 'certificate'));
// Prepare table header
$table = new html_table();
$table->class = 'generaltable';
$table->head = array(get_string('issued', 'certificate'));
$table->align = array('left');
$table->attributes = array("style" => "width:20%; margin:auto");
$gradecolumn = $certificate->printgrade;
if ($gradecolumn) {
$table->head[] = get_string('grade');
$table->align[] = 'center';
$table->size[] = '';
}
// One row for each attempt
foreach ($attempts as $attempt) {
$row = array();
// prepare strings for time taken and date completed
$datecompleted = '';
if ($attempt->certdate > 0) {
// attempt has finished
$datecompleted = userdate($attempt->certdate);
}
$row[] = $datecompleted;
// Ouside the if because we may be showing feedback but not grades.
if ($gradecolumn) {
$attemptgrade = $attempt->reportgrade;
$row[] = $attemptgrade;
} else {
$row[] = '';
}
$table->data[$attempt->id] = $row;
}
echo html_writer::table($table);
}
/**
* Inserts preliminary user data when a certificate is viewed.
* Prevents form from issuing a certificate upon browser refresh.
*
* @param stdClass $course
* @param stdClass $user
* @param stdClass $certificate
* @return null
*/
function certificate_prepare_issue($course, $user, $certificate) {
global $DB;
if ($certificate->reissuecert == 0) {
if ($DB->record_exists('certificate_issues', array('certificateid'=>$certificate->id, 'userid'=>$user->id))) {
return;
}
} else if ($DB->record_exists('certificate_issues', array('certificateid'=>$certificate->id, 'userid'=>$user->id, 'certdate'=>'0'))) {
return;
}
$timecreated = time();
$code = certificate_generate_code();
$studentname = fullname($user);
$newrec = new Object();
$newrec->certificateid = $certificate->id;
$newrec->userid = $user->id;
$newrec->timecreated = $timecreated;
$newrec->studentname = $studentname;
$newrec->code = $code;
$newrec->classname = $course->fullname;
$DB->insert_record('certificate_issues', $newrec, false);
}
/**
* Inserts final user data when a certificate is created.
*
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $cm
*/
function certificate_issue($course, $certificate, $certrecord, $cm) {
global $USER, $DB;
$sql = 'SELECT MAX(timecreated) AS latest FROM {certificate_issues} ' .
'WHERE userid = :userid and certificateid = :certificateid';
if ($record = $DB->get_record_sql($sql, array('certificateid'=>$certificate->id, 'userid'=>$USER->id))) {
$latest = $record->latest;
}
$certrecord = $DB->get_record('certificate_issues', array('certificateid'=>$certificate->id, 'userid'=>$USER->id, 'timecreated'=>$latest));
if ($certificate->printgrade) {
if ($certificate->printgrade == 1) {
$grade = certificate_print_course_grade($course);
} else if ($certificate->printgrade > 1) {
$grade = certificate_print_mod_grade($course, $certificate->printgrade);
}
if ($certificate->gradefmt == 1) {
$certrecord->reportgrade = $grade->percentage;
}
if ($certificate->gradefmt == 2) {
$certrecord->reportgrade = $grade->points;
}
if ($certificate->gradefmt == 3) {
$certrecord->reportgrade = $grade->letter;
}
}
$date = certificate_generate_date($certificate, $course);
$certrecord->certdate = $date;
$DB->update_record('certificate_issues', $certrecord);
certificate_email_teachers($course, $certificate, $certrecord, $cm);
certificate_email_others($course, $certificate, $certrecord, $cm);
}
/**
* Get all the modules
*
* @return array
*/
function certificate_get_mods() {
global $COURSE, $CFG, $DB;
$strtopic = get_string("topic");
$strweek = get_string("week");
$strsection = get_string("section");
// Collect modules data
get_all_mods($COURSE->id, $mods, $modnames, $modnamesplural, $modnamesused);
$modules = array();
$sections = get_all_sections($COURSE->id); // Sort everything the same as the course
for ($i=0; $i<=$COURSE->numsections; $i++) {
// should always be true
if (isset($sections[$i])) {
$section = $sections[$i];
if ($section->sequence) {
switch ($COURSE->format) {
case "topics":
$sectionlabel = $strtopic;
break;
case "weeks":
$sectionlabel = $strweek;
break;
default:
$sectionlabel = $strsection;
}
$sectionmods = explode(",", $section->sequence);
foreach ($sectionmods as $sectionmod) {
if (empty($mods[$sectionmod])) {
continue;
}
$mod = $mods[$sectionmod];
$mod->courseid = $COURSE->id;
$instance = $DB->get_record($mod->modname, array('id' => $mod->instance));
if ($grade_items = grade_get_grade_items_for_activity($mod)) {
$mod_item = grade_get_grades($COURSE->id, 'mod', $mod->modname, $mod->instance);
$item = reset($mod_item->items);
if (isset($item->grademax)){
$modules[$mod->id] = $sectionlabel.' '.$section->section.' : '.$instance->name;
}
}
}
}
}
}
return $modules;
}
/**
* Search through all the modules for grade data for mod_form.
*
* @param boolean $course include course
* @return array
*/
function certificate_get_grade_options() {
$gradeoptions['0'] = get_string('no');
$gradeoptions['1'] = get_string('coursegrade', 'certificate');
return $gradeoptions;
}
/**
* Search through all the modules for grade dates for mod_form.
*
* @return array
*/
function certificate_get_date_options() {
$dateoptions['0'] = get_string('no');
$dateoptions['1'] = get_string('issueddate', 'certificate');
$dateoptions['2'] = get_string('completiondate', 'certificate');
return $dateoptions;
}
/**
* Get the course outcomes for for mod_form print outcome.
*
* @return array
*/
function certificate_get_outcomes() {
global $COURSE, $DB;
// get all outcomes in course
$grade_seq = new grade_tree($COURSE->id, false, true, '', false);
if ($grade_items = $grade_seq->items) {
// list of item for menu
$printoutcome = array();
foreach ($grade_items as $grade_item) {
if (isset($grade_item->outcomeid)){
$itemmodule = $grade_item->itemmodule;
$printoutcome[$grade_item->id] = $itemmodule.': '.$grade_item->get_name();
}
}
}