MDL-55188 events: First deprecation of eventslib.php
[moodle.git] / enrol / paypal / ipn.php
CommitLineData
4317f92f 1<?php
24df3e1a
AB
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/**
24a62572
PS
18 * Listens for Instant Payment Notification from PayPal
19 *
20 * This script waits for Payment notification from PayPal,
21 * then double checks that data by sending it back to PayPal.
22 * If PayPal verifies this then it sets up the enrolment for that
23 * user.
24 *
31ac2aef 25 * @package enrol_paypal
24df3e1a 26 * @copyright 2010 Eugene Venter
24a62572
PS
27 * @author Eugene Venter - based on code by others
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24df3e1a 29 */
04f47a89 30
af549df9
PS
31// Disable moodle specific debug messages and any errors in output,
32// comment out when debugging or better look into error log!
33define('NO_DEBUG_DISPLAY', true);
04f47a89 34
39a5fbeb 35// @codingStandardsIgnoreLine This script does not require login.
24df3e1a 36require("../../config.php");
24a62572 37require_once("lib.php");
24df3e1a 38require_once($CFG->libdir.'/enrollib.php');
c3a0938e 39require_once($CFG->libdir . '/filelib.php');
24df3e1a 40
af549df9
PS
41// PayPal does not like when we return error messages here,
42// the custom handler just logs exceptions and stops.
4abbb418 43set_exception_handler(\enrol_paypal\util::get_exception_handler());
3d970777 44
39a5fbeb
DM
45// Make sure we are enabled in the first place.
46if (!enrol_is_enabled('paypal')) {
47 http_response_code(503);
48 throw new moodle_exception('errdisabled', 'enrol_paypal');
49}
50
04f47a89 51/// Keep out casual intruders
24df3e1a 52if (empty($_POST) or !empty($_GET)) {
39a5fbeb
DM
53 http_response_code(400);
54 throw new moodle_exception('invalidrequest', 'core_error');
24df3e1a 55}
04f47a89 56
934bdbee 57/// Read all the data from PayPal and get it ready for later;
58/// we expect only valid UTF-8 encoding, it is the responsibility
24df3e1a 59/// of user to set it up properly in PayPal business account,
934bdbee 60/// it is documented in docs wiki.
04f47a89 61
24df3e1a 62$req = 'cmd=_notify-validate';
04f47a89 63
94b9c2e8 64$data = new stdClass();
934bdbee 65
24df3e1a 66foreach ($_POST as $key => $value) {
d12cdcbd
DM
67 if ($key !== clean_param($key, PARAM_ALPHANUMEXT)) {
68 throw new moodle_exception('invalidrequest', 'core_error', '', null, $key);
69 }
70 if (is_array($value)) {
71 throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Unexpected array param: '.$key);
72 }
24df3e1a 73 $req .= "&$key=".urlencode($value);
f07bbccb 74 $data->$key = fix_utf8($value);
24df3e1a 75}
04f47a89 76
d12cdcbd
DM
77if (empty($data->custom)) {
78 throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Missing request param: custom');
79}
80
24df3e1a 81$custom = explode('-', $data->custom);
d12cdcbd
DM
82unset($data->custom);
83
84if (empty($custom) || count($custom) < 3) {
85 throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Invalid value of the request param: custom');
86}
87
24df3e1a
AB
88$data->userid = (int)$custom[0];
89$data->courseid = (int)$custom[1];
90$data->instanceid = (int)$custom[2];
91$data->payment_gross = $data->mc_gross;
92$data->payment_currency = $data->mc_currency;
93$data->timeupdated = time();
04f47a89 94
39a5fbeb
DM
95$user = $DB->get_record("user", array("id" => $data->userid), "*", MUST_EXIST);
96$course = $DB->get_record("course", array("id" => $data->courseid), "*", MUST_EXIST);
97$context = context_course::instance($course->id, MUST_EXIST);
597342b0 98
73b2a94c 99$PAGE->set_context($context);
4abbb418 100
39a5fbeb 101$plugin_instance = $DB->get_record("enrol", array("id" => $data->instanceid, "enrol" => "paypal", "status" => 0), "*", MUST_EXIST);
24df3e1a
AB
102$plugin = enrol_get_plugin('paypal');
103
104/// Open a connection back to PayPal to validate the data
a38da470 105$paypaladdr = empty($CFG->usepaypalsandbox) ? 'ipnpb.paypal.com' : 'ipnpb.sandbox.paypal.com';
c3a0938e
TL
106$c = new curl();
107$options = array(
108 'returntransfer' => true,
b7a9c851 109 'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
c3a0938e 110 'timeout' => 30,
b7a9c851 111 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1,
c3a0938e 112);
c3a0938e
TL
113$location = "https://$paypaladdr/cgi-bin/webscr";
114$result = $c->post($location, $req, $options);
24df3e1a 115
39a5fbeb
DM
116if ($c->get_errno()) {
117 throw new moodle_exception('errpaypalconnect', 'enrol_paypal', '', array('url' => $paypaladdr, 'result' => $result),
118 json_encode($data));
24df3e1a 119}
04f47a89 120
121/// Connection is OK, so now we post the data to validate it
122
04f47a89 123/// Now read the response and check if everything is OK.
124
c3a0938e 125if (strlen($result) > 0) {
24df3e1a 126 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
04f47a89 127
04f47a89 128
24df3e1a 129 // check the payment_status and payment_reason
597342b0 130
24df3e1a
AB
131 // If status is not completed or pending then unenrol the student if already enrolled
132 // and notify admin
597342b0 133
24df3e1a
AB
134 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
135 $plugin->unenrol_user($plugin_instance, $data->userid);
4abbb418
CB
136 \enrol_paypal\util::message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course",
137 $data);
24df3e1a
AB
138 die;
139 }
04f47a89 140
24df3e1a 141 // If currency is incorrectly set then someone maybe trying to cheat the system
8e605b76 142
24df3e1a 143 if ($data->mc_currency != $plugin_instance->currency) {
4abbb418
CB
144 \enrol_paypal\util::message_paypal_error_to_admin(
145 "Currency does not match course settings, received: ".$data->mc_currency,
146 $data);
24df3e1a
AB
147 die;
148 }
8e605b76 149
24df3e1a
AB
150 // If status is pending and reason is other than echeck then we are on hold until further notice
151 // Email user to let them know. Email admin.
152
153 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
cc350fd9 154 $eventdata = new \core\message\message();
880fc15b 155 $eventdata->courseid = empty($data->courseid) ? SITEID : $data->courseid;
24df3e1a
AB
156 $eventdata->modulename = 'moodle';
157 $eventdata->component = 'enrol_paypal';
158 $eventdata->name = 'paypal_enrolment';
159 $eventdata->userfrom = get_admin();
160 $eventdata->userto = $user;
161 $eventdata->subject = "Moodle: PayPal payment";
162 $eventdata->fullmessage = "Your PayPal payment is pending.";
163 $eventdata->fullmessageformat = FORMAT_PLAIN;
164 $eventdata->fullmessagehtml = '';
165 $eventdata->smallmessage = '';
166 message_send($eventdata);
167
4abbb418 168 \enrol_paypal\util::message_paypal_error_to_admin("Payment pending", $data);
24df3e1a
AB
169 die;
170 }
597342b0 171
24df3e1a
AB
172 // If our status is not completed or not pending on an echeck clearance then ignore and die
173 // This check is redundant at present but may be useful if paypal extend the return codes in the future
3b120e46 174
24df3e1a
AB
175 if (! ( $data->payment_status == "Completed" or
176 ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
177 die;
178 }
597342b0 179
24df3e1a 180 // At this point we only proceed with a status of completed or pending with a reason of echeck
597342b0 181
47ea60fd
DM
182 // Make sure this transaction doesn't exist already.
183 if ($existing = $DB->get_record("enrol_paypal", array("txn_id" => $data->txn_id), "*", IGNORE_MULTIPLE)) {
4abbb418 184 \enrol_paypal\util::message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
24df3e1a 185 die;
47ea60fd 186 }
597342b0 187
47ea60fd
DM
188 // Check that the receiver email is the one we want it to be.
189 if (isset($data->business)) {
190 $recipient = $data->business;
191 } else if (isset($data->receiver_email)) {
192 $recipient = $data->receiver_email;
193 } else {
194 $recipient = 'empty';
24df3e1a 195 }
597342b0 196
47ea60fd
DM
197 if (core_text::strtolower($recipient) !== core_text::strtolower($plugin->get_config('paypalbusiness'))) {
198 \enrol_paypal\util::message_paypal_error_to_admin("Business email is {$recipient} (not ".
24df3e1a
AB
199 $plugin->get_config('paypalbusiness').")", $data);
200 die;
24df3e1a 201 }
934bdbee 202
24df3e1a 203 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
4abbb418 204 \enrol_paypal\util::message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
24df3e1a
AB
205 die;
206 }
04f47a89 207
24df3e1a 208 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
4abbb418 209 \enrol_paypal\util::message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
24df3e1a
AB
210 die;
211 }
934bdbee 212
55bcef29 213 $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
91d284c1 214
24df3e1a
AB
215 // Check that amount paid is the correct amount
216 if ( (float) $plugin_instance->cost <= 0 ) {
217 $cost = (float) $plugin->get_config('cost');
218 } else {
219 $cost = (float) $plugin_instance->cost;
220 }
04f47a89 221
ee4df06f
PS
222 // Use the same rounding of floats as on the enrol form.
223 $cost = format_float($cost, 2, false);
224
24df3e1a 225 if ($data->payment_gross < $cost) {
4abbb418 226 \enrol_paypal\util::message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
24df3e1a 227 die;
04f47a89 228
24df3e1a 229 }
f07bbccb 230 // Use the queried course's full name for the item_name field.
231 $data->item_name = $course->fullname;
3d970777 232
24df3e1a 233 // ALL CLEAR !
04f47a89 234
24df3e1a 235 $DB->insert_record("enrol_paypal", $data);
04f47a89 236
24df3e1a
AB
237 if ($plugin_instance->enrolperiod) {
238 $timestart = time();
239 $timeend = $timestart + $plugin_instance->enrolperiod;
240 } else {
241 $timestart = 0;
242 $timeend = 0;
243 }
0f093efa 244
24df3e1a
AB
245 // Enrol user
246 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
04f47a89 247
24df3e1a
AB
248 // Pass $view=true to filter hidden caps if the user cannot see them
249 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
250 '', '', '', '', false, true)) {
251 $users = sort_by_roleassignment_authority($users, $context);
252 $teacher = array_shift($users);
253 } else {
254 $teacher = false;
255 }
256
257 $mailstudents = $plugin->get_config('mailstudents');
258 $mailteachers = $plugin->get_config('mailteachers');
259 $mailadmins = $plugin->get_config('mailadmins');
8ebbb06a
SH
260 $shortname = format_string($course->shortname, true, array('context' => $context));
261
24df3e1a
AB
262
263 if (!empty($mailstudents)) {
32a8bcc4 264 $a = new stdClass();
91d284c1 265 $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
266 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
267
cc350fd9 268 $eventdata = new \core\message\message();
880fc15b 269 $eventdata->courseid = $course->id;
24df3e1a
AB
270 $eventdata->modulename = 'moodle';
271 $eventdata->component = 'enrol_paypal';
272 $eventdata->name = 'paypal_enrolment';
253ae230 273 $eventdata->userfrom = empty($teacher) ? core_user::get_noreply_user() : $teacher;
24df3e1a 274 $eventdata->userto = $user;
f619fcda 275 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
24df3e1a
AB
276 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
277 $eventdata->fullmessageformat = FORMAT_PLAIN;
278 $eventdata->fullmessagehtml = '';
279 $eventdata->smallmessage = '';
280 message_send($eventdata);
04f47a89 281
04f47a89 282 }
04f47a89 283
32a8bcc4 284 if (!empty($mailteachers) && !empty($teacher)) {
91d284c1 285 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
286 $a->user = fullname($user);
287
cc350fd9 288 $eventdata = new \core\message\message();
880fc15b 289 $eventdata->courseid = $course->id;
24df3e1a
AB
290 $eventdata->modulename = 'moodle';
291 $eventdata->component = 'enrol_paypal';
292 $eventdata->name = 'paypal_enrolment';
293 $eventdata->userfrom = $user;
294 $eventdata->userto = $teacher;
f619fcda
PS
295 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
296 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
24df3e1a
AB
297 $eventdata->fullmessageformat = FORMAT_PLAIN;
298 $eventdata->fullmessagehtml = '';
299 $eventdata->smallmessage = '';
300 message_send($eventdata);
301 }
302
303 if (!empty($mailadmins)) {
91d284c1 304 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
305 $a->user = fullname($user);
306 $admins = get_admins();
307 foreach ($admins as $admin) {
cc350fd9 308 $eventdata = new \core\message\message();
880fc15b 309 $eventdata->courseid = $course->id;
24df3e1a
AB
310 $eventdata->modulename = 'moodle';
311 $eventdata->component = 'enrol_paypal';
312 $eventdata->name = 'paypal_enrolment';
313 $eventdata->userfrom = $user;
314 $eventdata->userto = $admin;
f619fcda
PS
315 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
316 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
24df3e1a
AB
317 $eventdata->fullmessageformat = FORMAT_PLAIN;
318 $eventdata->fullmessagehtml = '';
319 $eventdata->smallmessage = '';
320 message_send($eventdata);
321 }
322 }
323
324 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
325 $DB->insert_record("enrol_paypal", $data, false);
39a5fbeb 326 throw new moodle_exception('erripninvalid', 'enrol_paypal', '', null, json_encode($data));
24df3e1a
AB
327 }
328}