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