-
Notifications
You must be signed in to change notification settings - Fork 114
/
locallib.php
1280 lines (1125 loc) · 43.9 KB
/
locallib.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 internal API,
* this is in separate file to reduce memory use on non-certificate pages.
*
* @package mod_certificate
* @copyright Mark Nelson <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/mod/certificate/lib.php');
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);
/**
* 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;
$context = context_module::instance($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;
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->id = 1;
$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
* @param string $filecontents the PDF file contents
* @param string $filename
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function certificate_email_student($course, $certificate, $certrecord, $context, $filecontents, $filename) {
global $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));
$tempdir = make_temp_directory('certificate/attachment');
if (!$tempdir) {
return false;
}
$tempfile = $tempdir.'/'.md5(sesskey().microtime().$USER->id.'.pdf');
$fp = fopen($tempfile, 'w+');
fputs($fp, $filecontents);
fclose($fp);
$prevabort = ignore_user_abort(true);
$result = email_to_user($USER, $from, $subject, $message, $messagehtml, $tempfile, $filename);
@unlink($tempfile);
ignore_user_abort($prevabort);
return $result;
}
/**
* 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 $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);
// We do not know the previous file name, better delete everything here,
// luckily there is supposed to be always only one certificate here.
$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 int $contextid
* @return string return the user files
*/
function certificate_print_user_files($certificate, $userid, $contextid) {
global $CFG, $DB, $OUTPUT;
$output = '';
$certrecord = $DB->get_record('certificate_issues', array('userid' => $userid, 'certificateid' => $certificate->id));
$fs = get_file_storage();
$component = 'mod_certificate';
$filearea = 'issue';
$files = $fs->get_area_files($contextid, $component, $filearea, $certrecord->id);
foreach ($files as $file) {
$filename = $file->get_filename();
$link = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$contextid.'/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 $DB, $USER;
$context = context_module::instance($cm->id);
$conditionssql = '';
$conditionsparams = array();
// Get all users that can manage this certificate to exclude them from the report.
$certmanagers = array_keys(get_users_by_capability($context, 'mod/certificate:manage', 'u.id'));
$certmanagers = array_merge($certmanagers, array_keys(get_admins()));
list($sql, $params) = $DB->get_in_or_equal($certmanagers, SQL_PARAMS_NAMED, 'cert');
$conditionssql .= "AND NOT u.id $sql \n";
$conditionsparams += $params;
if ($groupmode) {
$canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
$currentgroup = groups_get_activity_group($cm);
// If we are viewing all participants and the user does not have access to all groups then return nothing.
if (!$currentgroup && !$canaccessallgroups) {
return array();
}
if ($currentgroup) {
if (!$canaccessallgroups) {
// Guest users do not belong to any groups.
if (isguestuser()) {
return array();
}
// Check that the user belongs to the group we are viewing.
$usersgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
if ($usersgroups) {
if (!isset($usersgroups[$currentgroup])) {
return array();
}
} else { // They belong to no group, so return an empty array.
return array();
}
}
$groupusers = array_keys(groups_get_members($currentgroup, 'u.*'));
if (empty($groupusers)) {
return array();
}
list($sql, $params) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED, 'grp');
$conditionssql .= "AND u.id $sql ";
$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);
// The picture fields also include the name fields for the user.
$picturefields = user_picture::fields('u', get_extra_user_fields($context));
$users = $DB->get_records_sql("SELECT $picturefields, u.idnumber, 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;
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, $DB, $USER;
$logmanager = get_log_manager();
$readers = $logmanager->get_readers();
$enabledreaders = get_config('tool_log', 'enabled_stores');
$enabledreaders = explode(',', $enabledreaders);
// Go through all the readers until we find one that we can use.
foreach ($enabledreaders as $enabledreader) {
$reader = $readers[$enabledreader];
if ($reader instanceof \logstore_legacy\log\store) {
$logtable = 'log';
$coursefield = 'course';
$timefield = 'time';
break;
} else if ($reader instanceof \core\log\sql_internal_table_reader) {
$logtable = $reader->get_internal_log_table_name();
$coursefield = 'courseid';
$timefield = 'timecreated';
break;
}
}
// If we didn't find a reader then return 0.
if (!isset($logtable)) {
return 0;
}
$sql = "SELECT id, $timefield
FROM {{$logtable}}
WHERE userid = :userid
AND $coursefield = :courseid
ORDER BY $timefield ASC";
$params = array('userid' => $USER->id, 'courseid' => $courseid);
$totaltime = 0;
if ($logs = $DB->get_recordset_sql($sql, $params)) {
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->$timefield;
$lasthit = $log->$timefield;
$totaltime = 0;
}
$delay = $log->$timefield - $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->$timefield;
} else {
$totaltime += $delay;
}
// Now the actual log became the previous log for the next cycle
$lasthit = $log->$timefield;
}
return $totaltime;
}
return 0;
}
/**
* Get all the modules
*
* @return array
*/
function certificate_get_mods() {
global $COURSE, $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();
$sections = $modinfo->get_section_info_all();
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];
$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.
*
* @param int $courseid the course id
* @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;
// 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;
}
/**
* Get certificate types indexed and sorted by name for mod_form.
*
* @return array containing the certificate type
*/
function certificate_types() {
$types = array();
$names = get_list_of_plugins('mod/certificate/type');
$sm = get_string_manager();
foreach ($names as $name) {
if ($sm->string_exists('type'.$name, 'certificate')) {
$types[$name] = get_string('type'.$name, 'certificate');
} else {
$types[$name] = ucfirst($name);
}
}
asort($types);
return $types;
}
/**
* Get images for mod_form.
*
* @param string $type the image type
* @return array
*/
function certificate_get_images($type) {
global $CFG;
switch($type) {
case CERT_IMAGE_BORDER :
$path = "$CFG->dirroot/mod/certificate/pix/borders";
$uploadpath = "$CFG->dataroot/mod/certificate/pix/borders";
break;
case CERT_IMAGE_SEAL :
$path = "$CFG->dirroot/mod/certificate/pix/seals";
$uploadpath = "$CFG->dataroot/mod/certificate/pix/seals";
break;
case CERT_IMAGE_SIGNATURE :
$path = "$CFG->dirroot/mod/certificate/pix/signatures";
$uploadpath = "$CFG->dataroot/mod/certificate/pix/signatures";
break;
case CERT_IMAGE_WATERMARK :
$path = "$CFG->dirroot/mod/certificate/pix/watermarks";
$uploadpath = "$CFG->dataroot/mod/certificate/pix/watermarks";
break;
}
// If valid path
if (!empty($path)) {
$options = array();
$options += certificate_scan_image_dir($path);
$options += certificate_scan_image_dir($uploadpath);
// Sort images
ksort($options);
// Add the 'no' option to the top of the array
$options = array_merge(array('0' => get_string('no')), $options);
return $options;
} else {
return array();
}
}
/**
* Prepare to print an activity grade.
*
* @param stdClass $course
* @param int $moduleid
* @param int $userid
* @return stdClass|bool return the mod object if it exists, false otherwise
*/
function certificate_get_mod_grade($course, $moduleid, $userid) {
global $DB;
$cm = $DB->get_record('course_modules', array('id' => $moduleid));
$module = $DB->get_record('modules', array('id' => $cm->module));
$grade_item = grade_get_grades($course->id, 'mod', $module->name, $cm->instance, $userid);
if (!empty($grade_item)) {
$item = new grade_item();
$itemproperties = reset($grade_item->items);
foreach ($itemproperties as $key => $value) {
$item->$key = $value;
}
$modinfo = new stdClass;
$modname = $DB->get_field($module->name, 'name', array('id' => $cm->instance));
$modinfo->name = format_string($modname, true, array('context' => context_module::instance($cm->id)));
$grade = $item->grades[$userid]->grade;
$item->gradetype = GRADE_TYPE_VALUE;
$item->courseid = $course->id;
$modinfo->points = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_REAL, $decimals = 2);
$modinfo->percentage = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_PERCENTAGE, $decimals = 2);
$modinfo->letter = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_LETTER, $decimals = 0);
if ($grade) {
$modinfo->dategraded = $item->grades[$userid]->dategraded;
} else {
$modinfo->dategraded = time();
}
return $modinfo;
}
return false;
}
/**
* Returns the date to display for the certificate.
*
* @param stdClass $certificate
* @param stdClass $certrecord
* @param stdClass $course
* @param int $userid
* @return string the date
*/
function certificate_get_date($certificate, $certrecord, $course, $userid = null) {
global $DB, $USER;
if (empty($userid)) {
$userid = $USER->id;
}
// Set certificate date to current time, can be overwritten later
$date = $certrecord->timecreated;
if ($certificate->printdate == '2') {
// Get the enrolment end date
$sql = "SELECT MAX(c.timecompleted) as timecompleted
FROM {course_completions} c
WHERE c.userid = :userid
AND c.course = :courseid";
if ($timecompleted = $DB->get_record_sql($sql, array('userid' => $userid, 'courseid' => $course->id))) {
if (!empty($timecompleted->timecompleted)) {
$date = $timecompleted->timecompleted;
}
}
} else if ($certificate->printdate > 2) {
if ($modinfo = certificate_get_mod_grade($course, $certificate->printdate, $userid)) {
$date = $modinfo->dategraded;
}
}
if ($certificate->printdate > 0) {
if ($certificate->datefmt == 1) {
$certificatedate = userdate($date, '%B %d, %Y');
} else if ($certificate->datefmt == 2) {
$suffix = certificate_get_ordinal_number_suffix(userdate($date, '%d'));
$certificatedate = userdate($date, '%B %d' . $suffix . ', %Y');
} else if ($certificate->datefmt == 3) {
$certificatedate = userdate($date, '%d %B %Y');
} else if ($certificate->datefmt == 4) {
$certificatedate = userdate($date, '%B %Y');
} else if ($certificate->datefmt == 5) {
$certificatedate = userdate($date, get_string('strftimedate', 'langconfig'));
}
return $certificatedate;
}
return '';
}
/**
* Helper function to return the suffix of the day of
* the month, eg 'st' if it is the 1st of the month.
*
* @param int the day of the month
* @return string the suffix.
*/
function certificate_get_ordinal_number_suffix($day) {
if (!in_array(($day % 100), array(11, 12, 13))) {
switch ($day % 10) {
// Handle 1st, 2nd, 3rd
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
}
}
return 'th';
}
/**
* Returns the grade to display for the certificate.
*
* @param stdClass $certificate
* @param stdClass $course
* @param int $userid
* @param bool $valueonly if true return only the points, %age, or letter with no prefix
* @return string the grade result
*/
function certificate_get_grade($certificate, $course, $userid = null, $valueonly = false) {
global $USER;
if (empty($userid)) {
$userid = $USER->id;
}
if ($certificate->printgrade > 0) {
if ($certificate->printgrade == 1) {
if ($course_item = grade_item::fetch_course_item($course->id)) {
// Check we want to add a prefix to the grade.
$strprefix = '';
if (!$valueonly) {
$strprefix = get_string('coursegrade', 'certificate') . ': ';
}
$grade = new grade_grade(array('itemid' => $course_item->id, 'userid' => $userid));
$course_item->gradetype = GRADE_TYPE_VALUE;
$coursegrade = new stdClass;
$coursegrade->points = grade_format_gradevalue($grade->finalgrade, $course_item, true, GRADE_DISPLAY_TYPE_REAL, $decimals = 2);
$coursegrade->percentage = grade_format_gradevalue($grade->finalgrade, $course_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE, $decimals = 2);
$coursegrade->letter = grade_format_gradevalue($grade->finalgrade, $course_item, true, GRADE_DISPLAY_TYPE_LETTER, $decimals = 0);
if ($certificate->gradefmt == 1) {
$grade = $strprefix . $coursegrade->percentage;
} else if ($certificate->gradefmt == 2) {
$grade = $strprefix . $coursegrade->points;
} else if ($certificate->gradefmt == 3) {
$grade = $strprefix . $coursegrade->letter;
}
return $grade;
}
} else { // Print the mod grade
if ($modinfo = certificate_get_mod_grade($course, $certificate->printgrade, $userid)) {
// Check we want to add a prefix to the grade.
$strprefix = '';
if (!$valueonly) {
$strprefix = $modinfo->name . ' ' . get_string('grade', 'certificate') . ': ';
}
if ($certificate->gradefmt == 1) {
$grade = $strprefix . $modinfo->percentage;
} else if ($certificate->gradefmt == 2) {
$grade = $strprefix . $modinfo->points;
} else if ($certificate->gradefmt == 3) {
$grade = $strprefix . $modinfo->letter;
}
return $grade;
}
}
} else if ($certificate->printgrade < 0) { // Must be a category id.
if ($category_item = grade_item::fetch(array('itemtype' => 'category', 'iteminstance' => -$certificate->printgrade))) {
$category_item->gradetype = GRADE_TYPE_VALUE;
$grade = new grade_grade(array('itemid' => $category_item->id, 'userid' => $userid));
$category_grade = new stdClass;
$category_grade->points = grade_format_gradevalue($grade->finalgrade, $category_item, true, GRADE_DISPLAY_TYPE_REAL, $decimals = 2);
$category_grade->percentage = grade_format_gradevalue($grade->finalgrade, $category_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE, $decimals = 2);
$category_grade->letter = grade_format_gradevalue($grade->finalgrade, $category_item, true, GRADE_DISPLAY_TYPE_LETTER, $decimals = 0);
if ($certificate->gradefmt == 1) {
$formattedgrade = $category_grade->percentage;
} else if ($certificate->gradefmt == 2) {
$formattedgrade = $category_grade->points;
} else if ($certificate->gradefmt == 3) {
$formattedgrade = $category_grade->letter;
}
return $formattedgrade;
}
}
return '';
}
/**
* Returns the outcome to display on the certificate
*