MDL-41531 enrol_paypal: Fix enrol errors due to non-ASCII characters
[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
24df3e1a 35require("../../config.php");
24a62572 36require_once("lib.php");
24df3e1a
AB
37require_once($CFG->libdir.'/eventslib.php');
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.
43set_exception_handler('enrol_paypal_ipn_exception_handler');
3d970777 44
04f47a89 45/// Keep out casual intruders
24df3e1a
AB
46if (empty($_POST) or !empty($_GET)) {
47 print_error("Sorry, you can not use the script that way.");
48}
04f47a89 49
934bdbee 50/// Read all the data from PayPal and get it ready for later;
51/// we expect only valid UTF-8 encoding, it is the responsibility
24df3e1a 52/// of user to set it up properly in PayPal business account,
934bdbee 53/// it is documented in docs wiki.
04f47a89 54
24df3e1a 55$req = 'cmd=_notify-validate';
04f47a89 56
94b9c2e8 57$data = new stdClass();
934bdbee 58
24df3e1a
AB
59foreach ($_POST as $key => $value) {
60 $req .= "&$key=".urlencode($value);
f07bbccb 61 $data->$key = fix_utf8($value);
24df3e1a 62}
04f47a89 63
24df3e1a
AB
64$custom = explode('-', $data->custom);
65$data->userid = (int)$custom[0];
66$data->courseid = (int)$custom[1];
67$data->instanceid = (int)$custom[2];
68$data->payment_gross = $data->mc_gross;
69$data->payment_currency = $data->mc_currency;
70$data->timeupdated = time();
04f47a89 71
72
597342b0 73/// get the user and course records
74
24df3e1a
AB
75if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
76 message_paypal_error_to_admin("Not a valid user id", $data);
77 die;
78}
597342b0 79
24df3e1a
AB
80if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
81 message_paypal_error_to_admin("Not a valid course id", $data);
82 die;
83}
597342b0 84
55bcef29 85if (! $context = context_course::instance($course->id, IGNORE_MISSING)) {
24df3e1a
AB
86 message_paypal_error_to_admin("Not a valid context id", $data);
87 die;
88}
597342b0 89
24df3e1a
AB
90if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid, "status"=>0))) {
91 message_paypal_error_to_admin("Not a valid instance id", $data);
92 die;
93}
04f47a89 94
24df3e1a
AB
95$plugin = enrol_get_plugin('paypal');
96
97/// Open a connection back to PayPal to validate the data
b7a9c851 98$paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
c3a0938e
TL
99$c = new curl();
100$options = array(
101 'returntransfer' => true,
b7a9c851 102 'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
c3a0938e 103 'timeout' => 30,
b7a9c851 104 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1,
c3a0938e 105);
c3a0938e
TL
106$location = "https://$paypaladdr/cgi-bin/webscr";
107$result = $c->post($location, $req, $options);
24df3e1a 108
c3a0938e 109if (!$result) { /// Could not connect to PayPal - FAIL
24df3e1a
AB
110 echo "<p>Error: could not access paypal.com</p>";
111 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
112 die;
113}
04f47a89 114
115/// Connection is OK, so now we post the data to validate it
116
04f47a89 117/// Now read the response and check if everything is OK.
118
c3a0938e 119if (strlen($result) > 0) {
24df3e1a 120 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
04f47a89 121
04f47a89 122
24df3e1a 123 // check the payment_status and payment_reason
597342b0 124
24df3e1a
AB
125 // If status is not completed or pending then unenrol the student if already enrolled
126 // and notify admin
597342b0 127
24df3e1a
AB
128 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
129 $plugin->unenrol_user($plugin_instance, $data->userid);
130 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
131 die;
132 }
04f47a89 133
24df3e1a 134 // If currency is incorrectly set then someone maybe trying to cheat the system
8e605b76 135
24df3e1a 136 if ($data->mc_currency != $plugin_instance->currency) {
37070863 137 message_paypal_error_to_admin("Currency does not match course settings, received: ".$data->mc_currency, $data);
24df3e1a
AB
138 die;
139 }
8e605b76 140
24df3e1a
AB
141 // If status is pending and reason is other than echeck then we are on hold until further notice
142 // Email user to let them know. Email admin.
143
144 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
94b9c2e8 145 $eventdata = new stdClass();
24df3e1a
AB
146 $eventdata->modulename = 'moodle';
147 $eventdata->component = 'enrol_paypal';
148 $eventdata->name = 'paypal_enrolment';
149 $eventdata->userfrom = get_admin();
150 $eventdata->userto = $user;
151 $eventdata->subject = "Moodle: PayPal payment";
152 $eventdata->fullmessage = "Your PayPal payment is pending.";
153 $eventdata->fullmessageformat = FORMAT_PLAIN;
154 $eventdata->fullmessagehtml = '';
155 $eventdata->smallmessage = '';
156 message_send($eventdata);
157
158 message_paypal_error_to_admin("Payment pending", $data);
159 die;
160 }
597342b0 161
24df3e1a
AB
162 // If our status is not completed or not pending on an echeck clearance then ignore and die
163 // This check is redundant at present but may be useful if paypal extend the return codes in the future
3b120e46 164
24df3e1a
AB
165 if (! ( $data->payment_status == "Completed" or
166 ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
167 die;
168 }
597342b0 169
24df3e1a 170 // At this point we only proceed with a status of completed or pending with a reason of echeck
597342b0 171
597342b0 172
597342b0 173
24df3e1a
AB
174 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id))) { // Make sure this transaction doesn't exist already
175 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
176 die;
597342b0 177
24df3e1a 178 }
597342b0 179
2f1e464a 180 if (core_text::strtolower($data->business) !== core_text::strtolower($plugin->get_config('paypalbusiness'))) { // Check that the email is the one we want it to be
24df3e1a
AB
181 message_paypal_error_to_admin("Business email is {$data->business} (not ".
182 $plugin->get_config('paypalbusiness').")", $data);
183 die;
04f47a89 184
24df3e1a 185 }
934bdbee 186
24df3e1a
AB
187 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
188 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
189 die;
190 }
04f47a89 191
24df3e1a 192 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
0e35ba6f 193 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
24df3e1a
AB
194 die;
195 }
934bdbee 196
55bcef29 197 $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
91d284c1 198
24df3e1a
AB
199 // Check that amount paid is the correct amount
200 if ( (float) $plugin_instance->cost <= 0 ) {
201 $cost = (float) $plugin->get_config('cost');
202 } else {
203 $cost = (float) $plugin_instance->cost;
204 }
04f47a89 205
ee4df06f
PS
206 // Use the same rounding of floats as on the enrol form.
207 $cost = format_float($cost, 2, false);
208
24df3e1a 209 if ($data->payment_gross < $cost) {
24df3e1a
AB
210 message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
211 die;
04f47a89 212
24df3e1a 213 }
f07bbccb 214 // Use the queried course's full name for the item_name field.
215 $data->item_name = $course->fullname;
3d970777 216
24df3e1a 217 // ALL CLEAR !
04f47a89 218
24df3e1a 219 $DB->insert_record("enrol_paypal", $data);
04f47a89 220
24df3e1a
AB
221 if ($plugin_instance->enrolperiod) {
222 $timestart = time();
223 $timeend = $timestart + $plugin_instance->enrolperiod;
224 } else {
225 $timestart = 0;
226 $timeend = 0;
227 }
0f093efa 228
24df3e1a
AB
229 // Enrol user
230 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
04f47a89 231
24df3e1a
AB
232 // Pass $view=true to filter hidden caps if the user cannot see them
233 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
234 '', '', '', '', false, true)) {
235 $users = sort_by_roleassignment_authority($users, $context);
236 $teacher = array_shift($users);
237 } else {
238 $teacher = false;
239 }
240
241 $mailstudents = $plugin->get_config('mailstudents');
242 $mailteachers = $plugin->get_config('mailteachers');
243 $mailadmins = $plugin->get_config('mailadmins');
8ebbb06a
SH
244 $shortname = format_string($course->shortname, true, array('context' => $context));
245
24df3e1a
AB
246
247 if (!empty($mailstudents)) {
32a8bcc4 248 $a = new stdClass();
91d284c1 249 $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
250 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
251
94b9c2e8 252 $eventdata = new stdClass();
24df3e1a
AB
253 $eventdata->modulename = 'moodle';
254 $eventdata->component = 'enrol_paypal';
255 $eventdata->name = 'paypal_enrolment';
530debc0 256 $eventdata->userfrom = empty($teacher) ? core_user::get_support_user() : $teacher;
24df3e1a 257 $eventdata->userto = $user;
f619fcda 258 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
24df3e1a
AB
259 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
260 $eventdata->fullmessageformat = FORMAT_PLAIN;
261 $eventdata->fullmessagehtml = '';
262 $eventdata->smallmessage = '';
263 message_send($eventdata);
04f47a89 264
04f47a89 265 }
04f47a89 266
32a8bcc4 267 if (!empty($mailteachers) && !empty($teacher)) {
91d284c1 268 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
269 $a->user = fullname($user);
270
94b9c2e8 271 $eventdata = new stdClass();
24df3e1a
AB
272 $eventdata->modulename = 'moodle';
273 $eventdata->component = 'enrol_paypal';
274 $eventdata->name = 'paypal_enrolment';
275 $eventdata->userfrom = $user;
276 $eventdata->userto = $teacher;
f619fcda
PS
277 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
278 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
24df3e1a
AB
279 $eventdata->fullmessageformat = FORMAT_PLAIN;
280 $eventdata->fullmessagehtml = '';
281 $eventdata->smallmessage = '';
282 message_send($eventdata);
283 }
284
285 if (!empty($mailadmins)) {
91d284c1 286 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
24df3e1a
AB
287 $a->user = fullname($user);
288 $admins = get_admins();
289 foreach ($admins as $admin) {
94b9c2e8 290 $eventdata = new stdClass();
24df3e1a
AB
291 $eventdata->modulename = 'moodle';
292 $eventdata->component = 'enrol_paypal';
293 $eventdata->name = 'paypal_enrolment';
294 $eventdata->userfrom = $user;
295 $eventdata->userto = $admin;
f619fcda
PS
296 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
297 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
24df3e1a
AB
298 $eventdata->fullmessageformat = FORMAT_PLAIN;
299 $eventdata->fullmessagehtml = '';
300 $eventdata->smallmessage = '';
301 message_send($eventdata);
302 }
303 }
304
305 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
306 $DB->insert_record("enrol_paypal", $data, false);
307 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
308 }
309}
04f47a89 310
24df3e1a 311exit;
04f47a89 312
313
24df3e1a 314//--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
04f47a89 315
316
3b120e46 317function message_paypal_error_to_admin($subject, $data) {
24df3e1a 318 echo $subject;
04f47a89 319 $admin = get_admin();
8f425a8f 320 $site = get_site();
04f47a89 321
322 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
323
324 foreach ($data as $key => $value) {
325 $message .= "$key => $value\n";
326 }
327
94b9c2e8 328 $eventdata = new stdClass();
3b120e46 329 $eventdata->modulename = 'moodle';
24df3e1a
AB
330 $eventdata->component = 'enrol_paypal';
331 $eventdata->name = 'paypal_enrolment';
3b120e46 332 $eventdata->userfrom = $admin;
333 $eventdata->userto = $admin;
334 $eventdata->subject = "PAYPAL ERROR: ".$subject;
335 $eventdata->fullmessage = $message;
336 $eventdata->fullmessageformat = FORMAT_PLAIN;
337 $eventdata->fullmessagehtml = '';
338 $eventdata->smallmessage = '';
7c7d3afa 339 message_send($eventdata);
04f47a89 340}
341
af549df9
PS
342/**
343 * Silent exception handler.
344 *
345 * @param Exception $ex
346 * @return void - does not return. Terminates execution!
347 */
348function enrol_paypal_ipn_exception_handler($ex) {
349 $info = get_exception_info($ex);
4317f92f 350
af549df9
PS
351 $logerrmsg = "enrol_paypal IPN exception handler: ".$info->message;
352 if (debugging('', DEBUG_NORMAL)) {
353 $logerrmsg .= ' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
354 }
355 error_log($logerrmsg);
356
357 exit(0);
358}