~ubuntu-branches/ubuntu/utopic/moodle/utopic

« back to all changes in this revision

Viewing changes to enrol/authorize/uploadcsv.php

  • Committer: Package Import Robot
  • Author(s): Thijs Kinkhorst
  • Date: 2014-05-12 16:10:38 UTC
  • mfrom: (36.1.3 sid)
  • Revision ID: package-import@ubuntu.com-20140512161038-puyqf65k4e0s8ytz
Tags: 2.6.3-1
New upstream release.

Show diffs side-by-side

added added

removed removed

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