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