MDL-31643 dndupload - prevent file upload when total file count would exceed the...
[moodle.git] / enrol / authorize / uploadcsv.php
blob95c940bb9e06ebe688dbd3b74fffa97fbc4535d6
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 * Authorize.Net enrolment plugin - support for user self unenrolment.
20 * @package enrol
21 * @subpackage authorize
22 * @copyright 2010 Eugene Venter
23 * @author Eugene Venter
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 /// Load libraries
28 require_once('../../config.php');
29 require_once($CFG->dirroot.'/enrol/authorize/const.php');
30 require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
31 require_once($CFG->libdir.'/eventslib.php');
32 require_once('import_form.php');
34 /// Require capabilities
35 require_login();
36 require_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_SYSTEM));
38 /// Print header
39 $struploadcsv = get_string('uploadcsv', 'enrol_authorize');
40 $managebutton = "<form method='get' action='index.php'><input type='submit' value='".get_string('paymentmanagement', 'enrol_authorize')."' /></form>";
42 $form = new enrol_authorize_import_form();
44 $PAGE->set_url('/enrol/authorize/uploadcsv.php');
45 $PAGE->navbar->add(get_string('paymentmanagement', 'enrol_authorize'), 'index.php');
46 $PAGE->navbar->add($struploadcsv, 'uploadcsv.php');
47 $PAGE->set_title($struploadcsv);
48 $PAGE->set_cacheable(false);
49 $PAGE->set_button($managebutton);
50 echo $OUTPUT->header();
51 echo $OUTPUT->heading($struploadcsv);
53 /// Handle CSV file
54 if (!$form->get_data()) {
55 $form->display();
56 } else {
57 $filename = $CFG->tempdir . '/enrolauthorize/importedfile_'.time().'.csv';
58 make_temp_directory('enrolauthorize');
59 // Fix mac/dos newlines
60 $text = $form->get_file_content('csvfile');
61 $text = preg_replace('!\r\n?!', "\n", $text);
62 $fp = fopen($filename, "w");
63 fwrite($fp, $text);
64 fclose($fp);
65 authorize_process_csv($filename);
68 /// Print footer
69 echo $OUTPUT->footer();
71 function authorize_process_csv($filename) {
72 global $CFG, $SITE, $DB;
74 $plugin = enrol_get_plugin('authorize');
76 /// We need these fields
77 $myfields = array(
78 'Transaction ID', // enrol_authorize.transid or enrol_authorize_refunds.transid; See: Reference Transaction ID
79 'Transaction Status', // Under Review,Approved Review,Review Failed,Settled Successfully
80 'Transaction Type', // Authorization w/ Auto Capture, Authorization Only, Capture Only, Credit, Void, Prior Authorization Capture
81 'Settlement Amount', //
82 'Settlement Currency', //
83 'Settlement Date/Time', //
84 'Authorization Amount', //
85 'Authorization Currency', //
86 'Submit Date/Time', // timecreated
87 'Reference Transaction ID', // enrol_authorize.transid if Transaction Type = Credit
88 'Total Amount', // enrol_authorize.cost
89 'Currency', // enrol_authorize.currency
90 'Invoice Number', // enrol_authorize.id: Don't trust this! Backup/Restore changes this
91 'Customer ID' // enrol_authorize.userid
94 /// Open the file and get first line
95 $handle = fopen($filename, "r");
96 if (!$handle) {
97 print_error('cannotopencsv');
99 $firstline = fgetcsv($handle, 8192, ",");
100 $numfields = count($firstline);
101 if ($numfields != 49 && $numfields != 70) {
102 @fclose($handle);
103 print_error('csvinvalidcolsnum');
106 /// Re-sort fields
107 $csvfields = array();
108 foreach ($myfields as $myfield) {
109 $csvindex = array_search($myfield, $firstline);
110 if ($csvindex === false) {
111 $csvfields = array();
112 break;
114 $csvfields[$myfield] = $csvindex;
116 if (empty($csvfields)) {
117 @fclose($handle);
118 print_error('csvinvalidcols');
121 /// Read lines
122 $sendem = array();
123 $ignoredlines = '';
125 $imported = 0;
126 $updated = 0;
127 $ignored = 0;
128 while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
129 if (count($data) != $numfields) {
130 $ignored++; // ignore empty lines
131 continue;
134 $transid = $data[$csvfields['Transaction ID']];
135 $transtype = $data[$csvfields['Transaction Type']];
136 $transstatus = $data[$csvfields['Transaction Status']];
137 $reftransid = $data[$csvfields['Reference Transaction ID']];
138 $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
140 if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
141 if (($order = $DB->get_record('enrol_authorize', array('transid'=>$transid)))) {
142 $order->status = ($transstatus == 'Approved Review') ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
143 $DB->update_record('enrol_authorize', $order);
144 $updated++; // Updated order status
146 continue;
149 if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
150 if (($order = $DB->get_record('enrol_authorize', array('transid'=>$reftransid)))) {
151 if (AN_METHOD_ECHECK == $order->paymentmethod) {
152 $refund = $DB->get_record('enrol_authorize_refunds', array('transid'=>$transid));
153 if ($refund) {
154 $refund->status = AN_STATUS_CREDIT;
155 $refund->settletime = $settlementdate;
156 $DB->update_record('enrol_authorize_refunds', $refund);
157 $updated++;
159 else {
160 $ignored++;
161 $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
165 else {
166 $ignored++;
167 $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
169 continue;
172 if (! ($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
173 $ignored++;
174 $ignoredlines .= $transid . ": Not settled\n";
175 continue;
178 // TransactionId must match
179 $order = $DB->get_record('enrol_authorize', array('transid'=>$transid));
180 if (!$order) {
181 $ignored++;
182 $ignoredlines .= $transid . ": Not our business\n";
183 continue;
186 // Authorized/Captured and Settled
187 $order->status = AN_STATUS_AUTHCAPTURE;
188 $order->settletime = $settlementdate;
189 $DB->update_record('enrol_authorize', $order);
190 $updated++; // Updated order status and settlement date
192 if ($order->paymentmethod != AN_METHOD_ECHECK) {
193 $ignored++;
194 $ignoredlines .= $transid . ": The method must be echeck\n";
195 continue;
198 // Get course and context
199 $course = $DB->get_record('course', array('id'=>$order->courseid));
200 if (!$course) {
201 $ignored++;
202 $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
203 continue;
205 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
206 if (!$coursecontext) {
207 $ignored++;
208 $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
209 continue;
212 // Get user
213 $user = $DB->get_record('user', array('id'=>$order->userid));
214 if (!$user) {
215 $ignored++;
216 $ignoredlines .= $transid . ": Could not find this user: " . $order->userid . "\n";
217 continue;
220 // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
221 if (($role = get_default_course_role($course))) {
222 if (! user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
223 $timestart = $timeend = 0;
224 if ($course->enrolperiod) {
225 $timestart = time();
226 $timeend = $timestart + $course->enrolperiod;
228 // Enrol user
229 $pinstance = $DB->get_record('enrol', array('id'=>$order->instanceid));
230 $plugin->enrol_user($pinstance, $user->id, $pinstance->roleid, $timestart, $timeend);
232 $imported++;
233 if ($plugin->get_config('enrol_mailstudents')) {
234 $sendem[] = $order->id;
239 fclose($handle);
241 /// Send email to admin
242 if (!empty($ignoredlines)) {
243 $admin = get_admin();
245 $eventdata = new stdClass();
246 $eventdata->modulename = 'moodle';
247 $eventdata->component = 'enrol_authorize';
248 $eventdata->name = 'authorize_enrolment';
249 $eventdata->userfrom = $admin;
250 $eventdata->userto = $admin;
251 $eventdata->subject = format_string($SITE->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))).': Authorize.net CSV ERROR LOG';
252 $eventdata->fullmessage = $ignoredlines;
253 $eventdata->fullmessageformat = FORMAT_PLAIN;
254 $eventdata->fullmessagehtml = '';
255 $eventdata->smallmessage = '';
256 message_send($eventdata);
259 /// Send welcome messages to users
260 if (!empty($sendem)) {
261 send_welcome_messages($sendem);
264 /// Show result
265 notice("<b>Done...</b><br />Imported: $imported<br />Updated: $updated<br />Ignored: $ignored");