MDL-59756 enrol: Swap positions of edit and unenrol actions
[moodle.git] / enrol / paypal / lib.php
CommitLineData
5ea88553
AB
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 * Paypal enrolment plugin.
19 *
20 * This plugin allows you to set up paid courses.
21 *
31ac2aef 22 * @package enrol_paypal
42761bc6
PS
23 * @copyright 2010 Eugene Venter
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5ea88553
AB
25 */
26
97795859 27defined('MOODLE_INTERNAL') || die();
24a62572 28
5ea88553
AB
29/**
30 * Paypal enrolment plugin implementation.
31 * @author Eugene Venter - based on code by Martin Dougiamas and others
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 */
5ea88553
AB
34class enrol_paypal_plugin extends enrol_plugin {
35
0456edb4
PS
36 public function get_currencies() {
37 // See https://www.paypal.com/cgi-bin/webscr?cmd=p/sell/mc/mc_intro-outside,
38 // 3-character ISO-4217: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_currency_codes
39 $codes = array(
40 'AUD', 'BRL', 'CAD', 'CHF', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HUF', 'ILS', 'JPY',
93d31b5d 41 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'RUB', 'SEK', 'SGD', 'THB', 'TRY', 'TWD', 'USD');
0456edb4
PS
42 $currencies = array();
43 foreach ($codes as $c) {
44 $currencies[$c] = new lang_string($c, 'core_currencies');
45 }
46
47 return $currencies;
48 }
49
5bd2219b
PS
50 /**
51 * Returns optional enrolment information icons.
52 *
53 * This is used in course list for quick overview of enrolment options.
54 *
55 * We are not using single instance parameter because sometimes
56 * we might want to prevent icon repetition when multiple instances
57 * of one type exist. One instance may also produce several icons.
58 *
59 * @param array $instances all enrol instances of this type in one course
60 * @return array of pix_icon
61 */
62 public function get_info_icons(array $instances) {
3039181c 63 $found = false;
64 foreach ($instances as $instance) {
65 if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
66 continue;
67 }
68 if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
69 continue;
70 }
71 $found = true;
72 break;
73 }
74 if ($found) {
75 return array(new pix_icon('icon', get_string('pluginname', 'enrol_paypal'), 'enrol_paypal'));
76 }
77 return array();
5bd2219b 78 }
5ea88553 79
42761bc6 80 public function roles_protected() {
1d6ba3f5 81 // users with role assign cap may tweak the roles later
42761bc6
PS
82 return false;
83 }
5ea88553 84
42761bc6
PS
85 public function allow_unenrol(stdClass $instance) {
86 // users with unenrol cap may unenrol other users manually - requires enrol/paypal:unenrol
87 return true;
88 }
5ea88553 89
42761bc6
PS
90 public function allow_manage(stdClass $instance) {
91 // users with manage cap may tweak period and status - requires enrol/paypal:manage
92 return true;
5ea88553
AB
93 }
94
42761bc6
PS
95 public function show_enrolme_link(stdClass $instance) {
96 return ($instance->status == ENROL_INSTANCE_ENABLED);
5ea88553
AB
97 }
98
5ea88553 99 /**
60010fd6 100 * Returns true if the user can add a new instance in this course.
42761bc6 101 * @param int $courseid
60010fd6 102 * @return boolean
5ea88553 103 */
60010fd6 104 public function can_add_instance($courseid) {
55bcef29 105 $context = context_course::instance($courseid, MUST_EXIST);
5ea88553 106
42761bc6 107 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/paypal:config', $context)) {
60010fd6 108 return false;
5ea88553 109 }
5ea88553 110
42761bc6 111 // multiple instances supported - different cost for different roles
60010fd6
DW
112 return true;
113 }
114
115 /**
116 * We are a good plugin and don't invent our own UI/validation code path.
117 *
118 * @return boolean
119 */
120 public function use_standard_editing_ui() {
121 return true;
122 }
123
124 /**
125 * Add new instance of enrol plugin.
126 * @param object $course
127 * @param array $fields instance fields
128 * @return int id of new instance, null if can not be created
129 */
130 public function add_instance($course, array $fields = null) {
131 if ($fields && !empty($fields['cost'])) {
132 $fields['cost'] = unformat_float($fields['cost']);
133 }
134 return parent::add_instance($course, $fields);
135 }
136
137 /**
138 * Update instance of enrol plugin.
139 * @param stdClass $instance
140 * @param stdClass $data modified instance fields
141 * @return boolean
142 */
143 public function update_instance($instance, $data) {
144 if ($data) {
145 $data->cost = unformat_float($data->cost);
146 }
147 return parent::update_instance($instance, $data);
42761bc6 148 }
5ea88553
AB
149
150 /**
151 * Creates course enrol form, checks if form submitted
152 * and enrols user if necessary. It can also redirect.
153 *
154 * @param stdClass $instance
155 * @return string html text, usually a form in a text box
156 */
157 function enrol_page_hook(stdClass $instance) {
158 global $CFG, $USER, $OUTPUT, $PAGE, $DB;
159
160 ob_start();
161
162 if ($DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id))) {
163 return ob_get_clean();
164 }
165
166 if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
167 return ob_get_clean();
168 }
169
170 if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
171 return ob_get_clean();
172 }
173
174 $course = $DB->get_record('course', array('id'=>$instance->courseid));
55bcef29 175 $context = context_course::instance($course->id);
5ea88553 176
8ebbb06a
SH
177 $shortname = format_string($course->shortname, true, array('context' => $context));
178 $strloginto = get_string("loginto", "", $shortname);
5ea88553
AB
179 $strcourses = get_string("courses");
180
5ea88553
AB
181 // Pass $view=true to filter hidden caps if the user cannot see them
182 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
183 '', '', '', '', false, true)) {
184 $users = sort_by_roleassignment_authority($users, $context);
185 $teacher = array_shift($users);
186 } else {
187 $teacher = false;
188 }
189
190 if ( (float) $instance->cost <= 0 ) {
191 $cost = (float) $this->get_config('cost');
192 } else {
193 $cost = (float) $instance->cost;
194 }
195
196 if (abs($cost) < 0.01) { // no cost, other enrolment methods (instances) should be used
197 echo '<p>'.get_string('nocost', 'enrol_paypal').'</p>';
198 } else {
199
ee4df06f
PS
200 // Calculate localised and "." cost, make sure we send PayPal the same value,
201 // please note PayPal expects amount with 2 decimal places and "." separator.
202 $localisedcost = format_float($cost, 2, true);
203 $cost = format_float($cost, 2, false);
204
b3df1764 205 if (isguestuser()) { // force login only for guest user, not real users with guest role
5ea88553
AB
206 if (empty($CFG->loginhttps)) {
207 $wwwroot = $CFG->wwwroot;
208 } else {
209 // This actually is not so secure ;-), 'cause we're
210 // in unencrypted connection...
211 $wwwroot = str_replace("http://", "https://", $CFG->wwwroot);
212 }
213 echo '<div class="mdl-align"><p>'.get_string('paymentrequired').'</p>';
ee4df06f 214 echo '<p><b>'.get_string('cost').": $instance->currency $localisedcost".'</b></p>';
5ea88553
AB
215 echo '<p><a href="'.$wwwroot.'/login/">'.get_string('loginsite').'</a></p>';
216 echo '</div>';
217 } else {
218 //Sanitise some fields before building the PayPal form
32d66135 219 $coursefullname = format_string($course->fullname, true, array('context'=>$context));
8ebbb06a 220 $courseshortname = $shortname;
5ea88553
AB
221 $userfullname = fullname($USER);
222 $userfirstname = $USER->firstname;
223 $userlastname = $USER->lastname;
224 $useraddress = $USER->address;
225 $usercity = $USER->city;
2c3e42fd 226 $instancename = $this->get_instance_name($instance);
5ea88553
AB
227
228 include($CFG->dirroot.'/enrol/paypal/enrol.html');
229 }
230
231 }
232
233 return $OUTPUT->box(ob_get_clean());
42761bc6 234 }
5ea88553 235
471b96c4
PS
236 /**
237 * Restore instance and map settings.
238 *
239 * @param restore_enrolments_structure_step $step
240 * @param stdClass $data
241 * @param stdClass $course
242 * @param int $oldid
243 */
244 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
245 global $DB;
246 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
247 $merge = false;
248 } else {
249 $merge = array(
250 'courseid' => $data->courseid,
251 'enrol' => $this->get_name(),
252 'roleid' => $data->roleid,
253 'cost' => $data->cost,
254 'currency' => $data->currency,
255 );
256 }
257 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
258 $instance = reset($instances);
259 $instanceid = $instance->id;
260 } else {
261 $instanceid = $this->add_instance($course, (array)$data);
262 }
263 $step->set_mapping('enrol', $oldid, $instanceid);
264 }
265
266 /**
267 * Restore user enrolment.
268 *
269 * @param restore_enrolments_structure_step $step
270 * @param stdClass $data
271 * @param stdClass $instance
272 * @param int $oldinstancestatus
273 * @param int $userid
274 */
275 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
276 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
277 }
278
a8e85e05
AG
279 /**
280 * Gets an array of the user enrolment actions
281 *
282 * @param course_enrolment_manager $manager
283 * @param stdClass $ue A user enrolment object
284 * @return array An array of user_enrolment_actions
285 */
286 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
287 $actions = array();
288 $context = $manager->get_context();
289 $instance = $ue->enrolmentinstance;
290 $params = $manager->get_moodlepage()->url->params();
291 $params['ue'] = $ue->id;
b3ef2e51
PS
292 if ($this->allow_manage($instance) && has_capability("enrol/paypal:manage", $context)) {
293 $url = new moodle_url('/enrol/editenrolment.php', $params);
fd0a43be 294 $actionparams = array('class' => 'editenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_EDIT);
da155761
LB
295 $actions[] = new user_enrolment_action(new pix_icon('t/edit', get_string('editenrolment', 'enrol')),
296 get_string('editenrolment', 'enrol'), $url, $actionparams);
00aba5ec
JP
297 }
298 if ($this->allow_unenrol($instance) && has_capability("enrol/paypal:unenrol", $context)) {
299 $url = new moodle_url('/enrol/unenroluser.php', $params);
300 $actionparams = array('class' => 'unenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_UNENROL);
301 $actions[] = new user_enrolment_action(new pix_icon('t/delete', get_string('unenrol', 'enrol')),
302 get_string('unenrol', 'enrol'), $url, $actionparams);
b3ef2e51 303 }
a8e85e05
AG
304 return $actions;
305 }
d9a707ad
PS
306
307 public function cron() {
308 $trace = new text_progress_trace();
309 $this->process_expirations($trace);
310 }
311
60010fd6
DW
312 /**
313 * Return an array of valid options for the status.
314 *
315 * @return array
316 */
317 protected function get_status_options() {
318 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
319 ENROL_INSTANCE_DISABLED => get_string('no'));
320 return $options;
321 }
322
323 /**
324 * Return an array of valid options for the roleid.
325 *
326 * @param stdClass $instance
327 * @param context $context
328 * @return array
329 */
330 protected function get_roleid_options($instance, $context) {
331 if ($instance->id) {
332 $roles = get_default_enrol_roles($context, $instance->roleid);
333 } else {
334 $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
335 }
336 return $roles;
337 }
338
339
340 /**
341 * Add elements to the edit instance form.
342 *
343 * @param stdClass $instance
344 * @param MoodleQuickForm $mform
345 * @param context $context
346 * @return bool
347 */
348 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
349
350 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
351 $mform->setType('name', PARAM_TEXT);
352
353 $options = $this->get_status_options();
354 $mform->addElement('select', 'status', get_string('status', 'enrol_paypal'), $options);
355 $mform->setDefault('status', $this->get_config('status'));
356
357 $mform->addElement('text', 'cost', get_string('cost', 'enrol_paypal'), array('size' => 4));
358 $mform->setType('cost', PARAM_RAW);
359 $mform->setDefault('cost', format_float($this->get_config('cost'), 2, true));
360
361 $paypalcurrencies = $this->get_currencies();
362 $mform->addElement('select', 'currency', get_string('currency', 'enrol_paypal'), $paypalcurrencies);
363 $mform->setDefault('currency', $this->get_config('currency'));
364
365 $roles = $this->get_roleid_options($instance, $context);
366 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_paypal'), $roles);
367 $mform->setDefault('roleid', $this->get_config('roleid'));
368
369 $options = array('optional' => true, 'defaultunit' => 86400);
370 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_paypal'), $options);
371 $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
372 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_paypal');
373
374 $options = array('optional' => true);
375 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_paypal'), $options);
376 $mform->setDefault('enrolstartdate', 0);
377 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_paypal');
378
379 $options = array('optional' => true);
380 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_paypal'), $options);
381 $mform->setDefault('enrolenddate', 0);
382 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_paypal');
383
384 if (enrol_accessing_via_instance($instance)) {
385 $warningtext = get_string('instanceeditselfwarningtext', 'core_enrol');
386 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warningtext);
387 }
388 }
389
390 /**
391 * Perform custom validation of the data used to edit the instance.
392 *
393 * @param array $data array of ("fieldname"=>value) of submitted data
394 * @param array $files array of uploaded files "element_name"=>tmp_file_path
395 * @param object $instance The instance loaded from the DB
396 * @param context $context The context of the instance we are editing
397 * @return array of "element_name"=>"error_description" if there are errors,
398 * or an empty array if everything is OK.
399 * @return void
400 */
401 public function edit_instance_validation($data, $files, $instance, $context) {
402 $errors = array();
403
404 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
405 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_paypal');
406 }
407
408 $cost = str_replace(get_string('decsep', 'langconfig'), '.', $data['cost']);
409 if (!is_numeric($cost)) {
410 $errors['cost'] = get_string('costerror', 'enrol_paypal');
411 }
412
413 $validstatus = array_keys($this->get_status_options());
414 $validcurrency = array_keys($this->get_currencies());
415 $validroles = array_keys($this->get_roleid_options($instance, $context));
416 $tovalidate = array(
417 'name' => PARAM_TEXT,
418 'status' => $validstatus,
419 'currency' => $validcurrency,
420 'roleid' => $validroles,
421 'enrolperiod' => PARAM_INT,
422 'enrolstartdate' => PARAM_INT,
423 'enrolenddate' => PARAM_INT
424 );
425
426 $typeerrors = $this->validate_param_types($data, $tovalidate);
427 $errors = array_merge($errors, $typeerrors);
428
429 return $errors;
430 }
431
d9a707ad
PS
432 /**
433 * Execute synchronisation.
434 * @param progress_trace $trace
435 * @return int exit code, 0 means ok
436 */
437 public function sync(progress_trace $trace) {
438 $this->process_expirations($trace);
439 return 0;
440 }
ee9e079d
DN
441
442 /**
443 * Is it possible to delete enrol instance via standard UI?
444 *
b5a289c4 445 * @param stdClass $instance
ee9e079d
DN
446 * @return bool
447 */
448 public function can_delete_instance($instance) {
449 $context = context_course::instance($instance->courseid);
450 return has_capability('enrol/paypal:config', $context);
451 }
b5a289c4
DNA
452
453 /**
454 * Is it possible to hide/show enrol instance via standard UI?
455 *
456 * @param stdClass $instance
457 * @return bool
458 */
459 public function can_hide_show_instance($instance) {
460 $context = context_course::instance($instance->courseid);
461 return has_capability('enrol/paypal:config', $context);
462 }
42761bc6 463}