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.
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 * 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_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
29 */
30
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);
34
35// @codingStandardsIgnoreLine This script does not require login.
36require("../../config.php");
37require_once("lib.php");
38require_once($CFG->libdir.'/enrollib.php');
39require_once($CFG->libdir . '/filelib.php');
40
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\util::get_exception_handler());
44
45// Make sure we are enabled in the first place.
46if (!enrol_is_enabled('paypal')) {
47    http_response_code(503);
48    throw new moodle_exception('errdisabled', 'enrol_paypal');
49}
50
51/// Keep out casual intruders
52if (empty($_POST) or !empty($_GET)) {
53    http_response_code(400);
54    throw new moodle_exception('invalidrequest', 'core_error');
55}
56
57/// Read all the data from PayPal and get it ready for later;
58/// we expect only valid UTF-8 encoding, it is the responsibility
59/// of user to set it up properly in PayPal business account,
60/// it is documented in docs wiki.
61
62$req = 'cmd=_notify-validate';
63
64$data = new stdClass();
65
66foreach ($_POST as $key => $value) {
67    if ($key !== clean_param($key, PARAM_ALPHANUMEXT)) {
68        throw new moodle_exception('invalidrequest', 'core_error', '', null, $key);
69    }
70    if (is_array($value)) {
71        throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Unexpected array param: '.$key);
72    }
73    $req .= "&$key=".urlencode($value);
74    $data->$key = fix_utf8($value);
75}
76
77if (empty($data->custom)) {
78    throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Missing request param: custom');
79}
80
81$custom = explode('-', $data->custom);
82unset($data->custom);
83
84if (empty($custom) || count($custom) < 3) {
85    throw new moodle_exception('invalidrequest', 'core_error', '', null, 'Invalid value of the request param: custom');
86}
87
88$data->userid           = (int)$custom[0];
89$data->courseid         = (int)$custom[1];
90$data->instanceid       = (int)$custom[2];
91$data->payment_gross    = $data->mc_gross;
92$data->payment_currency = $data->mc_currency;
93$data->timeupdated      = time();
94
95$user = $DB->get_record("user", array("id" => $data->userid), "*", MUST_EXIST);
96$course = $DB->get_record("course", array("id" => $data->courseid), "*", MUST_EXIST);
97$context = context_course::instance($course->id, MUST_EXIST);
98
99$PAGE->set_context($context);
100
101$plugin_instance = $DB->get_record("enrol", array("id" => $data->instanceid, "enrol" => "paypal", "status" => 0), "*", MUST_EXIST);
102$plugin = enrol_get_plugin('paypal');
103
104/// Open a connection back to PayPal to validate the data
105$paypaladdr = empty($CFG->usepaypalsandbox) ? 'ipnpb.paypal.com' : 'ipnpb.sandbox.paypal.com';
106$c = new curl();
107$options = array(
108    'returntransfer' => true,
109    'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
110    'timeout' => 30,
111    'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1,
112);
113$location = "https://$paypaladdr/cgi-bin/webscr";
114$result = $c->post($location, $req, $options);
115
116if ($c->get_errno()) {
117    throw new moodle_exception('errpaypalconnect', 'enrol_paypal', '', array('url' => $paypaladdr, 'result' => $result),
118        json_encode($data));
119}
120
121/// Connection is OK, so now we post the data to validate it
122
123/// Now read the response and check if everything is OK.
124
125if (strlen($result) > 0) {
126    if (strcmp($result, "VERIFIED") == 0) {          // VALID PAYMENT!
127
128
129        // check the payment_status and payment_reason
130
131        // If status is not completed or pending then unenrol the student if already enrolled
132        // and notify admin
133
134        if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
135            $plugin->unenrol_user($plugin_instance, $data->userid);
136            \enrol_paypal\util::message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course",
137                                                              $data);
138            die;
139        }
140
141        // If currency is incorrectly set then someone maybe trying to cheat the system
142
143        if ($data->mc_currency != $plugin_instance->currency) {
144            \enrol_paypal\util::message_paypal_error_to_admin(
145                "Currency does not match course settings, received: ".$data->mc_currency,
146                $data);
147            die;
148        }
149
150        // If status is pending and reason is other than echeck then we are on hold until further notice
151        // Email user to let them know. Email admin.
152
153        if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
154            $eventdata = new \core\message\message();
155            $eventdata->courseid          = empty($data->courseid) ? SITEID : $data->courseid;
156            $eventdata->modulename        = 'moodle';
157            $eventdata->component         = 'enrol_paypal';
158            $eventdata->name              = 'paypal_enrolment';
159            $eventdata->userfrom          = get_admin();
160            $eventdata->userto            = $user;
161            $eventdata->subject           = "Moodle: PayPal payment";
162            $eventdata->fullmessage       = "Your PayPal payment is pending.";
163            $eventdata->fullmessageformat = FORMAT_PLAIN;
164            $eventdata->fullmessagehtml   = '';
165            $eventdata->smallmessage      = '';
166            message_send($eventdata);
167
168            \enrol_paypal\util::message_paypal_error_to_admin("Payment pending", $data);
169            die;
170        }
171
172        // If our status is not completed or not pending on an echeck clearance then ignore and die
173        // This check is redundant at present but may be useful if paypal extend the return codes in the future
174
175        if (! ( $data->payment_status == "Completed" or
176               ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
177            die;
178        }
179
180        // At this point we only proceed with a status of completed or pending with a reason of echeck
181
182        // Make sure this transaction doesn't exist already.
183        if ($existing = $DB->get_record("enrol_paypal", array("txn_id" => $data->txn_id), "*", IGNORE_MULTIPLE)) {
184            \enrol_paypal\util::message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
185            die;
186        }
187
188        // Check that the receiver email is the one we want it to be.
189        if (isset($data->business)) {
190            $recipient = $data->business;
191        } else if (isset($data->receiver_email)) {
192            $recipient = $data->receiver_email;
193        } else {
194            $recipient = 'empty';
195        }
196
197        if (core_text::strtolower($recipient) !== core_text::strtolower($plugin->get_config('paypalbusiness'))) {
198            \enrol_paypal\util::message_paypal_error_to_admin("Business email is {$recipient} (not ".
199                    $plugin->get_config('paypalbusiness').")", $data);
200            die;
201        }
202
203        if (!$user = $DB->get_record('user', array('id'=>$data->userid))) {   // Check that user exists
204            \enrol_paypal\util::message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
205            die;
206        }
207
208        if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
209            \enrol_paypal\util::message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
210            die;
211        }
212
213        $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
214
215        // Check that amount paid is the correct amount
216        if ( (float) $plugin_instance->cost <= 0 ) {
217            $cost = (float) $plugin->get_config('cost');
218        } else {
219            $cost = (float) $plugin_instance->cost;
220        }
221
222        // Use the same rounding of floats as on the enrol form.
223        $cost = format_float($cost, 2, false);
224
225        if ($data->payment_gross < $cost) {
226            \enrol_paypal\util::message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
227            die;
228
229        }
230        // Use the queried course's full name for the item_name field.
231        $data->item_name = $course->fullname;
232
233        // ALL CLEAR !
234
235        $DB->insert_record("enrol_paypal", $data);
236
237        if ($plugin_instance->enrolperiod) {
238            $timestart = time();
239            $timeend   = $timestart + $plugin_instance->enrolperiod;
240        } else {
241            $timestart = 0;
242            $timeend   = 0;
243        }
244
245        // Enrol user
246        $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
247
248        // Pass $view=true to filter hidden caps if the user cannot see them
249        if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
250                                             '', '', '', '', false, true)) {
251            $users = sort_by_roleassignment_authority($users, $context);
252            $teacher = array_shift($users);
253        } else {
254            $teacher = false;
255        }
256
257        $mailstudents = $plugin->get_config('mailstudents');
258        $mailteachers = $plugin->get_config('mailteachers');
259        $mailadmins   = $plugin->get_config('mailadmins');
260        $shortname = format_string($course->shortname, true, array('context' => $context));
261
262
263        if (!empty($mailstudents)) {
264            $a = new stdClass();
265            $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
266            $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
267
268            $eventdata = new \core\message\message();
269            $eventdata->courseid          = $course->id;
270            $eventdata->modulename        = 'moodle';
271            $eventdata->component         = 'enrol_paypal';
272            $eventdata->name              = 'paypal_enrolment';
273            $eventdata->userfrom          = empty($teacher) ? core_user::get_noreply_user() : $teacher;
274            $eventdata->userto            = $user;
275            $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
276            $eventdata->fullmessage       = get_string('welcometocoursetext', '', $a);
277            $eventdata->fullmessageformat = FORMAT_PLAIN;
278            $eventdata->fullmessagehtml   = '';
279            $eventdata->smallmessage      = '';
280            message_send($eventdata);
281
282        }
283
284        if (!empty($mailteachers) && !empty($teacher)) {
285            $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
286            $a->user = fullname($user);
287
288            $eventdata = new \core\message\message();
289            $eventdata->courseid          = $course->id;
290            $eventdata->modulename        = 'moodle';
291            $eventdata->component         = 'enrol_paypal';
292            $eventdata->name              = 'paypal_enrolment';
293            $eventdata->userfrom          = $user;
294            $eventdata->userto            = $teacher;
295            $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
296            $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
297            $eventdata->fullmessageformat = FORMAT_PLAIN;
298            $eventdata->fullmessagehtml   = '';
299            $eventdata->smallmessage      = '';
300            message_send($eventdata);
301        }
302
303        if (!empty($mailadmins)) {
304            $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
305            $a->user = fullname($user);
306            $admins = get_admins();
307            foreach ($admins as $admin) {
308                $eventdata = new \core\message\message();
309                $eventdata->courseid          = $course->id;
310                $eventdata->modulename        = 'moodle';
311                $eventdata->component         = 'enrol_paypal';
312                $eventdata->name              = 'paypal_enrolment';
313                $eventdata->userfrom          = $user;
314                $eventdata->userto            = $admin;
315                $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
316                $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
317                $eventdata->fullmessageformat = FORMAT_PLAIN;
318                $eventdata->fullmessagehtml   = '';
319                $eventdata->smallmessage      = '';
320                message_send($eventdata);
321            }
322        }
323
324    } else if (strcmp ($result, "INVALID") == 0) { // ERROR
325        $DB->insert_record("enrol_paypal", $data, false);
326        throw new moodle_exception('erripninvalid', 'enrol_paypal', '', null, json_encode($data));
327    }
328}
329