MDL-69166 enrol_fee: use template for payment btn & properly format cost
[moodle.git] / enrol / fee / classes / plugin.php
CommitLineData
a580b337
SR
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Fee enrolment plugin.
19 *
20 * This plugin allows you to set up paid courses.
21 *
22 * @package enrol_fee
23 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27/**
28 * Fee enrolment plugin implementation.
29 *
30 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 */
33class enrol_fee_plugin extends enrol_plugin {
34
35 /**
36 * Returns the list of currencies that the payment subsystem supports and therefore we can work with.
37 *
38 * @return array[currencycode => currencyname]
39 */
40 public function get_possible_currencies(): array {
41 $codes = \core_payment\helper::get_supported_currencies();
42
43 $currencies = [];
44 foreach ($codes as $c) {
45 $currencies[$c] = new lang_string($c, 'core_currencies');
46 }
47
48 return $currencies;
49 }
50
51 /**
52 * Returns optional enrolment information icons.
53 *
54 * This is used in course list for quick overview of enrolment options.
55 *
56 * We are not using single instance parameter because sometimes
57 * we might want to prevent icon repetition when multiple instances
58 * of one type exist. One instance may also produce several icons.
59 *
60 * @param array $instances all enrol instances of this type in one course
61 * @return array of pix_icon
62 */
63 public function get_info_icons(array $instances) {
64 $found = false;
65 foreach ($instances as $instance) {
66 if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
67 continue;
68 }
69 if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
70 continue;
71 }
72 $found = true;
73 break;
74 }
75 if ($found) {
76 return array(new pix_icon('icon', get_string('pluginname', 'enrol_fee'), 'enrol_fee'));
77 }
78 return array();
79 }
80
81 public function roles_protected() {
82 // Users with role assign cap may tweak the roles later.
83 return false;
84 }
85
86 public function allow_unenrol(stdClass $instance) {
87 // Users with unenrol cap may unenrol other users manually - requires enrol/fee:unenrol.
88 return true;
89 }
90
91 public function allow_manage(stdClass $instance) {
92 // Users with manage cap may tweak period and status - requires enrol/fee:manage.
93 return true;
94 }
95
96 public function show_enrolme_link(stdClass $instance) {
97 return ($instance->status == ENROL_INSTANCE_ENABLED);
98 }
99
100 /**
101 * Returns true if the user can add a new instance in this course.
102 * @param int $courseid
103 * @return boolean
104 */
105 public function can_add_instance($courseid) {
106 $context = context_course::instance($courseid, MUST_EXIST);
107
108 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/fee:config', $context)) {
109 return false;
110 }
111
112 // Multiple instances supported - different cost for different roles.
113 return true;
114 }
115
116 /**
117 * We are a good plugin and don't invent our own UI/validation code path.
118 *
119 * @return boolean
120 */
121 public function use_standard_editing_ui() {
122 return true;
123 }
124
125 /**
126 * Add new instance of enrol plugin.
127 * @param object $course
128 * @param array $fields instance fields
129 * @return int id of new instance, null if can not be created
130 */
131 public function add_instance($course, array $fields = null) {
132 if ($fields && !empty($fields['cost'])) {
133 $fields['cost'] = unformat_float($fields['cost']);
134 }
135 return parent::add_instance($course, $fields);
136 }
137
138 /**
139 * Update instance of enrol plugin.
140 * @param stdClass $instance
141 * @param stdClass $data modified instance fields
142 * @return boolean
143 */
144 public function update_instance($instance, $data) {
145 if ($data) {
146 $data->cost = unformat_float($data->cost);
147 }
148 return parent::update_instance($instance, $data);
149 }
150
151 /**
152 * Creates course enrol form, checks if form submitted
153 * and enrols user if necessary. It can also redirect.
154 *
155 * @param stdClass $instance
156 * @return string html text, usually a form in a text box
157 */
158 public function enrol_page_hook(stdClass $instance) {
159 global $CFG, $USER, $OUTPUT, $PAGE, $DB;
160
161 ob_start();
162
163 if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
164 return ob_get_clean();
165 }
166
167 if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
168 return ob_get_clean();
169 }
170
171 if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
172 return ob_get_clean();
173 }
174
175 $course = $DB->get_record('course', array('id' => $instance->courseid));
176 $context = context_course::instance($course->id);
177
178 $shortname = format_string($course->shortname, true, array('context' => $context));
179 $strloginto = get_string("loginto", "", $shortname);
180 $strcourses = get_string("courses");
181
182 // Pass $view=true to filter hidden caps if the user cannot see them.
183 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
184 '', '', '', '', false, true)) {
185 $users = sort_by_roleassignment_authority($users, $context);
186 $teacher = array_shift($users);
187 } else {
188 $teacher = false;
189 }
190
191 if ( (float) $instance->cost <= 0 ) {
192 $cost = (float) $this->get_config('cost');
193 } else {
194 $cost = (float) $instance->cost;
195 }
196
197 if (abs($cost) < 0.01) { // No cost, other enrolment methods (instances) should be used.
198 echo '<p>'.get_string('nocost', 'enrol_fee').'</p>';
199 } else {
a580b337 200
9d773ee5
SR
201 $locale = get_string('localecldr', 'langconfig');
202 $fmt = NumberFormatter::create($locale, NumberFormatter::CURRENCY);
203 $localisedcost = numfmt_format_currency($fmt, $cost, $instance->currency);
204
205 $data = [
206 'isguestuser' => isguestuser(),
207 'cost' => $localisedcost,
208 'currency' => $instance->currency,
209 'amount' => $cost,
210 'instanceid' => $instance->id,
211 'description' => get_string('purchasedescription', 'enrol_fee',
212 format_string($course->fullname, true, ['context' => $context])),
213 ];
214 echo $OUTPUT->render_from_template('enrol_fee/payment_region', $data);
a580b337
SR
215 }
216
217 return $OUTPUT->box(ob_get_clean());
218 }
219
220 /**
221 * Restore instance and map settings.
222 *
223 * @param restore_enrolments_structure_step $step
224 * @param stdClass $data
225 * @param stdClass $course
226 * @param int $oldid
227 */
228 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
229 global $DB;
230 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
231 $merge = false;
232 } else {
233 $merge = array(
234 'courseid' => $data->courseid,
235 'enrol' => $this->get_name(),
236 'roleid' => $data->roleid,
237 'cost' => $data->cost,
238 'currency' => $data->currency,
239 );
240 }
241 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
242 $instance = reset($instances);
243 $instanceid = $instance->id;
244 } else {
245 $instanceid = $this->add_instance($course, (array) $data);
246 }
247 $step->set_mapping('enrol', $oldid, $instanceid);
248 }
249
250 /**
251 * Restore user enrolment.
252 *
253 * @param restore_enrolments_structure_step $step
254 * @param stdClass $data
255 * @param stdClass $instance
256 * @param int $oldinstancestatus
257 * @param int $userid
258 */
259 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
260 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
261 }
262
263 /**
264 * Return an array of valid options for the status.
265 *
266 * @return array
267 */
268 protected function get_status_options() {
269 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
270 ENROL_INSTANCE_DISABLED => get_string('no'));
271 return $options;
272 }
273
274 /**
275 * Return an array of valid options for the roleid.
276 *
277 * @param stdClass $instance
278 * @param context $context
279 * @return array
280 */
281 protected function get_roleid_options($instance, $context) {
282 if ($instance->id) {
283 $roles = get_default_enrol_roles($context, $instance->roleid);
284 } else {
285 $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
286 }
287 return $roles;
288 }
289
290
291 /**
292 * Add elements to the edit instance form.
293 *
294 * @param stdClass $instance
295 * @param MoodleQuickForm $mform
296 * @param context $context
297 * @return bool
298 */
299 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
300
301 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
302 $mform->setType('name', PARAM_TEXT);
303
304 $options = $this->get_status_options();
305 $mform->addElement('select', 'status', get_string('status', 'enrol_fee'), $options);
306 $mform->setDefault('status', $this->get_config('status'));
307
308 $mform->addElement('text', 'cost', get_string('cost', 'enrol_fee'), array('size' => 4));
309 $mform->setType('cost', PARAM_RAW);
310 $mform->setDefault('cost', format_float($this->get_config('cost'), 2, true));
311
312 $supportedcurrencies = $this->get_possible_currencies();
313 $mform->addElement('select', 'currency', get_string('currency', 'enrol_fee'), $supportedcurrencies);
314 $mform->setDefault('currency', $this->get_config('currency'));
315
316 $roles = $this->get_roleid_options($instance, $context);
317 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_fee'), $roles);
318 $mform->setDefault('roleid', $this->get_config('roleid'));
319
320 $options = array('optional' => true, 'defaultunit' => 86400);
321 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_fee'), $options);
322 $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
323 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_fee');
324
325 $options = array('optional' => true);
326 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_fee'), $options);
327 $mform->setDefault('enrolstartdate', 0);
328 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_fee');
329
330 $options = array('optional' => true);
331 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_fee'), $options);
332 $mform->setDefault('enrolenddate', 0);
333 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_fee');
334
335 if (enrol_accessing_via_instance($instance)) {
336 $warningtext = get_string('instanceeditselfwarningtext', 'core_enrol');
337 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warningtext);
338 }
339 }
340
341 /**
342 * Perform custom validation of the data used to edit the instance.
343 *
344 * @param array $data array of ("fieldname"=>value) of submitted data
345 * @param array $files array of uploaded files "element_name"=>tmp_file_path
346 * @param object $instance The instance loaded from the DB
347 * @param context $context The context of the instance we are editing
348 * @return array of "element_name"=>"error_description" if there are errors,
349 * or an empty array if everything is OK.
350 * @return void
351 */
352 public function edit_instance_validation($data, $files, $instance, $context) {
353 $errors = array();
354
355 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
356 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_fee');
357 }
358
359 $cost = str_replace(get_string('decsep', 'langconfig'), '.', $data['cost']);
360 if (!is_numeric($cost)) {
361 $errors['cost'] = get_string('costerror', 'enrol_fee');
362 }
363
364 $validstatus = array_keys($this->get_status_options());
365 $validcurrency = array_keys($this->get_possible_currencies());
366 $validroles = array_keys($this->get_roleid_options($instance, $context));
367 $tovalidate = array(
368 'name' => PARAM_TEXT,
369 'status' => $validstatus,
370 'currency' => $validcurrency,
371 'roleid' => $validroles,
372 'enrolperiod' => PARAM_INT,
373 'enrolstartdate' => PARAM_INT,
374 'enrolenddate' => PARAM_INT
375 );
376
377 $typeerrors = $this->validate_param_types($data, $tovalidate);
378 $errors = array_merge($errors, $typeerrors);
379
380 return $errors;
381 }
382
383 /**
384 * Execute synchronisation.
385 * @param progress_trace $trace
386 * @return int exit code, 0 means ok
387 */
388 public function sync(progress_trace $trace) {
389 $this->process_expirations($trace);
390 return 0;
391 }
392
393 /**
394 * Is it possible to delete enrol instance via standard UI?
395 *
396 * @param stdClass $instance
397 * @return bool
398 */
399 public function can_delete_instance($instance) {
400 $context = context_course::instance($instance->courseid);
401 return has_capability('enrol/fee:config', $context);
402 }
403
404 /**
405 * Is it possible to hide/show enrol instance via standard UI?
406 *
407 * @param stdClass $instance
408 * @return bool
409 */
410 public function can_hide_show_instance($instance) {
411 $context = context_course::instance($instance->courseid);
412 return has_capability('enrol/fee:config', $context);
413 }
414}