-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.php
2147 lines (1881 loc) · 82.7 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of 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/>.
/**
* wallet enrolment plugin.
*
* @package enrol_wallet
* @copyright 2023 Mo Farouk <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// Disable all callbacks during upgrade.
$version = get_config('enrol_wallet', 'version');
if ($version >= 2024030900) {
global $CFG;
require_once("$CFG->dirroot/enrol/wallet/extendlib.php");
}
use enrol_wallet\form\enrol_form;
use enrol_wallet\form\empty_form;
use enrol_wallet\form\applycoupon_form;
use enrol_wallet\form\insuf_form;
use enrol_wallet\form\topup_form;
use enrol_wallet\coupons;
use enrol_wallet\util\instance as helper;
use enrol_wallet\util\balance_op;
use enrol_wallet\util\balance;
use enrol_wallet\event\enrolpage_viewed;
use enrol_wallet\output\payment_info;
use enrol_wallet\restriction\info;
use enrol_wallet\editselectedusers_operation;
use enrol_wallet\deleteselectedusers_operation;
use enrol_wallet\restriction\frontend;
use enrol_wallet\util\offers;
/**
* wallet enrolment plugin implementation.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_wallet_plugin extends enrol_plugin {
/**
* If coupons disabled.
*/
public const WALLET_NOCOUPONS = coupons::NOCOUPONS;
/**
* If only fixed value coupons enabled.
*/
public const WALLET_COUPONSFIXED = coupons::FIXED;
/**
* If only percentage discount coupons enabled.
*/
public const WALLET_COUPONSDISCOUNT = coupons::DISCOUNT;
/**
* If all coupons enabled.
*/
public const WALLET_COUPONSALL = coupons::ALL;
/**
* If enrol coupons available.
*/
public const WALLET_COUPONSENROL = coupons::ENROL;
/**
* If category coupons available.
*/
public const WALLET_COUPONCAT = coupons::CATEGORY;
/**
* If the user has insufficient balance.
*/
public const INSUFFICIENT_BALANCE = 2;
/**
* If the user has insufficient balance even after discount.
*/
public const INSUFFICIENT_BALANCE_DISCOUNTED = 3;
/**
* lasternoller
* @var array
*/
protected $lasternoller = null;
/**
* lasternollerinstanceid
* @var int
*/
protected $lasternollerinstanceid = 0;
/**
* The cost after discounts.
* @var float
*/
protected $costafter;
/**
* Helper Class
* @var helper
*/
protected $helper;
/**
* Creating new enrol_wallet_plugin, passing the instance object or id
* will calculate the cost after discount and caches it.
*
* @param \stdClass $instance
*/
public function __construct($instance = null) {
if (!empty($instance)) {
$this->helper = new helper($instance);
$this->costafter = $this->helper->get_cost_after_discount();
}
$this->load_config();
}
/**
* Returns optional enrolment information icons.
*
* This is used in course list for quick overview of enrolment options.
*
* We are not using single instance parameter because sometimes
* we might want to prevent icon repetition when multiple instances
* of one type exist. One instance may also produce several icons.
*
* @param array $instances all enrol instances of this type in one course
* @return array of pix_icon
*/
public function get_info_icons(array $instances) {
global $PAGE;
$icons = [];
foreach ($instances as $instance) {
$helper = new helper($instance);
$cost = $helper->get_cost_after_discount();
$enrolstat = $this->can_self_enrol($instance);
$canenrol = (true === $enrolstat);
$insuf = (self::INSUFFICIENT_BALANCE == $enrolstat || self::INSUFFICIENT_BALANCE_DISCOUNTED == $enrolstat);
$discount = 0;
if (is_numeric($instance->cost) && !empty($instance->cost)) {
$discount = (int)(($instance->cost - $cost) / $instance->cost * 100);
}
if (!$canenrol && !$insuf) {
$cost = null;
} else if ($canenrol && $cost === 0.0) {
$discount = 100;
$cost = 'FREE';
}
$attributes = [
'class' => 'wallet-icon',
'data-instance-id' => $instance->id,
'data-cost' => is_numeric($cost) ? (int)ceil($cost) : $cost,
'data-selector' => 'enrol_wallet_icon',
'data-discount' => $discount,
'title' => get_string('pluginname', 'enrol_wallet') . " ($cost)",
];
$icons[] = new pix_icon('wallet', $attributes['title'], 'enrol_wallet', $attributes);
}
if (!empty($icons)) {
return $icons;
}
return [new pix_icon('wallet', get_string('pluginname', 'enrol_wallet'), 'enrol_wallet')];
}
/**
* Returns localized name of enrol instance
*
* @param stdClass $instance (null is accepted too)
* @return string
*/
public function get_instance_name($instance) {
global $DB, $USER;
if (empty($instance->name)) {
if (!empty($instance->roleid) && $role = $DB->get_record('role', ['id' => $instance->roleid])) {
$role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')';
} else {
$role = '';
}
$cost = $instance->cost;
$currency = $instance->currency;
$enrol = $this->get_name();
return get_string('pluginname', 'enrol_' . $enrol) . $role . '-' . $cost . ' ' . $currency;
} else {
return format_string($instance->name);
}
}
/**
* Does this plugin assign protected roles are can they be manually removed?
* @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
*/
public function roles_protected() {
return false;
}
/**
* Does this plugin allow manual unenrolment of all users?
* All plugins allowing this must implement 'enrol/xxx:unenrol' capability
*
* @param stdClass $instance course enrol instance
* @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch
* user_enrollments
*/
public function allow_unenrol(stdClass $instance) {
return true;
}
/**
* Return unenrol link to unenrol user from the current course.
* Null if unenrol self is not allowed or the user doesn't has the capability to unenrol.
* @param stdClass $instance
* @return moodle_url|null
*/
public function get_unenrolself_link($instance) {
global $USER, $DB;
// Check if unenrol self is enabled in the settings.
$enabled = $this->get_config('unenrolselfenabled');
if (!$enabled) {
return null;
}
// Check main security in the main function.
$return = parent::get_unenrolself_link($instance);
if (empty($return)) {
return null;
}
$parentreturn = $return;
// Check the periods conditions.
$before = $this->get_config('unenrollimitbefor');
$after = $this->get_config('unenrollimitafter');
$enrolrecord = $DB->get_record('user_enrolments', ['enrolid' => $instance->id, 'userid' => $USER->id]);
$enrolstart = $enrolrecord->timestart;
$enrolend = $enrolrecord->timeend;
// Cannot unenrol self after this period from enrol start date.
if (!empty($after) && time() > $after + $enrolstart) {
// Make sure this is not interfere with the second condition.
if (!empty($before) && !empty($enrolend) && time() > $enrolend - $before) {
$return = $parentreturn;
} else {
$return = null;
}
}
// Cannot unenrol self before this period from the enrol end date.
if (!empty($before) && !empty($enrolend) && time() < $enrolend - $before) {
// Make sure this is not interfere with the first condition.
if (!empty($after) && time() < $after + $enrolstart) {
$return = $parentreturn;
} else {
$return = null;
}
}
return $return;
}
/**
* Unenrol user from the course if enrolled using wallet enrolment.
* using this to refund the users balance again.
* @param stdClass $instance
* @param int $userid
* @return void
*/
public function unenrol_user(stdClass $instance, $userid) {
// Check if refund upon unenrolment is enabled.
$enabled = $this->get_config('unenrolrefund');
if (empty($enabled)) {
return parent::unenrol_user($instance, $userid);
}
global $DB;
$enrolrecord = $DB->get_record('user_enrolments', ['enrolid' => $instance->id, 'userid' => $userid]);
$enrolstart = $enrolrecord->timestart;
$enrolend = $enrolrecord->timeend;
$refundperiod = $this->get_config('unenrolrefundperiod');
$now = time();
if (
(!empty($enrolend) && $now > $enrolend) // The enrolmet already ended.
|| ($now > $enrolstart && !empty($refundperiod) && ($now - $enrolstart) > $refundperiod) // Passed the period.
) {
// Condition for refunding aren't met.
return parent::unenrol_user($instance, $userid);
}
$rawcost = $this->get_cost_after_discount($userid, $instance);
// Check for refunding fee.
$fee = intval($this->get_config('unenrolrefundfee'));
$cost = $rawcost - ($rawcost * $fee / 100);
// Check for previously used coupon.
$coupons = $DB->get_records('enrol_wallet_coupons_usage', ['userid' => $userid, 'instanceid' => $instance->id]);
$credit = $cost;
if (!empty($coupons)) {
foreach ($coupons as $coupon) {
if ($coupon->type == 'fixed' || $coupon->type == 'category') {
$credit -= $coupon->value;
} else if ($coupon->type == 'percent') {
$credit -= ($cost * $coupon->value / 100);
} else if ($coupon->type == 'enrol') {
$credit -= $cost;
}
}
}
if ($credit <= 0) {
return parent::unenrol_user($instance, $userid);
} else if ($credit > $cost) {
// Shouldn't happen.
$credit = $cost;
}
// Credit the user.
$a = [
'fee' => $cost - $credit,
'credit' => $credit,
'coursename' => get_course($instance->courseid)->fullname,
];
$desc = get_string('refunduponunenrol_desc', 'enrol_wallet', $a);
$op = new balance_op($userid);
$op->credit($credit, balance_op::C_UNENROL, $instance->id, $desc, false, false);
return parent::unenrol_user($instance, $userid);
}
/**
* Does this plugin allow manual changes in user_enrollments table?
*
* All plugins allowing this must implement 'enrol/xxx:manage' capability
*
* @param stdClass $instance course enrol instance
* @return bool - true means it is possible to change enrol period and status in user_enrolments table
*/
public function allow_manage(stdClass $instance) {
return true;
}
/**
* Does this plugin support some way to user to self enrol?
*
* @param stdClass $instance course enrol instance
* @return bool - true means show "Enrol me in this course" link in course UI
*/
public function show_enrolme_link(stdClass $instance) {
if (true !== $this->can_self_enrol($instance, false)) {
return false;
}
return true;
}
/**
* Return true if we can add a new instance to this course.
*
* @param int $courseid
* @return boolean
*/
public function can_add_instance($courseid) {
global $DB;
$context = context_course::instance($courseid, MUST_EXIST);
if (!has_capability('moodle/course:enrolconfig', $context) || !has_capability('enrol/wallet:config', $context)) {
return false;
}
// Check the number of allowed instances.
$count = $DB->count_records('enrol', ['courseid' => $courseid, 'enrol' => 'wallet']);
if ($multiple = $this->get_config('allowmultipleinstances')) {
if (empty($multiple)) {
return true;
} else if ($count >= $multiple) {
return false;
}
}
return true;
}
/**
* Self enrol user to course
*
* @param stdClass $instance enrolment instance
* @param stdClass|null $user User to enrol and deduct fees from
* @param bool $charge Charge the user to enrol (only false in case of enrol coupons)
* @return bool|array true if enrolled else error code and message
*/
public function enrol_self(stdClass $instance, $user = null, $charge = true) {
global $CFG, $DB, $USER;
require_once("$CFG->dirroot/enrol/wallet/locallib.php");
if (empty($user)) {
$user = $USER;
}
// Get the name of the course.
$helper = $this->get_helper($instance, $user->id);
$op = new balance_op($user->id, $helper->get_course_category());
// Get the final cost after discount (if there is no discount it return the full cost).
$costafter = $helper->get_cost_after_discount();
$helper->reset_static_cache();
$charge = $charge && ($costafter >= 0.01);
if ($charge) {
$canborrow = enrol_wallet_is_borrow_eligible($user->id);
// Deduct fees from user's account.
if (!$op->debit($costafter, balance_op::D_ENROL_INSTANCE, $instance->id, '', $canborrow)) {
throw new moodle_exception('cannotdeductbalance', 'enrol_wallet');
}
}
$timestart = time();
$timeend = ($instance->enrolperiod) ? $timestart + $instance->enrolperiod : 0;
// Some times the user get deducted but not enrolled, so we try the while loop to make sure that the user enrolled.
try {
$conditions = [
'userid' => $user->id,
'enrolid' => $instance->id,
'timestart' => $timestart,
'timeend' => $timeend,
'status' => ENROL_USER_ACTIVE,
];
do {
$this->enrol_user($instance, $user->id, $instance->roleid, $timestart, $timeend, null, true);
} while (!$DB->record_exists('user_enrolments', $conditions));
} catch (\moodle_exception $e) {
// Rollback the transaction in case of error.
if ($charge) {
$op->credit($costafter, balance_op::C_ROLLBACK, $instance->id, 'Refund due to error', false, false);
}
throw $e;
}
\core\notification::success(get_string('youenrolledincourse', 'enrol'));
// Mark coupon as used (this is for percentage discount coupons only).
if ($couponutil = $helper->get_coupon_helper()) {
$couponutil->mark_coupon_used();
}
// Unset the session coupon to make sure not used again.
// This is a double check, already included in mark_coupon_used().
coupons::unset_session_coupon();
// Now apply the cashback if enabled.
$cashbackenabled = $this->get_config('cashback');
if ($cashbackenabled) {
$op->apply_cashback();
}
// Send welcome message.
if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) {
$this->email_welcome_message($instance, $user);
}
return true;
}
/**
* Check for other enrol_wallet instances, return true if there is a cheaper one.
*
* @param stdClass $thisinstance the id of this instances.
* @return bool
*/
public function hide_due_cheaper_instance($thisinstance) {
global $DB, $USER;
$courseid = $thisinstance->courseid;
// Check the status of this instance.
$thisid = $thisinstance->id;
$thiscost = $this->get_cost_after_discount($USER->id, $thisinstance, true);
$thisenrolstat = $this->can_self_enrol($thisinstance);
$thiscanenrol = (true === $thisenrolstat);
$thisinsuf = (self::INSUFFICIENT_BALANCE == $thisenrolstat || self::INSUFFICIENT_BALANCE_DISCOUNTED == $thisenrolstat);
// Get the other instances.
$instances = $DB->get_records('enrol', ['courseid' => $courseid, 'enrol' => 'wallet'], 'cost ASC');
// No need to check if there is only one instance.
if (count($instances) < 2) {
return false;
}
// Check the status of other instance.
$hide = false;
foreach ($instances as $instance) {
// Don't compare the instance with itself.
if ($thisid == $instance->id) {
continue;
}
$wallet = new self;
$othercost = $wallet->get_cost_after_discount($USER->id, $instance);
$enrolstat = $wallet->can_self_enrol($instance);
$canenrol = (true === $enrolstat);
$insuf = (self::INSUFFICIENT_BALANCE == $enrolstat || self::INSUFFICIENT_BALANCE_DISCOUNTED == $enrolstat);
// Hide if can enrol in other and is cheaper or cannot enrol in this one.
if ($canenrol && ($othercost < $thiscost || !$thiscanenrol)) {
$hide = true;
break;
}
// Both insuficient but there is a cheaper one.
if ($insuf && $thisinsuf && $othercost < $thiscost) {
$otherinsuf = true;
}
}
// Cannot enrol in any but there is other cheaper with insufficient balance.
if (!$hide && !empty($otherinsuf) && !$thiscanenrol) {
$hide = true;
}
return $hide;
}
/**
* Check if there is restriction according to other courses enrolment.
* Return false if not restricted and string with required courses names in case if restricted.
* @param stdClass $instance
* @return bool|string
*/
public function is_course_enrolment_restriction($instance) {
global $DB;
if (!empty($instance->customchar3) && !empty($instance->customint7)) {
$courses = explode(',', $instance->customchar3);
$restrict = false;
$count = 0;
$total = 0;
$notenrolled = [];
foreach ($courses as $courseid) {
if (!$DB->record_exists('course', ['id' => $courseid])) {
continue;
}
$total++;
$coursectx = context_course::instance($courseid);
if (!is_enrolled($coursectx)) {
$restrict = true;
// The user is not enrolled in the required course.
$notenrolled[] = get_course($courseid)->fullname;
} else {
// Count the courses which the user enrolled in.
$count++;
}
}
$coursesnames = '(' . implode(', ', $notenrolled) . ')';
// In case that the course creator choose a higher number than the selected courses.
$limit = min($total, $instance->customint7);
if ($restrict && $count < $limit) {
return $coursesnames;
}
}
return false;
}
/**
* Creates course enrol form, checks if form submitted
* and enrols user if necessary. It can also redirect.
*
* @param stdClass $instance
* @return string html text, usually a form in a text box
*/
public function enrol_page_hook(stdClass $instance) {
global $OUTPUT, $USER, $CFG;
require_once("$CFG->dirroot/enrol/wallet/locallib.php");
// Hide this instance in case of existance of another avaliable one with lower cost.
if ($this->hide_due_cheaper_instance($instance)) {
return '';
}
enrolpage_viewed::create_and_trigger($instance);
$couponsetting = $this->get_config('coupons');
$helper = $this->get_helper($instance);
$costafter = $helper->get_cost_after_discount();
$costbefore = $instance->cost;
$enrolstatus = $this->can_self_enrol($instance);
$output = '';
if (coupons::is_enabled()) {
$formdata = new stdClass();
$formdata->header = $this->get_instance_name($instance);
$formdata->instance = $instance;
$formdata->url = (new \moodle_url('/enrol/index.php', ['id' => $instance->courseid]))->out();
$couponaction = new \moodle_url('/enrol/wallet/extra/coupon_action.php');
$couponform = new applycoupon_form($couponaction, $formdata);
if ($submitteddata = $couponform->get_data()) {
enrol_wallet_process_coupon_data($submitteddata);
}
}
if (true === $enrolstatus) {
$confirmpage = new moodle_url('/enrol/wallet/confirm.php');
// This user can self enrol using this instance.
$form = new enrol_form($confirmpage, $instance);
$instanceid = optional_param('instance', 0, PARAM_INT);
if ((int)$instance->id === $instanceid) {
// If form validates user can purchase enrolment with wallet balance.
$data = $form->get_data();
if (!empty($data) && $data->instance == $instance->id) {
$this->enrol_self($instance, $USER);
return '';
}
}
ob_start();
$form->display();
$output .= ob_get_clean();
// Now prepare the coupon form.
// Check the coupons settings first.
if (coupons::is_enabled() && $costafter != 0) {
ob_start();
$couponform->display();
$output .= ob_get_clean();
}
} else if (
self::INSUFFICIENT_BALANCE == $enrolstatus
|| self::INSUFFICIENT_BALANCE_DISCOUNTED == $enrolstatus
) {
$balancehelper = new balance(0, $helper->get_course_category());
$balance = $balancehelper->get_valid_balance();
// This user has insufficient wallet balance to be directly enrolled.
// So we will show him several ways for payments or recharge his wallet.
$data = new stdClass();
$data->header = $this->get_instance_name($instance);
$data->instance = $instance;
$a = [
'cost_before' => $costbefore,
'cost_after' => $costafter,
'user_balance' => $balance,
'currency' => $instance->currency,
];
if ($enrolstatus == self::INSUFFICIENT_BALANCE) {
$data->info = get_string('insufficient_balance', 'enrol_wallet', $a);
} else {
$data->info = get_string('insufficient_balance_discount', 'enrol_wallet', $a);
}
$form = new insuf_form(null, $data);
ob_start();
$form->display();
$output .= ob_get_clean();
// Now prepare the coupon form.
if (coupons::is_enabled()) {
ob_start();
$couponform->display();
$output .= ob_get_clean();
}
// If the payment enbled in this instance, display the payment button.
if (!empty($instance->customint1) && !empty($instance->currency)) {
$output .= self::show_payment_info($instance, $costafter);
}
// If payment is enabled in general, adding topup option.
$account = $this->get_config('paymentaccount');
if (enrol_wallet_is_valid_account($account)) {
$topupurl = new moodle_url('/enrol/wallet/extra/topup.php');
$topupform = new topup_form($topupurl, $data);
ob_start();
$topupform->display();
$output .= ob_get_clean();
}
} else {
// This user cannot enrol using this instance. Using an empty form to keep
// the UI consistent with other enrolment plugins that returns a form.
$data = new stdClass();
$data->header = $this->get_instance_name($instance);
$data->info = $enrolstatus;
$data->instance = $instance;
// The can_self_enrol call returns a button to the login page if the user is a
// guest, setting the login url to the form if that is the case.
$url = isguestuser() ? get_login_url() : null;
$form = new empty_form($url, $data);
ob_start();
$form->display();
$output .= ob_get_clean();
}
$offers = new offers($instance);
$output .= $offers->format_offers_descriptions();
return $OUTPUT->box($output);
}
/**
* Checks if user can self enrol.
*
* @param stdClass $instance enrolment instance
* @param bool $checkuserenrolment if true will check if user enrolment is inactive.
* used by navigation to improve performance.
* @return bool|string true if successful, else error message or false.
*/
public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
global $CFG, $DB, $OUTPUT, $USER;
$repurchase = $this->get_config('repurchase');
if (isguestuser()) {
// Can not enrol guest.
return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
}
// Check if user has the capability to enrol in this context.
if (!has_capability('enrol/wallet:enrolself', context_course::instance($instance->courseid))) {
return get_string('canntenrol', 'enrol_wallet');
}
// Check if user is a parent only if auth wallet exists.
if (file_exists($CFG->dirroot . '/auth/parent/lib.php')) {
require_once($CFG->dirroot . '/auth/parent/lib.php');
if (auth_parent_is_parent($USER)) {
return get_string('canntenrol', 'enrol_wallet');
}
}
if ($checkuserenrolment) {
// Check if user is already enroled.
if ($ue = $DB->get_record('user_enrolments', ['userid' => $USER->id, 'enrolid' => $instance->id])) {
// Check if repurchase enabled, the enrolment already endded and the user isn't suspended.
if (!$repurchase || (!empty($ue->timeend) && $ue->timeend > time()) || $ue->status == ENROL_USER_SUSPENDED) {
return get_string('alreadyenroled', 'enrol_wallet');
}
}
}
$return = [];
// Disabled instance.
if ($instance->status != ENROL_INSTANCE_ENABLED) {
$return[] = get_string('canntenrol', 'enrol_wallet');
}
// Cannot enrol early.
if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
$return[] = get_string('canntenrolearly', 'enrol_wallet', userdate($instance->enrolstartdate));
}
// Cannot enrol late.
if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
$return[] = get_string('canntenrollate', 'enrol_wallet', userdate($instance->enrolenddate));
}
// New enrols not allowed.
if (!$instance->customint6) {
$return[] = get_string('canntenrol', 'enrol_wallet');
}
// Max enrolments reached.
if ($instance->customint3 > 0) {
// Max enrol limit specified.
$count = $DB->count_records('user_enrolments', ['enrolid' => $instance->id]);
if ($count >= $instance->customint3) {
// Bad luck, no more self enrolments here.
$return[] = get_string('maxenrolledreached', 'enrol_wallet');
}
}
// Check the restrictions upon other courses enrollment.
if ($coursesnames = $this->is_course_enrolment_restriction($instance)) {
$a = [
'courses' => $coursesnames,
'number' => $instance->customint7,
];
$return[] = get_string('othercourserestriction', 'enrol_wallet', $a);
}
// Check the cohorts restrictions.
if ($instance->customint5) {
require_once("$CFG->dirroot/cohort/lib.php");
if (!cohort_is_member($instance->customint5, $USER->id)) {
$cohort = $DB->get_record('cohort', ['id' => $instance->customint5]);
if (!$cohort) {
return null;
}
$a = format_string($cohort->name, true, ['context' => context::instance_by_id($cohort->contextid)]);
$return[] = markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_wallet', $a));
}
}
if (!empty($this->get_config('restrictionenabled')) && !empty($instance->customtext2)) {
$info = new info($instance);
if (!$info->is_available($reasons, true, $USER->id)) {
$return[] = $reasons;
}
}
// All restrictions checked.
if (!empty($return)) {
// Display them all.
return implode('<br> &' . ' ', $return);
}
// Non valid cost.
if (!isset($instance->cost) || !is_numeric($instance->cost) || $instance->cost < 0) {
return get_string('nocost', 'enrol_wallet');
}
// Insufficient balance.
$helper = $this->get_helper($instance);
$costafter = $helper->get_cost_after_discount();
// Check if the discount gives acceptable cost.
if (!is_numeric($costafter) || $costafter < 0) {
return get_string('nocost', 'enrol_wallet');
}
require_once("$CFG->dirroot/enrol/wallet/locallib.php");
$this->costafter = $costafter;
$costbefore = $instance->cost;
$balancehelper = new balance(0, $helper->get_course_category());
$balance = $balancehelper->get_valid_balance();
$canborrow = enrol_wallet_is_borrow_eligible($USER->id);
if ($balance < $costafter && !$canborrow) {
if ($costbefore == $costafter) {
return self::INSUFFICIENT_BALANCE;
} else {
return self::INSUFFICIENT_BALANCE_DISCOUNTED;
}
}
return true;
}
/**
* Get the helper class
* @param \stdClass|int $instance
* @param int $userid
* @return helper|null
*/
protected function get_helper($instance, $userid = 0) {
global $USER;
if (is_number($instance)) {
$instanceid = $instance;
} else if (!empty($instance->id)) {
$instanceid = $instance->id;
} else {
return null;
}
if (empty($this->helper)
|| $this->helper->id !== $instanceid
|| (!empty($userid) && $userid != $this->helper->userid)
|| (empty($userid) && $USER->id != $this->helper->userid)) {
$this->helper = new helper($instance, $userid);
}
return $this->helper;
}
/**
* Return information for enrolment instance containing list of parameters required
* for enrolment, name of enrolment plugin etc.
*
* @param stdClass $instance enrolment instance
* @return stdClass instance info.
*/
public function get_enrol_info(stdClass $instance) {
global $USER;
$instanceinfo = new stdClass();
$instanceinfo->id = $instance->id;
$instanceinfo->courseid = $instance->courseid;
$instanceinfo->type = $this->get_name();
$instanceinfo->name = $this->get_instance_name($instance);
$instanceinfo->status = $this->can_self_enrol($instance);
$instanceinfo->cost = $this->get_cost_after_discount($USER->id, $instance);
return $instanceinfo;
}
/**
* Add new instance of enrol plugin with default settings.
* @param stdClass $course
* @return int id of new instance
*/
public function add_default_instance($course) {
$fields = $this->get_instance_defaults();
return $this->add_instance($course, $fields);
}
/**
* Send welcome email to specified user.
*
* @param stdClass $instance
* @param stdClass $user user record
* @return void
*/
protected function email_welcome_message($instance, $user) {
global $CFG, $DB;
$course = $DB->get_record('course', ['id' => $instance->courseid], '*', MUST_EXIST);
$context = context_course::instance($course->id);
$a = new stdClass();
$a->coursename = format_string($course->fullname, true, ['context' => $context]);
$a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
if (!is_null($instance->customtext1) && trim($instance->customtext1) !== '') {
$message = $instance->customtext1;
$key = ['{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}'];
$value = [$a->coursename, $a->profileurl, fullname($user), $user->email];
$message = str_replace($key, $value, $message);
if (strpos($message, '<') === false) {
// Plain text only.
$messagetext = $message;
$messagehtml = text_to_html($messagetext, null, false, true);
} else {
// This is most probably the tag/newline soup known as FORMAT_MOODLE.
$options = new \stdClass();
$options->context = $context;
$options->para = false;
$options->newlines = true;
$options->filter = true;
$messagehtml = format_text($message, FORMAT_MOODLE, $options);
$messagetext = html_to_text($messagehtml);
}
} else {
$messagetext = get_string('welcometocoursetext', 'enrol_wallet', $a);
$messagehtml = text_to_html($messagetext, null, false, true);
}
$subject = get_string('welcometocourse', 'enrol_wallet', format_string($course->fullname, true, ['context' => $context]));
$sendoption = $instance->customint4;
$contact = $this->get_welcome_email_contact($sendoption, $context);
// Directly emailing welcome message rather than using messaging.
email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
}
/**
* Sync all meta course links.
*
* Unenrols users that have exceeded the "longtimenosee" value set on wallet enrolment instances.
*
* @param progress_trace $trace
* @param int $courseid one course, empty mean all
* @return int 0 means ok, 1 means error, 2 means plugin disabled
*/
public function sync(progress_trace $trace, $courseid = null) {
global $DB;
if (!enrol_is_enabled('wallet')) {
$trace->finished();
return 2;
}
// Unfortunately this may take a long time, execution can be interrupted safely here.
core_php_time_limit::raise();
raise_memory_limit(MEMORY_HUGE);
$trace->output('Verifying wallet enrolments...');
$params = ['now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE];
$coursesql = "";
if ($courseid) {
$coursesql = "AND e.courseid = :courseid";
$params['courseid'] = $courseid;
}
// Note: the logic of wallet enrolment guarantees that user logged in at least once (=== u.lastaccess set)
// and that user accessed course at least once too (=== user_lastaccess record exists).
// First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
$sql = "SELECT e.*, ue.userid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'wallet' AND e.customint2 > 0)
JOIN {user} u ON u.id = ue.userid
WHERE :now - u.lastaccess > e.customint2
$coursesql";
$rs = $DB->get_recordset_sql($sql, $params);