MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / enrol / authorize / uploadcsv.php
blob98dff546e95fea0d04b4ae7b7528fe51253f33ca
1 <?php // $Id$
3 /// Load libraries
4 require_once('../../config.php');
5 require_once($CFG->libdir.'/uploadlib.php');
6 require_once($CFG->dirroot.'/enrol/authorize/const.php');
7 require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
9 /// Require capabilites
10 require_login();
11 require_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id));
13 /// Print header
14 $struploadcsv = get_string('uploadcsv', 'enrol_authorize');
15 $navlinks = array();
16 $navlinks[] = array('name' => $struploadcsv, 'link' => "uploadcsv.php", 'type' => 'misc');
17 $navigation = build_navigation($navlinks);
19 print_header_simple($struploadcsv, "", $navigation);
20 print_heading_with_help($struploadcsv, 'uploadcsv', 'enrol/authorize');
22 /// Handle CSV file
23 if ($form = data_submitted() && confirm_sesskey()) {
24 $um = new upload_manager('csvfile', false, false, null, false, 0);
25 if ($um->preprocess_files()) {
26 $filename = $um->files['csvfile']['tmp_name'];
27 // Fix mac/dos newlines
28 $text = file_get_contents($filename);
29 $text = preg_replace('!\r\n?!', "\n", $text);
30 $fp = fopen($filename, "w");
31 fwrite($fp, $text);
32 fclose($fp);
33 authorize_process_csv($filename);
37 /// Print submit form
38 $maxuploadsize = get_max_upload_file_size();
39 echo '<center><form method="post" enctype="multipart/form-data" action="uploadcsv.php">
40 <input type="hidden" name="MAX_FILE_SIZE" value="'.$maxuploadsize.'" />
41 <input type="hidden" name="sesskey" value="'.$USER->sesskey.'">';
42 upload_print_form_fragment(1, array('csvfile'), array(get_string('file')));
43 echo '<input type="submit" value="'.get_string('upload').'" />';
44 echo '</form></center><br />';
46 /// Print footer
47 print_footer();
49 ?><?php
51 function authorize_process_csv($filename)
53 global $CFG, $SITE;
55 /// We need these fields
56 $myfields = array(
57 'Transaction ID', // enrol_authorize.transid or enrol_authorize_refunds.transid; See: Reference Transaction ID
58 'Transaction Status', // Under Review,Approved Review,Review Failed,Settled Successfully
59 'Transaction Type', // Authorization w/ Auto Capture, Authorization Only, Capture Only, Credit, Void, Prior Authorization Capture
60 'Settlement Amount', //
61 'Settlement Currency', //
62 'Settlement Date/Time', //
63 'Authorization Amount', //
64 'Authorization Currency', //
65 'Submit Date/Time', // timecreated
66 'Reference Transaction ID', // enrol_authorize.transid if Transaction Type = Credit
67 'Total Amount', // enrol_authorize.cost
68 'Currency', // enrol_authorize.currency
69 'Invoice Number', // enrol_authorize.id: Don't trust this! Backup/Restore changes this
70 'Customer ID' // enrol_authorize.userid
73 /// Open the file and get first line
74 $handle = fopen($filename, "r");
75 if (!$handle) {
76 error('CANNOT OPEN CSV FILE');
78 $firstline = fgetcsv($handle, 8192, ",");
79 $numfields = count($firstline);
80 if ($numfields != 49 && $numfields != 70) {
81 @fclose($handle);
82 error('INVALID CSV FILE; Each line must include 49 or 70 fields');
85 /// Re-sort fields
86 $csvfields = array();
87 foreach ($myfields as $myfield) {
88 $csvindex = array_search($myfield, $firstline);
89 if ($csvindex === false) {
90 $csvfields = array();
91 break;
93 $csvfields[$myfield] = $csvindex;
95 if (empty($csvfields)) {
96 @fclose($handle);
97 error("<b>INVALID CSV FILE:</b> First line must include 'Header Fields' and
98 the file must be type of <br />'Expanded Fields/Comma Separated'<br />or<br />
99 'Expanded Fields with CAVV Result Code/Comma Separated'");
102 /// Read lines
103 $sendem = array();
104 $ignoredlines = '';
106 $imported = 0;
107 $updated = 0;
108 $ignored = 0;
109 while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
110 if (count($data) != $numfields) {
111 $ignored++; // ignore empty lines
112 continue;
115 $transid = $data[$csvfields['Transaction ID']];
116 $transtype = $data[$csvfields['Transaction Type']];
117 $transstatus = $data[$csvfields['Transaction Status']];
118 $reftransid = $data[$csvfields['Reference Transaction ID']];
119 $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
121 if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
122 if ($order = get_record('enrol_authorize', 'transid', $transid)) {
123 $order->status = ($transstatus == 'Approved Review') ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
124 update_record('enrol_authorize', $order);
125 $updated++; // Updated order status
127 continue;
130 if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
131 if ($order = get_record('enrol_authorize', 'transid', $reftransid)) {
132 if (AN_METHOD_ECHECK == $order->paymentmethod) {
133 $refund = get_record('enrol_authorize_refunds', 'transid', $transid);
134 if ($refund) {
135 $refund->status = AN_STATUS_CREDIT;
136 $refund->settletime = $settlementdate;
137 update_record('enrol_authorize_refunds', $refund);
138 $updated++;
140 else {
141 $ignored++;
142 $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
146 else {
147 $ignored++;
148 $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
150 continue;
153 if (! ($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
154 $ignored++;
155 $ignoredlines .= $transid . ": Not settled\n";
156 continue;
159 // TransactionId must match
160 $order = get_record('enrol_authorize', 'transid', $transid);
161 if (!$order) {
162 $ignored++;
163 $ignoredlines .= $transid . ": Not our business\n";
164 continue;
167 // Authorized/Captured and Settled
168 $order->status = AN_STATUS_AUTHCAPTURE;
169 $order->settletime = $settlementdate;
170 update_record('enrol_authorize', $order);
171 $updated++; // Updated order status and settlement date
173 if ($order->paymentmethod != AN_METHOD_ECHECK) {
174 $ignored++;
175 $ignoredlines .= $transid . ": The method must be echeck\n";
176 continue;
179 // Get course and context
180 $course = get_record('course', 'id', $order->courseid);
181 if (!$course) {
182 $ignored++;
183 $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
184 continue;
186 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
187 if (!$coursecontext) {
188 $ignored++;
189 $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
190 continue;
193 // Get user
194 $user = get_record('user', 'id', $order->userid);
195 if (!$user) {
196 $ignored++;
197 $ignoredlines .= $transid . ": Could not find this user: " . $order->userid . "\n";
198 continue;
201 // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
202 if ($role = get_default_course_role($course)) {
203 if (! user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
204 $timestart = $timeend = 0;
205 if ($course->enrolperiod) {
206 $timestart = time();
207 $timeend = $timestart + $course->enrolperiod;
209 if (role_assign($role->id, $user->id, 0, $coursecontext->id, $timestart, $timeend, 0, 'manual')) {
210 $imported++;
211 if (!empty($CFG->enrol_mailstudents)) {
212 $sendem[] = $order->id;
215 else {
216 $ignoredlines .= $transid . ": Error while trying to enrol " . fullname($user) . " in '$course->fullname' \n";
221 fclose($handle);
223 /// Send email to admin
224 if (!empty($ignoredlines)) {
225 $admin = get_admin();
226 email_to_user($admin, $admin, "$SITE->fullname: Authorize.net CSV ERROR LOG", $ignoredlines);
229 /// Send welcome messages to users
230 if (!empty($sendem)) {
231 send_welcome_messages($sendem);
234 /// Show result
235 notice("<b>Done...</b><br />Imported: $imported<br />Updated: $updated<br />Ignored: $ignored");