forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
badgeslib.php
1569 lines (1368 loc) · 54.4 KB
/
badgeslib.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/>.
/**
* Contains classes, functions and constants used in badges.
*
* @package core
* @subpackage badges
* @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Yuliya Bozhko <[email protected]>
*/
defined('MOODLE_INTERNAL') || die();
/* Include required award criteria library. */
require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
/* Include required user badge exporter */
use core_badges\external\user_badge_exporter;
/* Include required badge class exporter */
use core_badges\external\badgeclass_exporter;
/*
* Number of records per page.
*/
define('BADGE_PERPAGE', 50);
/*
* Badge award criteria aggregation method.
*/
define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
/*
* Badge award criteria aggregation method.
*/
define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
/*
* Inactive badge means that this badge cannot be earned and has not been awarded
* yet. Its award criteria can be changed.
*/
define('BADGE_STATUS_INACTIVE', 0);
/*
* Active badge means that this badge can we earned, but it has not been awarded
* yet. Can be deactivated for the purpose of changing its criteria.
*/
define('BADGE_STATUS_ACTIVE', 1);
/*
* Inactive badge can no longer be earned, but it has been awarded in the past and
* therefore its criteria cannot be changed.
*/
define('BADGE_STATUS_INACTIVE_LOCKED', 2);
/*
* Active badge means that it can be earned and has already been awarded to users.
* Its criteria cannot be changed any more.
*/
define('BADGE_STATUS_ACTIVE_LOCKED', 3);
/*
* Archived badge is considered deleted and can no longer be earned and is not
* displayed in the list of all badges.
*/
define('BADGE_STATUS_ARCHIVED', 4);
/*
* Badge type for site badges.
*/
define('BADGE_TYPE_SITE', 1);
/*
* Badge type for course badges.
*/
define('BADGE_TYPE_COURSE', 2);
/*
* Badge messaging schedule options.
*/
define('BADGE_MESSAGE_NEVER', 0);
define('BADGE_MESSAGE_ALWAYS', 1);
define('BADGE_MESSAGE_DAILY', 2);
define('BADGE_MESSAGE_WEEKLY', 3);
define('BADGE_MESSAGE_MONTHLY', 4);
/*
* URL of backpack. Custom ones can be added.
*/
define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
/**
* @deprecated since Moodle 4.5.
* @todo Final deprecation in Moodle 6.0. See MDL-82332.
*/
define('OPEN_BADGES_V1', 1);
/*
* Open Badges specifications.
*/
define('OPEN_BADGES_V2', 2);
define('OPEN_BADGES_V2P1', 2.1);
/*
* Only use for Open Badges 2.0 specification
*/
define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
define('BACKPACK_MOVE_UP', -1);
define('BACKPACK_MOVE_DOWN', 1);
// Global badge class has been moved to the component namespace.
class_alias('\core_badges\badge', 'badge');
/**
* Sends notifications to users about awarded badges.
*
* @param \core_badges\badge $badge Badge that was issued
* @param int $userid Recipient ID
* @param string $issued Unique hash of an issued badge
* @param string $filepathhash File path hash of an issued badge for attachments
*/
function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
global $CFG, $DB;
$admin = get_admin();
$userfrom = new stdClass();
$userfrom->id = $admin->id;
$userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
foreach (\core_user\fields::get_name_fields() as $addname) {
$userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
}
$userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
$userfrom->maildisplay = true;
$badgeurl = new moodle_url('/badges/badge.php', ['hash' => $issued]);
$issuedlink = html_writer::link($badgeurl, $badge->name);
$userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
$params = new stdClass();
$params->badgename = $badge->name;
$params->username = fullname($userto);
$params->badgelink = $issuedlink;
$message = badge_message_from_template($badge->message, $params);
$plaintext = html_to_text($message);
// Notify recipient.
$eventdata = new \core\message\message();
$eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
$eventdata->component = 'moodle';
$eventdata->name = 'badgerecipientnotice';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $userto;
$eventdata->notification = 1;
$eventdata->contexturl = $badgeurl;
$eventdata->contexturlname = $badge->name;
$eventdata->subject = $badge->messagesubject;
$eventdata->fullmessage = $plaintext;
$eventdata->fullmessageformat = FORMAT_HTML;
$eventdata->fullmessagehtml = $message;
$eventdata->smallmessage = '';
$eventdata->customdata = [
'notificationiconurl' => moodle_url::make_pluginfile_url(
$badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
'hash' => $issued,
];
// Attach badge image if possible.
if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
$fs = get_file_storage();
$file = $fs->get_file_by_hash($filepathhash);
$eventdata->attachment = $file;
$eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
message_send($eventdata);
} else {
message_send($eventdata);
}
// Notify badge creator about the award if they receive notifications every time.
if ($badge->notification == 1) {
$userfrom = core_user::get_noreply_user();
$userfrom->maildisplay = true;
$creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
$a = new stdClass();
$a->user = fullname($userto);
$a->link = $issuedlink;
$creatormessage = get_string('creatorbody', 'badges', $a);
$creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
$eventdata = new \core\message\message();
$eventdata->courseid = $badge->courseid;
$eventdata->component = 'moodle';
$eventdata->name = 'badgecreatornotice';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $creator;
$eventdata->notification = 1;
$eventdata->contexturl = $badgeurl;
$eventdata->contexturlname = $badge->name;
$eventdata->subject = $creatorsubject;
$eventdata->fullmessage = html_to_text($creatormessage);
$eventdata->fullmessageformat = FORMAT_HTML;
$eventdata->fullmessagehtml = $creatormessage;
$eventdata->smallmessage = '';
$eventdata->customdata = [
'notificationiconurl' => moodle_url::make_pluginfile_url(
$badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
'hash' => $issued,
];
message_send($eventdata);
$DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
}
}
/**
* Caclulates date for the next message digest to badge creators.
*
* @param int $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
* @return int Timestamp for next cron
*/
function badges_calculate_message_schedule($schedule) {
$nextcron = 0;
switch ($schedule) {
case BADGE_MESSAGE_DAILY:
$tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
$nextcron = $tomorrow->getTimestamp();
break;
case BADGE_MESSAGE_WEEKLY:
$nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
$nextcron = $nextweek->getTimestamp();
break;
case BADGE_MESSAGE_MONTHLY:
$nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
$nextcron = $nextmonth->getTimestamp();
break;
}
return $nextcron;
}
/**
* Replaces variables in a message template and returns text ready to be emailed to a user.
*
* @param string $message Message body.
* @return string Message with replaced values
*/
function badge_message_from_template($message, $params) {
$msg = $message;
foreach ($params as $key => $value) {
$msg = str_replace("%$key%", $value, $msg);
}
return $msg;
}
/**
* Get all badges.
*
* @param int Type of badges to return
* @param int Course ID for course badges
* @param string $sort An SQL field to sort by
* @param string $dir The sort direction ASC|DESC
* @param int $page The page or records to return
* @param int $perpage The number of records to return per page
* @param int $user User specific search
* @return array $badge Array of records matching criteria
*/
function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
global $DB;
$records = array();
$params = array();
$where = "b.status != :deleted AND b.type = :type ";
$params['deleted'] = BADGE_STATUS_ARCHIVED;
$userfields = array('b.id, b.name, b.status');
$usersql = "";
if ($user != 0) {
$userfields[] = 'bi.dateissued';
$userfields[] = 'bi.uniquehash';
$usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
$params['userid'] = $user;
$where .= " AND (b.status = 1 OR b.status = 3) ";
}
$fields = implode(', ', $userfields);
if ($courseid != 0 ) {
$where .= "AND b.courseid = :courseid ";
$params['courseid'] = $courseid;
}
$sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
$params['type'] = $type;
$sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
$records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
$badges = array();
foreach ($records as $r) {
$badge = new badge($r->id);
$badges[$r->id] = $badge;
if ($user != 0) {
$badges[$r->id]->dateissued = $r->dateissued;
$badges[$r->id]->uniquehash = $r->uniquehash;
} else {
$badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
$badges[$r->id]->statstring = $badge->get_status_name();
}
}
return $badges;
}
/**
* Get badges for a specific user.
*
* @param int $userid User ID
* @param int $courseid Badges earned by a user in a specific course
* @param int $page The page or records to return
* @param int $perpage The number of records to return per page
* @param string $search A simple string to search for
* @param bool $onlypublic Return only public badges
* @return array of badges ordered by decreasing date of issue
*/
function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
global $CFG, $DB;
$params = array(
'userid' => $userid
);
$sql = 'SELECT
bi.uniquehash,
bi.dateissued,
bi.dateexpire,
bi.id as issuedid,
bi.visible,
u.email,
b.*
FROM
{badge} b,
{badge_issued} bi,
{user} u
WHERE b.id = bi.badgeid
AND u.id = bi.userid
AND bi.userid = :userid';
if (!empty($search)) {
$sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
$params['search'] = '%'.$DB->sql_like_escape($search).'%';
}
if ($onlypublic) {
$sql .= ' AND (bi.visible = 1) ';
}
if (empty($CFG->badges_allowcoursebadges)) {
$sql .= ' AND b.courseid IS NULL';
} else if ($courseid != 0) {
$sql .= ' AND (b.courseid = :courseid) ';
$params['courseid'] = $courseid;
}
$sql .= ' ORDER BY bi.dateissued DESC';
$badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
return $badges;
}
/**
* Get badge by hash.
*
* @param string $hash
* @return object|bool
*/
function badges_get_badge_by_hash(string $hash): object|bool {
global $DB;
$sql = 'SELECT
bi.uniquehash,
bi.dateissued,
bi.userid,
bi.dateexpire,
bi.id as issuedid,
bi.visible,
u.email,
b.*
FROM
{badge} b,
{badge_issued} bi,
{user} u
WHERE b.id = bi.badgeid
AND u.id = bi.userid
AND ' . $DB->sql_compare_text('bi.uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40);
$badge = $DB->get_record_sql($sql, ['hash' => $hash], IGNORE_MISSING);
return $badge;
}
/**
* Update badge instance to external functions.
*
* @param stdClass $badge
* @param stdClass $user
* @return object
*/
function badges_prepare_badge_for_external(stdClass $badge, stdClass $user): object {
global $PAGE, $SITE, $USER;
if ($badge->type == BADGE_TYPE_SITE) {
$context = context_system::instance();
} else {
$context = context_course::instance($badge->courseid);
}
$canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
// If the user is viewing another user's badge and doesn't have the right capability return only part of the data.
if ($USER->id != $user->id && !$canconfiguredetails) {
$badge = (object) [
'id' => $badge->id,
'name' => $badge->name,
'type' => $badge->type,
'description' => $badge->description,
'issuername' => $badge->issuername,
'issuerurl' => $badge->issuerurl,
'issuercontact' => $badge->issuercontact,
'uniquehash' => $badge->uniquehash,
'dateissued' => $badge->dateissued,
'dateexpire' => $badge->dateexpire,
'version' => $badge->version,
'language' => $badge->language,
'imageauthorname' => $badge->imageauthorname,
'imageauthoremail' => $badge->imageauthoremail,
'imageauthorurl' => $badge->imageauthorurl,
'imagecaption' => $badge->imagecaption,
];
}
// Recipient (the badge was awarded to this person).
$badge->recipientid = $user->id;
if ($user->deleted) {
$strdata = new stdClass();
$strdata->user = fullname($user);
$strdata->site = format_string($SITE->fullname, true, ['context' => context_system::instance()]);
$badge->recipientfullname = get_string('error:userdeleted', 'badges', $strdata);
} else {
$badge->recipientfullname = fullname($user);
}
// Create a badge instance to be able to get the endorsement and other info.
$badgeinstance = new badge($badge->id);
$endorsement = $badgeinstance->get_endorsement();
$alignments = $badgeinstance->get_alignments();
$relatedbadges = $badgeinstance->get_related_badges();
if (!$canconfiguredetails) {
// Return only the properties visible by the user.
if (!empty($alignments)) {
foreach ($alignments as $alignment) {
unset($alignment->targetdescription);
unset($alignment->targetframework);
unset($alignment->targetcode);
}
}
if (!empty($relatedbadges)) {
foreach ($relatedbadges as $relatedbadge) {
unset($relatedbadge->version);
unset($relatedbadge->language);
unset($relatedbadge->type);
}
}
}
$related = [
'context' => $context,
'endorsement' => $endorsement ? $endorsement : null,
'alignment' => $alignments,
'relatedbadges' => $relatedbadges,
];
$exporter = new user_badge_exporter($badge, $related);
return $exporter->export($PAGE->get_renderer('core'));
}
/**
* Prepare badgeclass for external functions.
* @param core_badges\output\badgeclass $badgeclass
* @return stdClass
*/
function badges_prepare_badgeclass_for_external(core_badges\output\badgeclass $badgeclass): stdClass {
global $PAGE;
$context = $badgeclass->context;
$badgeurl = new \moodle_url('/badges/badgeclass.php', [
'id' => $badgeclass->badge->id,
]);
$badgeurl = $badgeurl->out(false);
$file = \moodle_url::make_webservice_pluginfile_url(
$badgeclass->context->id,
'badges',
'badgeimage',
$badgeclass->badge->id,
'/',
'f3'
);
$image = $file->out(false);
$badge = (object) [
'id' => $badgeurl,
'name' => $badgeclass->badge->name,
'type' => OPEN_BADGES_V2_TYPE_BADGE,
'description' => $badgeclass->badge->description,
'issuer' => $badgeclass->badge->issuername,
'hostedUrl' => $badgeclass->badge->issuerurl,
'image' => $image,
];
// Create a badge instance to be able to get the endorsement and other info.
$badgeinstance = new badge($badgeclass->badge->id);
$endorsement = $badgeinstance->get_endorsement();
$alignments = $badgeinstance->get_alignments();
$relatedbadges = $badgeinstance->get_related_badges();
$canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
if (!$canconfiguredetails) {
// Return only the properties visible by the user.
if (!empty($alignments)) {
foreach ($alignments as $alignment) {
unset($alignment->targetdescription);
unset($alignment->targetframework);
unset($alignment->targetcode);
}
}
if (!empty($relatedbadges)) {
foreach ($relatedbadges as $relatedbadge) {
unset($relatedbadge->version);
unset($relatedbadge->language);
unset($relatedbadge->type);
}
}
}
$related = [
'context' => $context,
'endorsement' => $endorsement ? $endorsement : null,
'relatedbadges' => $relatedbadges,
];
if (!empty($alignments)) {
$related['alignment'] = $alignments;
}
$exporter = new badgeclass_exporter($badge, $related);
return $exporter->export($PAGE->get_renderer('core', 'badges'));
}
/**
* Extends the course administration navigation with the Badges page
*
* @param navigation_node $coursenode
* @param object $course
*/
function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
global $CFG, $SITE;
$coursecontext = context_course::instance($course->id);
$isfrontpage = (!$coursecontext || $course->id == $SITE->id);
$canmanage = has_any_capability(array('moodle/badges:viewawarded',
'moodle/badges:createbadge',
'moodle/badges:awardbadge',
'moodle/badges:configurecriteria',
'moodle/badges:configuremessages',
'moodle/badges:configuredetails',
'moodle/badges:deletebadge'), $coursecontext);
if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
$coursenode->add(get_string('coursebadges', 'badges'), null,
navigation_node::TYPE_CONTAINER, null, 'coursebadges',
new pix_icon('i/badge', get_string('coursebadges', 'badges')));
$url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
$coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
navigation_node::TYPE_SETTING, null, 'coursebadges');
if (has_capability('moodle/badges:createbadge', $coursecontext)) {
$url = new moodle_url('/badges/edit.php', ['action' => 'new', 'courseid' => $course->id]);
$coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
navigation_node::TYPE_SETTING, null, 'newbadge');
}
}
}
/**
* Triggered when badge is manually awarded.
*
* @param object $data
* @return boolean
*/
function badges_award_handle_manual_criteria_review(stdClass $data) {
$criteria = $data->crit;
$userid = $data->userid;
$badge = new badge($criteria->badgeid);
if (!$badge->is_active() || $badge->is_issued($userid)) {
return true;
}
if ($criteria->review($userid)) {
$criteria->mark_complete($userid);
if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
$badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
$badge->issue($userid);
}
}
return true;
}
/**
* Process badge image from form data
*
* @param badge $badge Badge object
* @param string $iconfile Original file
*/
function badges_process_badge_image(badge $badge, $iconfile) {
global $CFG, $USER;
require_once($CFG->libdir. '/gdlib.php');
if (!empty($CFG->gdversion)) {
process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
@unlink($iconfile);
// Clean up file draft area after badge image has been saved.
$context = context_user::instance($USER->id, MUST_EXIST);
$fs = get_file_storage();
$fs->delete_area_files($context->id, 'user', 'draft');
}
}
/**
* Print badge image.
*
* @param badge $badge Badge object
* @param stdClass $context
* @param string $size
*/
function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
$fsize = ($size == 'small') ? 'f2' : 'f1';
$imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
// Appending a random parameter to image link to forse browser reload the image.
$imageurl->param('refresh', rand(1, 10000));
$attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
return html_writer::empty_tag('img', $attributes);
}
/**
* Bake issued badge.
*
* @param string $hash Unique hash of an issued badge.
* @param int $badgeid ID of the original badge.
* @param int $userid ID of badge recipient (optional).
* @param boolean $pathhash Return file pathhash instead of image url (optional).
* @return string|moodle_url|null Returns either new file path hash or new file URL
*/
function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
global $CFG, $USER;
require_once(__DIR__ . '/../badges/lib/bakerlib.php');
$badge = new badge($badgeid);
$badge_context = $badge->get_context();
$userid = ($userid) ? $userid : $USER->id;
$user_context = context_user::instance($userid);
$fs = get_file_storage();
if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
$contents = $file->get_content();
$filehandler = new PNG_MetaDataHandler($contents);
// For now, the site backpack OB version will be used as default.
$obversion = badges_open_badges_backpack_api();
$assertion = new core_badges_assertion($hash, $obversion);
$assertionjson = json_encode($assertion->get_badge_assertion());
if ($filehandler->check_chunks("iTXt", "openbadges")) {
// Add assertion URL iTXt chunk.
$newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
$fileinfo = array(
'contextid' => $user_context->id,
'component' => 'badges',
'filearea' => 'userbadge',
'itemid' => $badge->id,
'filepath' => '/',
'filename' => $hash . '.png',
);
// Create a file with added contents.
$newfile = $fs->create_file_from_string($fileinfo, $newcontents);
if ($pathhash) {
return $newfile->get_pathnamehash();
}
}
} else {
debugging('Error baking badge image!', DEBUG_DEVELOPER);
return;
}
}
// If file exists and we just need its path hash, return it.
if ($pathhash) {
$file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
return $file->get_pathnamehash();
}
$fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
return $fileurl;
}
/**
* Returns external backpack settings and badges from this backpack.
*
* This function first checks if badges for the user are cached and
* tries to retrieve them from the cache. Otherwise, badges are obtained
* through curl request to the backpack.
*
* @param int $userid Backpack user ID.
* @param boolean $refresh Refresh badges collection in cache.
* @return null|object Returns null is there is no backpack or object with backpack settings.
*/
function get_backpack_settings($userid, $refresh = false) {
global $DB;
// Try to get badges from cache first.
$badgescache = cache::make('core', 'externalbadges');
$out = $badgescache->get($userid);
if ($out !== false && !$refresh) {
return $out;
}
// Get badges through curl request to the backpack.
$record = $DB->get_record('badge_backpack', array('userid' => $userid));
if ($record) {
$sitebackpack = badges_get_site_backpack($record->externalbackpackid);
$backpack = new \core_badges\backpack_api($sitebackpack, $record);
$out = new stdClass();
$out->backpackid = $sitebackpack->id;
if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
$out->totalcollections = count($collections);
$out->totalbadges = 0;
$out->badges = array();
foreach ($collections as $collection) {
$badges = $backpack->get_badges($collection, true);
if (!empty($badges)) {
$out->badges = array_merge($out->badges, $badges);
$out->totalbadges += count($badges);
} else {
$out->badges = array_merge($out->badges, array());
}
}
} else {
$out->totalbadges = 0;
$out->totalcollections = 0;
}
$badgescache->set($userid, $out);
return $out;
}
return null;
}
/**
* Download all user badges in zip archive.
*
* @param int $userid ID of badge owner.
*/
function badges_download($userid) {
global $CFG, $DB;
$context = context_user::instance($userid);
$records = $DB->get_records('badge_issued', array('userid' => $userid));
// Get list of files to download.
$fs = get_file_storage();
$filelist = array();
foreach ($records as $issued) {
$badge = new badge($issued->badgeid);
// Need to make image name user-readable and unique using filename safe characters.
$name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
$name = str_replace(' ', '_', $name);
$name = clean_param($name, PARAM_FILE);
if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
$filelist[$name . '.png'] = $file;
}
}
// Zip files and sent them to a user.
$tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
$zipper = new zip_packer();
if ($zipper->archive_to_pathname($filelist, $tempzip)) {
send_temp_file($tempzip, 'badges.zip');
} else {
debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
die;
}
}
/**
* Checks if user has external backpack connected.
*
* @param int $userid ID of a user.
* @return bool True|False whether backpack connection exists.
*/
function badges_user_has_backpack($userid) {
global $DB;
return $DB->record_exists('badge_backpack', array('userid' => $userid));
}
/**
* Handles what happens to the course badges when a course is deleted.
*
* @param int $courseid course ID.
* @return void.
*/
function badges_handle_course_deletion($courseid) {
global $CFG, $DB;
include_once $CFG->libdir . '/filelib.php';
$systemcontext = context_system::instance();
$coursecontext = context_course::instance($courseid);
$fs = get_file_storage();
// Move badges images to the system context.
$fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
// Get all course badges.
$badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
foreach ($badges as $badge) {
// Archive badges in this course.
$toupdate = new stdClass();
$toupdate->id = $badge->id;
$toupdate->type = BADGE_TYPE_SITE;
$toupdate->courseid = null;
$toupdate->status = BADGE_STATUS_ARCHIVED;
$DB->update_record('badge', $toupdate);
}
}
/**
* Create the site backpack with this data.
*
* @param stdClass $data The new backpack data.
* @return boolean
*/
function badges_create_site_backpack($data) {
global $DB;
$context = context_system::instance();
require_capability('moodle/badges:manageglobalsettings', $context);
$max = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
$data->sortorder = $max + 1;
return badges_save_external_backpack($data);
}
/**
* Update the backpack with this id.
*
* @param integer $id The backpack to edit
* @param stdClass $data The new backpack data.
* @return boolean
*/
function badges_update_site_backpack($id, $data) {
global $DB;
$context = context_system::instance();
require_capability('moodle/badges:manageglobalsettings', $context);
if ($backpack = badges_get_site_backpack($id)) {
$data->id = $id;
return badges_save_external_backpack($data);
}
return false;
}
/**
* Delete the backpack with this id.
*
* @param integer $id The backpack to delete.
* @return boolean
*/
function badges_delete_site_backpack($id) {
global $DB;
$context = context_system::instance();
require_capability('moodle/badges:manageglobalsettings', $context);
// Only remove site backpack if it's not the default one.
$defaultbackpack = badges_get_site_primary_backpack();
if ($defaultbackpack->id != $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
$transaction = $DB->start_delegated_transaction();
// Remove connections for users to this backpack.
$sql = "SELECT DISTINCT bb.id
FROM {badge_backpack} bb
WHERE bb.externalbackpackid = :backpackid";
$params = ['backpackid' => $id];
$userbackpacks = $DB->get_fieldset_sql($sql, $params);
if ($userbackpacks) {
// Delete user external collections references to this backpack.
list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
$DB->delete_records_select('badge_external', "backpackid $insql", $params);
}
$DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
// Delete backpack entry.
$result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
$transaction->allow_commit();
return $result;
}
return false;
}
/**
* Perform the actual create/update of external bakpacks. Any checks on the validity of the id will need to be
* performed before it reaches this function.
*
* @param stdClass $data The backpack data we are updating/inserting
* @return int Returns the id of the new/updated record
*/
function badges_save_external_backpack(stdClass $data) {
global $DB;
if ($data->apiversion == OPEN_BADGES_V2P1) {
// Check if there is an existing issuer for the given backpackapiurl.
foreach (core\oauth2\api::get_all_issuers() as $tmpissuer) {
if ($data->backpackweburl == $tmpissuer->get('baseurl')) {
$issuer = $tmpissuer;
break;
}
}
// Create the issuer if it doesn't exist yet.
if (empty($issuer)) {
$issuer = new \core\oauth2\issuer(0, (object) [
'name' => $data->backpackweburl,
'baseurl' => $data->backpackweburl,
// Note: This is required because the DB schema is broken and does not accept a null value when it should.
'image' => '',
]);
$issuer->save();
}
// This can't be run from PHPUNIT because testing platforms need real URLs.
// In the future, this request can be moved to the moodle-exttests repository.
if (!PHPUNIT_TEST) {
// Create/update the endpoints for the issuer.
\core\oauth2\discovery\imsbadgeconnect::create_endpoints($issuer);
$data->oauth2_issuerid = $issuer->get('id');
$apibase = \core\oauth2\endpoint::get_record([
'issuerid' => $data->oauth2_issuerid,
'name' => 'apiBase',
]);
$data->backpackapiurl = $apibase->get('url');
}
}
$backpack = new stdClass();
$backpack->apiversion = $data->apiversion;
$backpack->backpackweburl = $data->backpackweburl;
$backpack->backpackapiurl = $data->backpackapiurl;
$backpack->oauth2_issuerid = $data->oauth2_issuerid ?? '';
if (isset($data->sortorder)) {
$backpack->sortorder = $data->sortorder;
}