forked from mdjnelson/moodle-mod_certificate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
1524 lines (1335 loc) · 50.1 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 the 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 Mark Nelson <[email protected]>
* @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');
/** The border image folder */
define('CERT_IMAGE_BORDER', 'borders');
/** The watermark image folder */
define('CERT_IMAGE_WATERMARK', 'watermarks');
/** The signature image folder */
define('CERT_IMAGE_SIGNATURE', 'signatures');
/** The seal image folder */
define('CERT_IMAGE_SEAL', 'seals');
/** Set CERT_PER_PAGE to 0 if you wish to display all certificates on the report page */
define('CERT_PER_PAGE', 30);
define('CERT_MAX_PER_PAGE', 200);
/**
* Add certificate instance.
*
* @param stdClass $certificate
* @return int new certificate instance id
*/
function certificate_add_instance($certificate) {
global $DB;
// Create the certificate.
$certificate->timecreated = time();
$certificate->timemodified = $certificate->timecreated;
return $DB->insert_record('certificate', $certificate);
}
/**
* Update certificate instance.
*
* @param stdClass $certificate
* @return bool true
*/
function certificate_update_instance($certificate) {
global $DB;
// Update the certificate.
$certificate->timemodified = time();
$certificate->id = $certificate->instance;
return $DB->update_record('certificate', $certificate);
}
/**
* 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 true if successful
*/
function certificate_delete_instance($id) {
global $DB;
// Ensure the certificate exists
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;
}
// Delete any files associated with the certificate
$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)) {
$sql = "SELECT cert.id
FROM {certificate} cert
WHERE cert.course = :courseid";
$DB->delete_records_select('certificate_issues', "certificateid IN ($sql)", array('courseid' => $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 stdClass $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 stdClass the user outline object
*/
function certificate_user_outline($course, $user, $mod, $certificate) {
global $DB;
$result = new stdClass;
if ($issue = $DB->get_record('certificate_issues', array('certificateid' => $certificate->id, 'userid' => $user->id))) {
$result->info = get_string('issued', 'certificate');
$result->time = $issue->timecreated;
} 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 string the user complete information
*/
function certificate_user_complete($course, $user, $mod, $certificate) {
global $DB, $OUTPUT;
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->timecreated);
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 stdClass list of participants
*/
function certificate_get_participants($certificateid) {
global $DB;
$sql = "SELECT DISTINCT u.id, u.id
FROM {user} u, {certificate_issues} a
WHERE a.certificateid = :certificateid
AND u.id = a.userid";
return $DB->get_records_sql($sql, array('certificateid' => $certificateid));
}
/**
* @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;
}
}
/**
* 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 the teacher 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
*/
function certificate_email_teachers($course, $certificate, $certrecord, $cm) {
global $USER, $CFG, $DB;
if ($certificate->emailteachers == 0) { // No need to do anything
return;
}
$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) {
$info = new stdClass;
$info->student = fullname($USER);
$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 = $USER;
$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
*
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $cm course module
*/
function certificate_email_others($course, $certificate, $certrecord, $cm) {
global $USER, $CFG, $DB;
if ($certificate->emailothers) {
$others = explode(',', $certificate->emailothers);
if ($others) {
$strawarded = get_string('awarded', 'certificate');
foreach ($others as $other) {
$other = trim($other);
if (validate_email($other)) {
$destination = new stdClass;
$destination->email = $other;
$info = new stdClass;
$info->student = fullname($USER);
$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 = $USER;
$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 $course
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $context
*/
function certificate_email_student($course, $certificate, $certrecord, $context) {
global $DB, $USER;
// 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);
}
// Ok, no teachers, use administrator name
if (empty($teacher)) {
$teacher = fullname(get_admin());
}
$info = new stdClass;
$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));
// Remove full-stop at the end if it exists, to avoid "..pdf" being created and being filtered by clean_filename
$certname = rtrim($certificate->name, '.');
$filename = clean_filename("$certname.pdf");
// Get hashed pathname
$fs = get_file_storage();
$component = 'mod_certificate';
$filearea = 'issue';
$filepath = '/';
$files = $fs->get_area_files($context->id, $component, $filearea, $certrecord->id);
foreach ($files as $f) {
$filepathname = $f->get_contenthash();
}
$attachment = 'filedir/'.certificate_path_from_hash($filepathname).'/'.$filepathname;
$attachname = $filename;
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|nothing false if file not found, does not return anything 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
*
* @param string $pdf is the string contents of the pdf
* @param int $certrecordid the certificate issue record id
* @param string $filename pdf filename
* @param int $contextid context id
* @return bool return true if successful, false otherwise
*/
function certificate_save_pdf($pdf, $certrecordid, $filename, $contextid) {
global $DB, $USER;
if (empty($certrecordid)) {
return false;
}
if (empty($pdf)) {
return false;
}
$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' => $certrecordid, // 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);
// If the file exists, delete it and recreate it. This is to ensure that the
// latest certificate is saved on the server. For example, the student's grade
// may have been updated. This is a quick dirty hack.
if ($fs->file_exists($contextid, $component, $filearea, $certrecordid, $filepath, $filename)) {
$fs->delete_area_files($contextid, $component, $filearea, $certrecordid);
}
$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
* @param stdClass $context
* @return string return the user files
*/
function certificate_print_user_files($certificate, $userid, $context) {
global $CFG, $DB, $OUTPUT;
$output = '';
$certrecord = $DB->get_record('certificate_issues', array('userid' => $userid, 'certificateid' => $certificate->id));
$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;
}
/**
* 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
* @param stdClass $cm
* @return stdClass the newly created certificate issue
*/
function certificate_get_issue($course, $user, $certificate, $cm) {
global $DB;
// Check if there is an issue already, should only ever be one
if ($certissue = $DB->get_record('certificate_issues', array('userid' => $user->id, 'certificateid' => $certificate->id))) {
return $certissue;
}
// Create new certificate issue record
$certissue = new stdClass();
$certissue->certificateid = $certificate->id;
$certissue->userid = $user->id;
$certissue->code = certificate_generate_code();
$certissue->timecreated = time();
$certissue->id = $DB->insert_record('certificate_issues', $certissue);
// Email to the teachers and anyone else
certificate_email_teachers($course, $certificate, $certissue, $cm);
certificate_email_others($course, $certificate, $certissue, $cm);
return $certissue;
}
/**
* Returns a list of issued certificates - sorted for report.
*
* @param int $certificateid
* @param string $sort the sort order
* @param bool $groupmode are we in group mode ?
* @param stdClass $cm the course module
* @param int $page offset
* @param int $perpage total per page
* @return stdClass the users
*/
function certificate_get_issues($certificateid, $sort="ci.timecreated ASC", $groupmode, $cm, $page = 0, $perpage = 0) {
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);
$conditionssql = '';
$conditionsparams = array();
if ($certmanagers = array_keys(get_users_by_capability($context, 'mod/certificate:manage', 'u.id'))) {
list($sql, $params) = $DB->get_in_or_equal($certmanagers, SQL_PARAMS_NAMED, 'cert');
$conditionssql .= "AND NOT u.id $sql \n";
$conditionsparams += $params;
}
$restricttogroup = false;
if ($groupmode) {
$currentgroup = groups_get_activity_group($cm);
if ($currentgroup) {
$restricttogroup = true;
$groupusers = array_keys(groups_get_members($currentgroup, 'u.*'));
if (empty($groupusers)) {
return array();
}
}
}
$restricttogrouping = false;
// if groupmembersonly used, remove users who are not in any group
if (!empty($CFG->enablegroupings) and $cm->groupmembersonly) {
if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
$restricttogrouping = true;
} else {
return array();
}
}
if ($restricttogroup || $restricttogrouping) {
if ($restricttogroup) {
$allowedusers = $groupusers;
} else if ($restricttogroup && $restricttogrouping) {
$allowedusers = array_intersect($groupusers, $groupingusers);
} else {
$allowedusers = $groupingusers;
}
list($sql, $params) = $DB->get_in_or_equal($allowedusers, SQL_PARAMS_NAMED, 'grp');
$conditionssql .= "AND u.id $sql \n";
$conditionsparams += $params;
}
$page = (int) $page;
$perpage = (int) $perpage;
// Get all the users that have certificates issued, should only be one issue per user for a certificate
$allparams = $conditionsparams + array('certificateid' => $certificateid);
$users = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated
FROM {user} u
INNER JOIN {certificate_issues} ci
ON u.id = ci.userid
WHERE u.deleted = 0
AND ci.certificateid = :certificateid
$conditionssql
ORDER BY {$sort}",
$allparams,
$page * $perpage,
$perpage);
return $users;
}
/**
* Returns a list of previously issued certificates--used for reissue.
*
* @param int $certificateid
* @return stdClass the attempts else false if none found
*/
function certificate_get_attempts($certificateid) {
global $DB, $USER;
$sql = "SELECT *
FROM {certificate_issues} i
WHERE certificateid = :certificateid
AND userid = :userid";
if ($issues = $DB->get_records_sql($sql, array('certificateid' => $certificateid, 'userid' => $USER->id))) {
return $issues;
}
return false;
}
/**
* Prints a table of previously issued certificates--used for reissue.
*
* @param stdClass $course
* @param stdClass $certificate
* @param stdClass $attempts
* @return string the attempt table
*/
function certificate_print_attempts($course, $certificate, $attempts) {
global $OUTPUT, $DB;
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 = userdate($attempt->timecreated);
$row[] = $datecompleted;
if ($gradecolumn) {
$attemptgrade = certificate_get_grade($certificate, $course);
$row[] = $attemptgrade;
}
$table->data[$attempt->id] = $row;
}
echo html_writer::table($table);
}
/**
* Get the time the user has spent in the course
*
* @param int $courseid
* @return int the total time spent in seconds
*/
function certificate_get_course_time($courseid) {
global $CFG, $USER;
set_time_limit(0);
$totaltime = 0;
$sql = "l.course = :courseid AND l.userid = :userid";
if ($logs = get_logs($sql, array('courseid' => $courseid, 'userid' => $USER->id), 'l.time ASC', '', '', $totalcount)) {
foreach ($logs as $log) {
if (!isset($login)) {
// For the first time $login is not set so the first log is also the first login
$login = $log->time;
$lasthit = $log->time;
$totaltime = 0;
}
$delay = $log->time - $lasthit;
if ($delay > ($CFG->sessiontimeout * 60)) {
// The difference between the last log and the current log is more than
// the timeout Register session value so that we have found a session!
$login = $log->time;
} else {
$totaltime += $delay;
}
// Now the actual log became the previous log for the next cycle
$lasthit = $log->time;
}
return $totaltime;
}
return 0;
}
/**
* 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
$modinfo = get_fast_modinfo($COURSE);
$mods = $modinfo->get_cms();
$modules = array();
// Check what version we are running - really we should have separate branch for 2.4, but
// having a branch called master and one called MOODLE_24_STABLE may be confusing. This
// module will also be replaced in the future so hack will do. Here we get the course
// sections and sort the modules as they appear in the course.
if ($CFG->version >= '2012112900') {
$sections = $modinfo->get_section_info_all();
} else {
$sections = get_all_sections($COURSE->id);
}
for ($i = 0; $i <= count($sections) - 1; $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.
*
* @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;
}
/**
* Fetch all grade categories from the specified course
*
* @return array
*/
function certificate_get_grade_categories($courseid) {
$grade_category_options = array();
if ($grade_categories = grade_category::fetch_all(array('courseid'=>$courseid))) {
foreach ($grade_categories as $grade_category) {
if( !$grade_category->is_course_category() )
$grade_category_options[-$grade_category->id] = get_string('category') . ' : ' . $grade_category->get_name();
}
}
return $grade_category_options;
}
/**
* 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();
}
}
}
if (isset($printoutcome)) {
$outcomeoptions['0'] = get_string('no');
foreach ($printoutcome as $key => $value) {
$outcomeoptions[$key] = $value;
}
} else {
$outcomeoptions['0'] = get_string('nooutcomes', 'certificate');
}
return $outcomeoptions;
}
/**
* Used for course participation report (in case certificate is added).
*
* @return array
*/
function certificate_get_view_actions() {
return array('view', 'view all', 'view report');