-
Notifications
You must be signed in to change notification settings - Fork 46
/
locallib.php
2623 lines (2249 loc) · 102 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 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/>.
/**
* Simple Certificate module core interaction API
*
* @package mod
* @subpackage simplecertificate
* @copyright Carlos Alexandre Fonseca <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/simplecertificate/lib.php');
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/grade/lib.php');
require_once($CFG->dirroot . '/grade/querylib.php');
require_once($CFG->libdir . '/pdflib.php');
require_once($CFG->dirroot . '/user/profile/lib.php');
use core_availability\info;
use core_availability\info_module;
use core\message\inbound\private_files_handler;
class simplecertificate {
/**
* Module constats using in file storage.
* @var string componete name
*/
const CERTIFICATE_COMPONENT_NAME = 'mod_simplecertificate';
/**
* @var string filearea
*/
const CERTIFICATE_IMAGE_FILE_AREA = 'image';
/**
* @var string certificates filearea
*/
const CERTIFICATE_ISSUES_FILE_AREA = 'issues';
/**
* @var int
*/
const OUTPUT_OPEN_IN_BROWSER = 0;
/**
* @var int
*/
const OUTPUT_FORCE_DOWNLOAD = 1;
/**
* @var int
*/
const OUTPUT_SEND_EMAIL = 2;
/**
* @var array Charts not available in filename.
*/
const CHARS_NOT = ["á", "é", "í", "ó", "ú", "Á", "É", "Í", "Ó", "Ú", "ñ", "À", "Ã", "Ì", "Ò", "Ù", "Ù", "à ", "è", "ì",
"ò", "ù", "ç", "Ç", "â", "ê", "î", "ô", "û", "Â", "Ê", "ÃŽ", "Ô", "Û", "ü", "ö", "Ö", "ï",
"ä", "«", "Ò", "Ã", "Ä", "Ë", "ñ", "Ñ"];
/**
* @var array Charts to replace invalid chars in filename.
*/
const CHARS_YES = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U", "n", "N", "A", "E", "I", "O", "U", "a", "e", "i", "o",
"u", "c", "C", "a", "e", "i", "o", "u", "A", "E", "I", "O", "U", "u", "o", "O", "i", "a", "e", "U", "I",
"A", "E", "n", "N"];
// Date Options Const.
const CERT_ISSUE_DATE = -1;
const COURSE_COMPLETATION_DATE = -2;
const COURSE_START_DATE = -3;
// Grade Option Const.
const NO_GRADE = 0;
const COURSE_GRADE = -1;
// View const.
const DEFAULT_VIEW = 0;
const ISSUED_CERTIFCADES_VIEW = 1;
const BULK_ISSUE_CERTIFCADES_VIEW = 2;
// Pagination.
const SIMPLECERT_MAX_PER_PAGE = 200;
/**
*
* @var stdClass the assignment record that contains the global settings for this simplecertificate instance
*/
private $instance;
/**
*
* @var context the context of the course module for this simplecertificate instance
* (or just the course if we are creating a new one)
*/
private $context;
/**
*
* @var stdClass the course this simplecertificate instance belongs to
*/
private $course;
/**
*
* @var stdClass the course module for this simplecertificate instance
*/
private $coursemodule;
/**
*
* @var array cache for things like the coursemodule name or the scale menu -
* only lives for a single request.
*/
private $cache;
/**
*
* @var stdClass the current issued certificate
*/
private $issuecert;
/**
* Constructor for the base simplecertificate class.
*
* @param mixed $coursemodulecontext context|null the course module context
* (or the course context if the coursemodule has not been
* created yet).
* @param mixed $coursemodule the current course module if it was already loaded,
* otherwise this class will load one from the context as required.
* @param mixed $course the current course if it was already loaded,
* otherwise this class will load one from the context as required.
*/
public function __construct($coursemodulecontext, $coursemodule = null, $course = null) {
$this->context = $coursemodulecontext;
$this->coursemodule = $coursemodule;
$this->course = $course;
// Temporary cache only lives for a single request - used to reduce db lookups.
$this->cache = [];
}
/**
* Add this instance to the database.
*
* @param stdClass $formdata The data submitted from the form
* @param mod_simplecertificate_mod_form $mform the form object to get files
* @return mixed false if an error occurs or the int id of the new instance
*/
public function add_instance(stdClass $formdata) {
global $DB;
// Add the database record.
$update = $this->populate_simplecertificate_instance($formdata);
$update->timecreated = time();
$update->timemodified = $update->timecreated;
$returnid = $DB->insert_record('simplecertificate', $update, true);
$this->course = $DB->get_record('course', array('id' => $formdata->course), '*', MUST_EXIST);
$this->instance = $DB->get_record('simplecertificate', array('id' => $returnid), '*', MUST_EXIST);
if (!$this->instance) {
throw new moodle_exception('certificatenot', 'simplecertificate');
}
return $returnid;
}
/**
* Update this instance in the database.
*
* @param stdClass $formdata - the data submitted from the form
* @return bool false if an error occurs
*/
public function update_instance(stdClass $formdata) {
global $DB;
$update = $this->populate_simplecertificate_instance($formdata);
$update->timemodified = time();
$result = $DB->update_record('simplecertificate', $update);
if (!$DB->execute(
'UPDATE {simplecertificate_issues} SET haschange = 1 WHERE timedeleted is NULL AND certificateid = :certid',
array('certid' => $this->get_instance()->id))) {
throw new moodle_exception('cannotupdatemod', '', '', self::CERTIFICATE_COMPONENT_NAME,
'Error update simplecertificate, markig issues
with has change');
}
$this->instance = $DB->get_record('simplecertificate', array('id' => $update->id), '*', MUST_EXIST);
if (!$this->instance) {
throw new moodle_exception('certificatenot', 'simplecertificate');
}
return $result;
}
/**
* Delete this instance from the database.
*
* @return bool false if an error occurs
*/
public function delete_instance() {
global $DB;
try {
if ($this->get_instance()) {
// Delete issued certificates.
$this->remove_issues($this->get_instance());
// Delete files associated with this certificate.
$fs = get_file_storage();
if (!$fs->delete_area_files($this->get_context()->id)) {
return false;
}
// Delete the instance.
return $DB->delete_records('simplecertificate', ['id' => $this->get_instance()->id]);
}
return true;
} catch (moodle_exception $e) {
throw new moodle_exception($e->errorcode, $e->module, $e->link, $e->a, $e->debuginfo);
}
}
/**
* Remove all issued certificates for specified certificate id
*
* @param mixed stdClass/null $certificateisntance certificate object, certificate id or null
*/
protected function remove_issues($certificateisntance = null) {
global $DB;
try {
if (empty($certificateisntance)) {
$certificateisntance = $this->get_instance();
}
if ($issues = $DB->get_records_select('simplecertificate_issues',
'certificateid = :certificateid AND timedeleted is NULL',
array('certificateid' => $certificateisntance->id))) {
foreach ($issues as $issue) {
if (!$this->remove_issue($issue)) {
// TODO add exception msg.
throw new moodle_exception('TODO');
}
}
}
} catch (Exception $e) {
throw $e;
}
}
/**
* Remove an issue certificate
*
* @param stdClass $issue Issue certificate object
* @param boolean $movecertfile Move the certificate file to usuer private folder (defaul true)
* @return bool true if removed
*/
protected function remove_issue(stdClass $issue, $movecertfile = true) {
global $DB;
// Try to move certificate to users private file area.
try {
// Try to get issue file.
if (!$this->issue_file_exists($issue)) {
throw new moodle_exception('filenotfound', 'simplecertificate', null, null, 'issue id:[' . $issue->id . ']');
}
$fs = get_file_storage();
// Do not use $this->get_issue_file($issue), it has many functions calls.
$file = $fs->get_file_by_hash($issue->pathnamehash);
// Try get user context.
$userctx = context_user::instance($issue->userid);
if (!$userctx) {
throw new moodle_exception('usercontextnotfound', 'simplecertificate',
null, null, 'userid [' . $issue->userid . ']');
}
// Check if it's to move certificate file or not.
if ($movecertfile) {
$coursename = $issue->coursename;
$fileinfo = array(
'contextid' => $userctx->id,
'component' => 'user',
'filearea' => 'private',
'itemid' => $issue->certificateid,
'filepath' => '/certificates/' . $coursename . '/',
'filename' => $file->get_filename());
if (!$fs->file_exists($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'],
$fileinfo['filepath'], $fileinfo['filename'])) {
$newfile = $fs->create_file_from_storedfile($fileinfo, $file);
if ($newfile) {
$issue->pathnamehash = $newfile->get_pathnamehash();
} else {
throw new moodle_exception('cannotsavefile', null, null, null, $file->get_filename());
}
}
} else {
$file->delete();
}
} catch (moodle_exception $e) {
debugging($e->getMessage(), DEBUG_DEVELOPER, $e->getTrace());
$issue->pathnamehash = '';
}
try {
if ($movecertfile) {
$issue->timedeleted = time();
return $DB->update_record('simplecertificate_issues', $issue);
} else {
return $DB->delete_records('simplecertificate_issues', array('id' => $issue->id));
}
} catch (Exception $e) {
throw $e;
}
}
/**
* Get the settings for the current instance of this certificate
*
* @return stdClass The settings
*/
public function get_instance() {
global $DB;
if (!isset($this->instance)) {
$cm = $this->get_course_module();
if ($cm) {
$params = ['id' => $cm->instance];
$this->instance = $DB->get_record('simplecertificate', $params, '*', MUST_EXIST);
}
if (!$this->instance) {
throw new coding_exception('Improper use of the simplecertificate class. ' .
'Cannot load the simplecertificate record.');
}
}
if (empty($this->instance->coursename)) {
$this->instance->coursename = $this->get_course()->fullname;
}
return $this->instance;
}
/**
* Get context module.
*
* @return context
*/
public function get_context() {
return $this->context;
}
/**
* Get issue cert.
*
* @return context
*/
public function get_issuecert() {
return $this->issuecert;
}
/**
* Get the current course.
*
* @return mixed stdClass|null The course
*/
public function get_course() {
global $DB;
if ($this->course) {
return $this->course;
}
if (!$this->context) {
return null;
}
$params = ['id' => $this->get_course_context()->instanceid];
$this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
return $this->course;
}
/**
* Get the context of the current course.
*
* @return mixed context|null The course context
*/
public function get_course_context() {
if (!$this->context && !$this->course) {
throw new coding_exception('Improper use of the simplecertificate class. ' . 'Cannot load the course context.');
}
if ($this->context) {
return $this->context->get_course_context();
} else {
return context_course::instance($this->course->id);
}
}
/**
* Get the current course module.
*
* @return mixed stdClass|null The course module
*/
public function get_course_module() {
if ($this->coursemodule) {
return $this->coursemodule;
}
if ($this->context && $this->context->contextlevel == CONTEXT_MODULE) {
$this->coursemodule = get_coursemodule_from_id('simplecertificate', $this->context->instanceid, 0, false, MUST_EXIST);
return $this->coursemodule;
}
return null;
}
/**
* Set the submitted form data.
*
* @param stdClass $data The form data (instance)
*/
public function set_instance(stdClass $data) {
$this->instance = $data;
}
/**
* Set issue cert.
*
* @param stdClass $issuecert The issue certificate object.
*/
public function set_issuecert($issuecert) {
$this->issuecert = $issuecert;
}
/**
* Set the context.
*
* @param context $context The new context
*/
public function set_context(context $context) {
$this->context = $context;
}
/**
* Set the course data.
*
* @param stdClass $course The course data
*/
public function set_course(stdClass $course) {
$this->course = $course;
}
/**
*
* @param stdClass $formdata The data submitted from the form
* @param mod_simplecertificate_mod_form $mform The form object to get files
* @return stdClass The simplecertificate instance object
*/
private function populate_simplecertificate_instance(stdclass $formdata) {
// Clear image filearea.
$fs = get_file_storage();
$fs->delete_area_files($this->get_context()->id, self::CERTIFICATE_COMPONENT_NAME, self::CERTIFICATE_IMAGE_FILE_AREA);
// Creating a simplecertificate instace object.
$update = new stdClass();
if (isset($formdata->certificatetext['text'])) {
$update->certificatetext = $formdata->certificatetext['text'];
if (!isset($formdata->certificatetextformat)) {
$update->certificatetextformat = $formdata->certificatetext['format'];
}
unset($formdata->certificatetext);
}
if (isset($formdata->secondpagetext['text'])) {
$update->secondpagetext = $formdata->secondpagetext['text'];
if (!isset($formdata->secondpagetextformat)) {
$update->secondpagetextformat = $formdata->secondpagetext['format'];
}
unset($formdata->secondpagetext);
} else if (is_array($formdata->secondpagetext)) {
$update->secondpagetext = '';
unset($formdata->secondpagetext);
}
if (isset($formdata->certificateimage)) {
if (!empty($formdata->certificateimage)) {
$fileinfo = self::get_certificate_image_fileinfo($this->context->id);
$formdata->certificateimage = $this->save_upload_file($formdata->certificateimage, $fileinfo);
}
} else {
$formdata->certificateimage = null;
}
if (isset($formdata->secondimage)) {
if (!empty($formdata->secondimage)) {
$fileinfo = self::get_certificate_secondimage_fileinfo($this->context->id);
$formdata->secondimage = $this->save_upload_file($formdata->secondimage, $fileinfo);
}
} else {
$formdata->secondimage = null;
}
foreach ($formdata as $name => $value) {
$update->{$name} = $value;
}
if (isset($formdata->instance)) {
$update->id = $formdata->instance;
unset($update->instance);
}
return $update;
}
/**
* Save upload files in $fileinfo array and return the filename
*
* @param string $formitemid Upload file form id
* @param array $fileinfo The file info array, where to store uploaded file
* @return string filename
*/
private function save_upload_file($formitemid, array $fileinfo) {
// Clear file area.
if (empty($fileinfo['itemid'])) {
$fileinfo['itemid'] = '';
}
$fs = get_file_storage();
$fs->delete_area_files($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid']);
file_save_draft_area_files($formitemid, $fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
$fileinfo['itemid']);
// Get only files, not directories.
$files = $fs->get_area_files($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], '',
false);
$file = array_shift($files);
return $file->get_filename();
}
/**
* Get the first page background image fileinfo
*
* @param mixed $context The module context object or id
* @return the first page background image fileinfo
*/
public static function get_certificate_image_fileinfo($context) {
if (is_object($context)) {
$contextid = $context->id;
} else {
$contextid = $context;
}
return [
'contextid' => $contextid, // ID of context
'component' => self::CERTIFICATE_COMPONENT_NAME, // Usually = table name.
'filearea' => self::CERTIFICATE_IMAGE_FILE_AREA, // Usually = table name.
'itemid' => 1, // Usually = ID of row in table.
'filepath' => '/'
]; // Any path beginning and ending in /.
}
/**
* Get the second page background image fileinfo
*
* @param mixed $context The module context object or id
* @return the second page background image fileinfo
*/
public static function get_certificate_secondimage_fileinfo($context) {
$fileinfo = self::get_certificate_image_fileinfo($context);
$fileinfo['itemid'] = 2;
return $fileinfo;
}
/**
* Get the temporary filearea, used to store user
* profile photos to make the certiticate
*
* @param int/object $context The module context
* @return the temporary fileinfo
*/
public static function get_certificate_tmp_fileinfo($context) {
if (is_object($context)) {
$contextid = $context->id;
} else {
$contextid = $context;
}
return [
'contextid' => $contextid,
'component' => self::CERTIFICATE_COMPONENT_NAME,
'filearea' => 'tmp',
'itemid' => 0,
'filepath' => '/'
];
}
/**
* Get issued certificate object, if it's not exist, it will be create
*
* @param mixed User obj or id
* @param boolean Issue teh user certificate if it's not exists (default = true)
* @return stdClass the issue certificate object
*/
public function get_issue($user = null, $issueifempty = true) {
global $DB, $USER;
if (empty($user)) {
$userid = $USER->id;
} else {
if (is_object($user)) {
$userid = $user->id;
} else {
$userid = $user;
}
}
// Check if certificate has already issued.
// Trying cached first.
// The cache issue is from this user ?
$created = false;
if (!empty($this->issuecert) && $this->issuecert->userid == $userid) {
if (empty($this->issuecert->haschange)) {
// ...haschange is marked, if no return from cache.
return $this->issuecert;
} else {
// ...haschange is maked, must update.
$issuedcert = $this->issuecert;
}
// Not in cache, trying get from database.
} else if (!$issuedcert = $DB->get_record('simplecertificate_issues',
['userid' => $userid, 'certificateid' => $this->get_instance()->id, 'timedeleted' => null])) {
// Not in cache and not in DB, create new certificate issue record.
if (!$issueifempty) {
// Not create a new one, only check if exists.
return null;
}
// Mark as created.
$created = true;
$issuedcert = new stdClass();
$issuedcert->certificateid = $this->get_instance()->id;
$issuedcert->coursename = format_string($this->get_instance()->coursename, true);
$issuedcert->userid = $userid;
$issuedcert->haschange = 1;
$formatedcoursename = str_replace('-', '_', $this->get_instance()->coursename);
$formatedcertificatename = str_replace('-', '_', $this->get_instance()->name);
$issuedcert->certificatename = format_string($formatedcoursename . '-' . $formatedcertificatename, true);
$issuedcert->timecreated = time();
$issuedcert->code = $this->get_issue_uuid();
// Avoiding not null restriction.
$issuedcert->pathnamehash = '';
if (has_capability('mod/simplecertificate:manage', $this->context, $userid)) {
$issuedcert->id = 0;
} else {
$issuedcert->id = $DB->insert_record('simplecertificate_issues', $issuedcert);
// Email to the teachers and anyone else.
if (!empty($this->get_instance()->emailteachers)) {
$this->send_alert_email_teachers();
}
if (!empty($this->get_instance()->emailothers)) {
$this->send_alert_email_others();
}
}
}
// If cache or db issued certificate is maked as haschange, must update.
if (!empty($issuedcert->haschange) && !$created) { // Check haschange, if so, reissue.
$formatedcoursename = str_replace('-', '_', $this->get_instance()->coursename);
$formatedcertificatename = str_replace('-', '_', $this->get_instance()->name);
$issuedcert->certificatename = format_string($formatedcoursename . '-' . $formatedcertificatename, true);
$DB->update_record('simplecertificate_issues', $issuedcert);
}
// Caching to avoid unessecery db queries.
$this->issuecert = $issuedcert;
return $issuedcert;
}
/**
* Returns a list of previously issued certificates--used for reissue.
*
* @param int $certificateid
* @return stdClass the attempts else false if none found
*/
public function get_attempts() {
global $DB, $USER;
$sql = "SELECT *
FROM {simplecertificate_issues} i
WHERE certificateid = :certificateid
AND userid = :userid AND timedeleted IS NULL";
$issues = $DB->get_records_sql($sql, array('certificateid' => $this->get_instance()->id, 'userid' => $USER->id));
if ($issues) {
return $issues;
}
return false;
}
/**
* Prints a table of previously issued certificates--used for reissue.
*
* @param stdClass $attempts
* @return string the attempt table
*/
public function print_attempts($attempts) {
global $OUTPUT;
echo $OUTPUT->heading(get_string('summaryofattempts', 'simplecertificate'));
// Prepare table header.
$table = new html_table();
$table->class = 'generaltable';
$table->head = array(get_string('issued', 'simplecertificate'));
$table->align = array('left');
$table->attributes = array("style" => "width:20%; margin:auto");
$gradecolumn = $this->get_instance()->certgrade;
if ($gradecolumn) {
$table->head[] = get_string('grade', 'grades');
$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 = $this->get_grade();
$row[] = $attemptgrade;
}
$table->data[$attempt->id] = $row;
}
echo html_writer::table($table);
}
/**
* Returns the grade to display for the certificate.
*
* @param int $userid
* @return string the grade result
*/
protected function get_grade($userid = null) {
global $USER;
if (empty($userid)) {
$userid = $USER->id;
}
// If certgrade = 0 return nothing.
if (empty($this->get_instance()->certgrade)) { // No grade.
return '';
}
switch ($this->get_instance()->certgrade) {
case self::COURSE_GRADE: // Course grade.
$courseitem = grade_item::fetch_course_item($this->get_course()->id);
if ($courseitem) {
$grade = new grade_grade(array('itemid' => $courseitem->id, 'userid' => $userid));
$courseitem->gradetype = GRADE_TYPE_VALUE;
$coursegrade = new stdClass();
$decimals = $courseitem->get_decimals();
// If no decimals is set get the default decimals.
if (empty($decimals)) {
$decimals = 2;
}
// String used.
$coursegrade->points = grade_format_gradevalue(
$grade->finalgrade, $courseitem, true, GRADE_DISPLAY_TYPE_REAL, $decimals
);
$coursegrade->percentage = grade_format_gradevalue(
$grade->finalgrade, $courseitem, true, GRADE_DISPLAY_TYPE_PERCENTAGE, $decimals
);
$coursegrade->letter = grade_format_gradevalue(
$grade->finalgrade, $courseitem, true, GRADE_DISPLAY_TYPE_LETTER, $decimals = 0
);
}
break;
default: // Module grade.
// Get grade from a specific module, stored at certgrade.
$modinfo = $this->get_mod_grade($this->get_instance()->certgrade, $userid);
if ($modinfo) {
// String used.
$coursegrade = new stdClass();
$coursegrade->points = $modinfo->points;
$coursegrade->percentage = $modinfo->percentage;
$coursegrade->letter = $modinfo->letter;
break;
}
}
return $this->get_formated_grade($coursegrade);
}
private function get_formated_grade(stdClass $coursegrade) {
if (empty($coursegrade)) {
return '';
}
switch ($this->get_instance()->gradefmt) {
case 1:
return $coursegrade->percentage;
break;
case 3:
return $coursegrade->letter;
break;
default:
return $coursegrade->points;
break;
}
}
/**
* Prepare to print an activity grade.
*
* @param int $moduleid
* @param int $userid
* @return stdClass bool the mod object if it exists, false otherwise
*/
protected function get_mod_grade($moduleid, $userid) {
global $DB;
$cm = $DB->get_record('course_modules', ['id' => $moduleid]);
// The module may no longer exist if it was deleted.
if (!$cm) {
return false;
}
$module = $DB->get_record('modules', ['id' => $cm->module]);
$gradeitem = grade_get_grades($this->get_course()->id, 'mod', $module->name, $cm->instance, $userid);
if ($gradeitem) {
$item = new grade_item();
$itemproperties = reset($gradeitem->items);
foreach ($itemproperties as $key => $value) {
$item->$key = $value;
}
$modinfo = new stdClass();
$modinfo->name = utf8_decode($DB->get_field($module->name, 'name', ['id' => $cm->instance]));
$grade = $item->grades[$userid]->grade;
$item->gradetype = GRADE_TYPE_VALUE;
$item->courseid = $this->get_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;
}
/**
* Generate a V4 UUID.
*
* @see https://tools.ietf.org/html/rfc4122
*
* @return string UUID
*/
protected function get_issue_uuid() {
global $CFG;
require_once($CFG->libdir . '/classes/uuid.php');
return \core\uuid::generate();
}
/**
* Returns a list of teachers by group
* for sending email alerts to teachers
*
* @return array the teacher array
*/
protected function get_teachers() {
global $CFG, $DB;
$teachers = array();
if (!empty($CFG->coursecontact)) {
$coursecontactroles = explode(',', $CFG->coursecontact);
} else {
list($coursecontactroles, $trash) = get_roles_with_cap_in_context($this->get_context(), 'mod/simplecertificate:manage');
}
foreach ($coursecontactroles as $roleid) {
$roleid = (int)$roleid;
$role = $DB->get_record('role', array('id' => $roleid));
$users = get_role_users($roleid, $this->context, true);
if ($users) {
foreach ($users as $teacher) {
$manager = new stdClass();
$manager->user = $teacher;
$manager->username = fullname($teacher);
$manager->rolename = role_get_name($role, $this->get_context());
$teachers[$teacher->id] = $manager;
}
}
}
return $teachers;
}
/**
* Alerts teachers by email of received certificates.
* First checks whether the option to email teachers is set for this certificate.
*/
protected function send_alert_email_teachers() {
$teachers = $this->get_teachers();
if (!empty($this->get_instance()->emailteachers) && $teachers) {
$emailteachers = array();
foreach ($teachers as $teacher) {
$emailteachers[] = $teacher->user->email;
}
$this->send_alert_emails($emailteachers);
}
}
/**
* Alerts others by email of received certificates.
* First checks whether the option to email others is set for this certificate.
*/
protected function send_alert_email_others() {
if (!empty($this->get_instance()->emailothers)) {
$others = explode(',', $this->get_instance()->emailothers);
if ($others) {
$this->send_alert_emails($others);
}
}
}
/**
* Send Alerts email of received certificates
*
* @param array $emails emails arrays
*/
protected function send_alert_emails($emails) {
global $USER, $CFG;
if (!empty($emails)) {
$url = new moodle_url($CFG->wwwroot . '/mod/simplecertificate/view.php',
array('id' => $this->coursemodule->id, 'tab' => self::ISSUED_CERTIFCADES_VIEW));
foreach ($emails as $email) {
$email = trim($email);
if (validate_email($email)) {
$destination = new stdClass();
$destination->email = $email;
$destination->id = rand(-10, -1);
$info = new stdClass();
$info->student = fullname($USER);
$info->course = format_string($this->get_instance()->coursename, true);
$info->certificate = format_string($this->get_instance()->name, true);
$info->url = $url->out();
$from = $info->student;