MDL-69166 enrol_fee: An enrolment plugin that supports payments
[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 {
200 $localisedcost = format_float($cost, -1, true);
201
202 if (isguestuser()) { // Force login only for guest user, not real users with guest role.
203 $wwwroot = $CFG->wwwroot;
204 echo '<div class="mdl-align"><p>'.get_string('paymentrequired').'</p>';
205 echo '<p><b>'.get_string('cost').": $instance->currency $localisedcost".'</b></p>';
206 echo '<p><a href="'.$wwwroot.'/login/">'.get_string('loginsite').'</a></p>';
207 echo '</div>';
208 } else {
209 echo '<div align="center"><input type="submit" value="' . get_string("sendpaymentbutton", "enrol_paypal") . '" /></div>';
210 $PAGE->requires->js_call_amd('profilefield_conditional/conditionconfig', 'init', array('#id_param1',
211 '#profilefield_conditional_conditionconfiguration', '#id_conditionconfigbutton', $fieldid));
212 }
213
214 }
215
216 return $OUTPUT->box(ob_get_clean());
217 }
218
219 /**
220 * Restore instance and map settings.
221 *
222 * @param restore_enrolments_structure_step $step
223 * @param stdClass $data
224 * @param stdClass $course
225 * @param int $oldid
226 */
227 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
228 global $DB;
229 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
230 $merge = false;
231 } else {
232 $merge = array(
233 'courseid' => $data->courseid,
234 'enrol' => $this->get_name(),
235 'roleid' => $data->roleid,
236 'cost' => $data->cost,
237 'currency' => $data->currency,
238 );
239 }
240 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
241 $instance = reset($instances);
242 $instanceid = $instance->id;
243 } else {
244 $instanceid = $this->add_instance($course, (array) $data);
245 }
246 $step->set_mapping('enrol', $oldid, $instanceid);
247 }
248
249 /**
250 * Restore user enrolment.
251 *
252 * @param restore_enrolments_structure_step $step
253 * @param stdClass $data
254 * @param stdClass $instance
255 * @param int $oldinstancestatus
256 * @param int $userid
257 */
258 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
259 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
260 }
261
262 /**
263 * Return an array of valid options for the status.
264 *
265 * @return array
266 */
267 protected function get_status_options() {
268 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
269 ENROL_INSTANCE_DISABLED => get_string('no'));
270 return $options;
271 }
272
273 /**
274 * Return an array of valid options for the roleid.
275 *
276 * @param stdClass $instance
277 * @param context $context
278 * @return array
279 */
280 protected function get_roleid_options($instance, $context) {
281 if ($instance->id) {
282 $roles = get_default_enrol_roles($context, $instance->roleid);
283 } else {
284 $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
285 }
286 return $roles;
287 }
288
289
290 /**
291 * Add elements to the edit instance form.
292 *
293 * @param stdClass $instance
294 * @param MoodleQuickForm $mform
295 * @param context $context
296 * @return bool
297 */
298 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
299
300 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
301 $mform->setType('name', PARAM_TEXT);
302
303 $options = $this->get_status_options();
304 $mform->addElement('select', 'status', get_string('status', 'enrol_fee'), $options);
305 $mform->setDefault('status', $this->get_config('status'));
306
307 $mform->addElement('text', 'cost', get_string('cost', 'enrol_fee'), array('size' => 4));
308 $mform->setType('cost', PARAM_RAW);
309 $mform->setDefault('cost', format_float($this->get_config('cost'), 2, true));
310
311 $supportedcurrencies = $this->get_possible_currencies();
312 $mform->addElement('select', 'currency', get_string('currency', 'enrol_fee'), $supportedcurrencies);
313 $mform->setDefault('currency', $this->get_config('currency'));
314
315 $roles = $this->get_roleid_options($instance, $context);
316 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_fee'), $roles);
317 $mform->setDefault('roleid', $this->get_config('roleid'));
318
319 $options = array('optional' => true, 'defaultunit' => 86400);
320 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_fee'), $options);
321 $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
322 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_fee');
323
324 $options = array('optional' => true);
325 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_fee'), $options);
326 $mform->setDefault('enrolstartdate', 0);
327 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_fee');
328
329 $options = array('optional' => true);
330 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_fee'), $options);
331 $mform->setDefault('enrolenddate', 0);
332 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_fee');
333
334 if (enrol_accessing_via_instance($instance)) {
335 $warningtext = get_string('instanceeditselfwarningtext', 'core_enrol');
336 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warningtext);
337 }
338 }
339
340 /**
341 * Perform custom validation of the data used to edit the instance.
342 *
343 * @param array $data array of ("fieldname"=>value) of submitted data
344 * @param array $files array of uploaded files "element_name"=>tmp_file_path
345 * @param object $instance The instance loaded from the DB
346 * @param context $context The context of the instance we are editing
347 * @return array of "element_name"=>"error_description" if there are errors,
348 * or an empty array if everything is OK.
349 * @return void
350 */
351 public function edit_instance_validation($data, $files, $instance, $context) {
352 $errors = array();
353
354 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
355 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_fee');
356 }
357
358 $cost = str_replace(get_string('decsep', 'langconfig'), '.', $data['cost']);
359 if (!is_numeric($cost)) {
360 $errors['cost'] = get_string('costerror', 'enrol_fee');
361 }
362
363 $validstatus = array_keys($this->get_status_options());
364 $validcurrency = array_keys($this->get_possible_currencies());
365 $validroles = array_keys($this->get_roleid_options($instance, $context));
366 $tovalidate = array(
367 'name' => PARAM_TEXT,
368 'status' => $validstatus,
369 'currency' => $validcurrency,
370 'roleid' => $validroles,
371 'enrolperiod' => PARAM_INT,
372 'enrolstartdate' => PARAM_INT,
373 'enrolenddate' => PARAM_INT
374 );
375
376 $typeerrors = $this->validate_param_types($data, $tovalidate);
377 $errors = array_merge($errors, $typeerrors);
378
379 return $errors;
380 }
381
382 /**
383 * Execute synchronisation.
384 * @param progress_trace $trace
385 * @return int exit code, 0 means ok
386 */
387 public function sync(progress_trace $trace) {
388 $this->process_expirations($trace);
389 return 0;
390 }
391
392 /**
393 * Is it possible to delete enrol instance via standard UI?
394 *
395 * @param stdClass $instance
396 * @return bool
397 */
398 public function can_delete_instance($instance) {
399 $context = context_course::instance($instance->courseid);
400 return has_capability('enrol/fee:config', $context);
401 }
402
403 /**
404 * Is it possible to hide/show enrol instance via standard UI?
405 *
406 * @param stdClass $instance
407 * @return bool
408 */
409 public function can_hide_show_instance($instance) {
410 $context = context_course::instance($instance->courseid);
411 return has_capability('enrol/fee:config', $context);
412 }
413}