MDL-23502 fixed package info
[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/**
18 * @package enrol_paypal
19 * @copyright 2010 Eugene Venter
20 * @author Eugene Venter - based on code by others
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 */
04f47a89 23
24/**
5599d142 25* Listens for Instant Payment Notification from PayPal
04f47a89 26*
5599d142 27* This script waits for Payment notification from PayPal,
28* then double checks that data by sending it back to PayPal.
29* If PayPal verifies this then it sets up the enrolment for that
24df3e1a 30* user.
934bdbee 31*
04f47a89 32*/
33
34
24df3e1a
AB
35require("../../config.php");
36require("lib.php");
37require_once($CFG->libdir.'/eventslib.php');
38require_once($CFG->libdir.'/enrollib.php');
39
3d970777 40
04f47a89 41/// Keep out casual intruders
24df3e1a
AB
42if (empty($_POST) or !empty($_GET)) {
43 print_error("Sorry, you can not use the script that way.");
44}
04f47a89 45
934bdbee 46/// Read all the data from PayPal and get it ready for later;
47/// we expect only valid UTF-8 encoding, it is the responsibility
24df3e1a 48/// of user to set it up properly in PayPal business account,
934bdbee 49/// it is documented in docs wiki.
04f47a89 50
24df3e1a 51$req = 'cmd=_notify-validate';
04f47a89 52
24df3e1a 53$data = new object();
934bdbee 54
24df3e1a
AB
55foreach ($_POST as $key => $value) {
56 $req .= "&$key=".urlencode($value);
57 $data->$key = $value;
58}
04f47a89 59
24df3e1a
AB
60$custom = explode('-', $data->custom);
61$data->userid = (int)$custom[0];
62$data->courseid = (int)$custom[1];
63$data->instanceid = (int)$custom[2];
64$data->payment_gross = $data->mc_gross;
65$data->payment_currency = $data->mc_currency;
66$data->timeupdated = time();
04f47a89 67
68
597342b0 69/// get the user and course records
70
24df3e1a
AB
71if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
72 message_paypal_error_to_admin("Not a valid user id", $data);
73 die;
74}
597342b0 75
24df3e1a
AB
76if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
77 message_paypal_error_to_admin("Not a valid course id", $data);
78 die;
79}
597342b0 80
24df3e1a
AB
81if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
82 message_paypal_error_to_admin("Not a valid context id", $data);
83 die;
84}
597342b0 85
24df3e1a
AB
86if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid, "status"=>0))) {
87 message_paypal_error_to_admin("Not a valid instance id", $data);
88 die;
89}
04f47a89 90
24df3e1a
AB
91$plugin = enrol_get_plugin('paypal');
92
93/// Open a connection back to PayPal to validate the data
94$header = '';
95$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
96$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
97$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
98$paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
99$fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
100
101if (!$fp) { /// Could not open a socket to PayPal - FAIL
102 echo "<p>Error: could not access paypal.com</p>";
103 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
104 die;
105}
04f47a89 106
107/// Connection is OK, so now we post the data to validate it
108
24df3e1a 109fputs ($fp, $header.$req);
04f47a89 110
111/// Now read the response and check if everything is OK.
112
24df3e1a
AB
113while (!feof($fp)) {
114 $result = fgets($fp, 1024);
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
AB
131 if ($data->mc_currency != $plugin_instance->currency) {
132 message_paypal_error_to_admin("Currency does not match course settings, received: ".addslashes($data->mc_currency), $data);
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") {
140 $eventdata = new object();
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
24df3e1a
AB
175 if ($data->business != $plugin->get_config('paypalbusiness')) { // Check that the email is the one we want it to be
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
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');
233
234 if (!empty($mailstudents)) {
235 $a->coursename = $course->fullname;
236 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
237
238 $eventdata = new object();
239 $eventdata->modulename = 'moodle';
240 $eventdata->component = 'enrol_paypal';
241 $eventdata->name = 'paypal_enrolment';
242 $eventdata->userfrom = $teacher;
243 $eventdata->userto = $user;
244 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
245 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
246 $eventdata->fullmessageformat = FORMAT_PLAIN;
247 $eventdata->fullmessagehtml = '';
248 $eventdata->smallmessage = '';
249 message_send($eventdata);
04f47a89 250
04f47a89 251 }
04f47a89 252
24df3e1a
AB
253 if (!empty($mailteachers)) {
254 $a->course = $course->fullname;
255 $a->user = fullname($user);
256
257 $eventdata = new object();
258 $eventdata->modulename = 'moodle';
259 $eventdata->component = 'enrol_paypal';
260 $eventdata->name = 'paypal_enrolment';
261 $eventdata->userfrom = $user;
262 $eventdata->userto = $teacher;
263 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
264 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
265 $eventdata->fullmessageformat = FORMAT_PLAIN;
266 $eventdata->fullmessagehtml = '';
267 $eventdata->smallmessage = '';
268 message_send($eventdata);
269 }
270
271 if (!empty($mailadmins)) {
272 $a->course = $course->fullname;
273 $a->user = fullname($user);
274 $admins = get_admins();
275 foreach ($admins as $admin) {
276 $eventdata = new object();
277 $eventdata->modulename = 'moodle';
278 $eventdata->component = 'enrol_paypal';
279 $eventdata->name = 'paypal_enrolment';
280 $eventdata->userfrom = $user;
281 $eventdata->userto = $admin;
282 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
283 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
284 $eventdata->fullmessageformat = FORMAT_PLAIN;
285 $eventdata->fullmessagehtml = '';
286 $eventdata->smallmessage = '';
287 message_send($eventdata);
288 }
289 }
290
291 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
292 $DB->insert_record("enrol_paypal", $data, false);
293 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
294 }
295}
04f47a89 296
24df3e1a
AB
297fclose($fp);
298exit;
04f47a89 299
300
24df3e1a 301//--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
04f47a89 302
303
3b120e46 304function message_paypal_error_to_admin($subject, $data) {
24df3e1a 305 echo $subject;
04f47a89 306 $admin = get_admin();
8f425a8f 307 $site = get_site();
04f47a89 308
309 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
310
311 foreach ($data as $key => $value) {
312 $message .= "$key => $value\n";
313 }
314
3b120e46 315 $eventdata = new object();
316 $eventdata->modulename = 'moodle';
24df3e1a
AB
317 $eventdata->component = 'enrol_paypal';
318 $eventdata->name = 'paypal_enrolment';
3b120e46 319 $eventdata->userfrom = $admin;
320 $eventdata->userto = $admin;
321 $eventdata->subject = "PAYPAL ERROR: ".$subject;
322 $eventdata->fullmessage = $message;
323 $eventdata->fullmessageformat = FORMAT_PLAIN;
324 $eventdata->fullmessagehtml = '';
325 $eventdata->smallmessage = '';
7c7d3afa 326 message_send($eventdata);
04f47a89 327}
328
4317f92f 329