MDL-32188 question CBM: improve display of the certainty choices
[moodle.git] / enrol / paypal / ipn.php
blob32c67ca0409a8e276cb2c10251ca239392aecd73
1 <?php
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.
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/>.
17 /**
18 * Listens for Instant Payment Notification from PayPal
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.
25 * @package enrol_paypal
26 * @copyright 2010 Eugene Venter
27 * @author Eugene Venter - based on code by others
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 require("../../config.php");
33 require_once("lib.php");
34 require_once($CFG->libdir.'/eventslib.php');
35 require_once($CFG->libdir.'/enrollib.php');
36 require_once($CFG->libdir . '/filelib.php');
39 /// Keep out casual intruders
40 if (empty($_POST) or !empty($_GET)) {
41 print_error("Sorry, you can not use the script that way.");
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
46 /// of user to set it up properly in PayPal business account,
47 /// it is documented in docs wiki.
49 $req = 'cmd=_notify-validate';
51 $data = new stdClass();
53 foreach ($_POST as $key => $value) {
54 $req .= "&$key=".urlencode($value);
55 $data->$key = $value;
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();
67 /// get the user and course records
69 if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
70 message_paypal_error_to_admin("Not a valid user id", $data);
71 die;
74 if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
75 message_paypal_error_to_admin("Not a valid course id", $data);
76 die;
79 if (! $context = context_course::instance($course->id, IGNORE_MISSING)) {
80 message_paypal_error_to_admin("Not a valid context id", $data);
81 die;
84 if (! $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;
89 $plugin = enrol_get_plugin('paypal');
91 /// Open a connection back to PayPal to validate the data
92 $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
93 $c = new curl();
94 $options = array(
95 'returntransfer' => true,
96 'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
97 'timeout' => 30,
98 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1,
100 $location = "https://$paypaladdr/cgi-bin/webscr";
101 $result = $c->post($location, $req, $options);
103 if (!$result) { /// Could not connect to PayPal - FAIL
104 echo "<p>Error: could not access paypal.com</p>";
105 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
106 die;
109 /// Connection is OK, so now we post the data to validate it
111 /// Now read the response and check if everything is OK.
113 if (strlen($result) > 0) {
114 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
117 // check the payment_status and payment_reason
119 // If status is not completed or pending then unenrol the student if already enrolled
120 // and notify admin
122 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
123 $plugin->unenrol_user($plugin_instance, $data->userid);
124 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
125 die;
128 // If currency is incorrectly set then someone maybe trying to cheat the system
130 if ($data->mc_currency != $plugin_instance->currency) {
131 message_paypal_error_to_admin("Currency does not match course settings, received: ".$data->mc_currency, $data);
132 die;
135 // If status is pending and reason is other than echeck then we are on hold until further notice
136 // Email user to let them know. Email admin.
138 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
139 $eventdata = new stdClass();
140 $eventdata->modulename = 'moodle';
141 $eventdata->component = 'enrol_paypal';
142 $eventdata->name = 'paypal_enrolment';
143 $eventdata->userfrom = get_admin();
144 $eventdata->userto = $user;
145 $eventdata->subject = "Moodle: PayPal payment";
146 $eventdata->fullmessage = "Your PayPal payment is pending.";
147 $eventdata->fullmessageformat = FORMAT_PLAIN;
148 $eventdata->fullmessagehtml = '';
149 $eventdata->smallmessage = '';
150 message_send($eventdata);
152 message_paypal_error_to_admin("Payment pending", $data);
153 die;
156 // If our status is not completed or not pending on an echeck clearance then ignore and die
157 // This check is redundant at present but may be useful if paypal extend the return codes in the future
159 if (! ( $data->payment_status == "Completed" or
160 ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
161 die;
164 // At this point we only proceed with a status of completed or pending with a reason of echeck
168 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id))) { // Make sure this transaction doesn't exist already
169 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
170 die;
174 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
175 message_paypal_error_to_admin("Business email is {$data->business} (not ".
176 $plugin->get_config('paypalbusiness').")", $data);
177 die;
181 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
182 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
183 die;
186 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
187 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
188 die;
191 $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
193 // Check that amount paid is the correct amount
194 if ( (float) $plugin_instance->cost <= 0 ) {
195 $cost = (float) $plugin->get_config('cost');
196 } else {
197 $cost = (float) $plugin_instance->cost;
200 // Use the same rounding of floats as on the enrol form.
201 $cost = format_float($cost, 2, false);
203 if ($data->payment_gross < $cost) {
204 message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
205 die;
209 // ALL CLEAR !
211 $DB->insert_record("enrol_paypal", $data);
213 if ($plugin_instance->enrolperiod) {
214 $timestart = time();
215 $timeend = $timestart + $plugin_instance->enrolperiod;
216 } else {
217 $timestart = 0;
218 $timeend = 0;
221 // Enrol user
222 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
224 // Pass $view=true to filter hidden caps if the user cannot see them
225 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
226 '', '', '', '', false, true)) {
227 $users = sort_by_roleassignment_authority($users, $context);
228 $teacher = array_shift($users);
229 } else {
230 $teacher = false;
233 $mailstudents = $plugin->get_config('mailstudents');
234 $mailteachers = $plugin->get_config('mailteachers');
235 $mailadmins = $plugin->get_config('mailadmins');
236 $shortname = format_string($course->shortname, true, array('context' => $context));
239 if (!empty($mailstudents)) {
240 $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
241 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
243 $eventdata = new stdClass();
244 $eventdata->modulename = 'moodle';
245 $eventdata->component = 'enrol_paypal';
246 $eventdata->name = 'paypal_enrolment';
247 $eventdata->userfrom = $teacher;
248 $eventdata->userto = $user;
249 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
250 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
251 $eventdata->fullmessageformat = FORMAT_PLAIN;
252 $eventdata->fullmessagehtml = '';
253 $eventdata->smallmessage = '';
254 message_send($eventdata);
258 if (!empty($mailteachers)) {
259 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
260 $a->user = fullname($user);
262 $eventdata = new stdClass();
263 $eventdata->modulename = 'moodle';
264 $eventdata->component = 'enrol_paypal';
265 $eventdata->name = 'paypal_enrolment';
266 $eventdata->userfrom = $user;
267 $eventdata->userto = $teacher;
268 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
269 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
270 $eventdata->fullmessageformat = FORMAT_PLAIN;
271 $eventdata->fullmessagehtml = '';
272 $eventdata->smallmessage = '';
273 message_send($eventdata);
276 if (!empty($mailadmins)) {
277 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
278 $a->user = fullname($user);
279 $admins = get_admins();
280 foreach ($admins as $admin) {
281 $eventdata = new stdClass();
282 $eventdata->modulename = 'moodle';
283 $eventdata->component = 'enrol_paypal';
284 $eventdata->name = 'paypal_enrolment';
285 $eventdata->userfrom = $user;
286 $eventdata->userto = $admin;
287 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
288 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
289 $eventdata->fullmessageformat = FORMAT_PLAIN;
290 $eventdata->fullmessagehtml = '';
291 $eventdata->smallmessage = '';
292 message_send($eventdata);
296 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
297 $DB->insert_record("enrol_paypal", $data, false);
298 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
302 exit;
305 //--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
308 function message_paypal_error_to_admin($subject, $data) {
309 echo $subject;
310 $admin = get_admin();
311 $site = get_site();
313 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
315 foreach ($data as $key => $value) {
316 $message .= "$key => $value\n";
319 $eventdata = new stdClass();
320 $eventdata->modulename = 'moodle';
321 $eventdata->component = 'enrol_paypal';
322 $eventdata->name = 'paypal_enrolment';
323 $eventdata->userfrom = $admin;
324 $eventdata->userto = $admin;
325 $eventdata->subject = "PAYPAL ERROR: ".$subject;
326 $eventdata->fullmessage = $message;
327 $eventdata->fullmessageformat = FORMAT_PLAIN;
328 $eventdata->fullmessagehtml = '';
329 $eventdata->smallmessage = '';
330 message_send($eventdata);