Example #1
0
 /**
  * This function is run by admin/cron.php every time if admin has enabled this plugin.
  *
  * Everyday at settlement time (default is 00:05), it cleans up some tables
  * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
  *
  * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
  *
  * @access public
  */
 function cron()
 {
     global $CFG;
     require_once $CFG->dirroot . '/enrol/authorize/authorizenetlib.php';
     $oneday = 86400;
     $timenow = time();
     $settlementtime = authorize_getsettletime($timenow);
     $timediff30 = $settlementtime - 30 * $oneday;
     $mconfig = get_config('enrol/authorize');
     mtrace("Processing authorize cron...");
     if (intval($mconfig->an_dailysettlement) < $settlementtime) {
         set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
         mtrace("    daily cron; some cleanups and sending email to admins the count of pending orders expiring", ": ");
         $this->cron_daily();
         mtrace("done");
     }
     mtrace("    scheduled capture", ": ");
     if (empty($CFG->an_review) or !empty($CFG->an_test) or intval($CFG->an_capture_day) < 1 or !check_openssl_loaded()) {
         mtrace("disabled");
         return;
         // order review disabled or test mode or manual capture or openssl wasn't loaded.
     }
     $timediffcnf = $settlementtime - intval($CFG->an_capture_day) * $oneday;
     $select = "(status = '" . AN_STATUS_AUTH . "') AND (timecreated < '{$timediffcnf}') AND (timecreated > '{$timediff30}')";
     if (!($ordercount = count_records_select('enrol_authorize', $select))) {
         mtrace("no pending orders");
         return;
     }
     $eachconn = intval($mconfig->an_eachconnsecs);
     $eachconn = $eachconn > 60 ? 60 : ($eachconn <= 0 ? 3 : $eachconn);
     if ($ordercount * $eachconn + intval($mconfig->an_lastcron) > $timenow) {
         mtrace("blocked");
         return;
     }
     set_config('an_lastcron', $timenow, 'enrol/authorize');
     mtrace("    {$ordercount} orders are being processed now", ": ");
     $faults = '';
     $sendem = array();
     $elapsed = time();
     @set_time_limit(0);
     $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
     $lastcourseid = 0;
     for ($rs = get_recordset_select('enrol_authorize', $select, 'courseid'); $order = rs_fetch_next_record($rs);) {
         $message = '';
         $extra = NULL;
         if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
             if ($lastcourseid != $order->courseid) {
                 $lastcourseid = $order->courseid;
                 $course = get_record('course', 'id', $lastcourseid);
                 $role = get_default_course_role($course);
                 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
             }
             $timestart = $timeend = 0;
             if ($course->enrolperiod) {
                 $timestart = $timenow;
                 $timeend = $order->settletime + $course->enrolperiod;
             }
             $user = get_record('user', 'id', $order->userid);
             if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
                 $this->log .= "User({$user->id}) has been enrolled to course({$course->id}).\n";
                 if (!empty($CFG->enrol_mailstudents)) {
                     $sendem[] = $order->id;
                 }
             } else {
                 $faults .= "Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                 foreach ($order as $okey => $ovalue) {
                     $faults .= "   {$okey} = {$ovalue}\n";
                 }
             }
         } else {
             $this->log .= "Error, Order# {$order->id}: " . $message . "\n";
         }
     }
     rs_close($rs);
     mtrace("processed");
     $timenow = time();
     $elapsed = $timenow - $elapsed;
     $eachconn = ceil($elapsed / $ordercount);
     set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
     $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
     $adminuser = get_admin();
     if (!empty($faults)) {
         email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON FAULTS", $faults);
     }
     if (!empty($CFG->enrol_mailadmins)) {
         email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON LOG", $this->log);
     }
     // Send emails to students about which courses have enrolled.
     if (!empty($sendem)) {
         mtrace("    sending welcome messages to students", ": ");
         send_welcome_messages($sendem);
         mtrace("sent");
     }
 }
function authorize_process_csv($filename)
{
    global $CFG, $SITE, $DB;
    $plugin = enrol_get_plugin('authorize');
    /// We need these fields
    $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID');
    /// Open the file and get first line
    $handle = fopen($filename, "r");
    if (!$handle) {
        print_error('cannotopencsv');
    }
    $firstline = fgetcsv($handle, 8192, ",");
    $numfields = count($firstline);
    if ($numfields != 49 && $numfields != 70) {
        @fclose($handle);
        print_error('csvinvalidcolsnum');
    }
    /// Re-sort fields
    $csvfields = array();
    foreach ($myfields as $myfield) {
        $csvindex = array_search($myfield, $firstline);
        if ($csvindex === false) {
            $csvfields = array();
            break;
        }
        $csvfields[$myfield] = $csvindex;
    }
    if (empty($csvfields)) {
        @fclose($handle);
        print_error('csvinvalidcols');
    }
    /// Read lines
    $sendem = array();
    $ignoredlines = '';
    $imported = 0;
    $updated = 0;
    $ignored = 0;
    while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
        if (count($data) != $numfields) {
            $ignored++;
            // ignore empty lines
            continue;
        }
        $transid = $data[$csvfields['Transaction ID']];
        $transtype = $data[$csvfields['Transaction Type']];
        $transstatus = $data[$csvfields['Transaction Status']];
        $reftransid = $data[$csvfields['Reference Transaction ID']];
        $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
        if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
            if ($order = $DB->get_record('enrol_authorize', array('transid' => $transid))) {
                $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
                $DB->update_record('enrol_authorize', $order);
                $updated++;
                // Updated order status
            }
            continue;
        }
        if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
            if ($order = $DB->get_record('enrol_authorize', array('transid' => $reftransid))) {
                if (AN_METHOD_ECHECK == $order->paymentmethod) {
                    $refund = $DB->get_record('enrol_authorize_refunds', array('transid' => $transid));
                    if ($refund) {
                        $refund->status = AN_STATUS_CREDIT;
                        $refund->settletime = $settlementdate;
                        $DB->update_record('enrol_authorize_refunds', $refund);
                        $updated++;
                    } else {
                        $ignored++;
                        $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
                    }
                }
            } else {
                $ignored++;
                $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
            }
            continue;
        }
        if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
            $ignored++;
            $ignoredlines .= $transid . ": Not settled\n";
            continue;
        }
        // TransactionId must match
        $order = $DB->get_record('enrol_authorize', array('transid' => $transid));
        if (!$order) {
            $ignored++;
            $ignoredlines .= $transid . ": Not our business\n";
            continue;
        }
        // Authorized/Captured and Settled
        $order->status = AN_STATUS_AUTHCAPTURE;
        $order->settletime = $settlementdate;
        $DB->update_record('enrol_authorize', $order);
        $updated++;
        // Updated order status and settlement date
        if ($order->paymentmethod != AN_METHOD_ECHECK) {
            $ignored++;
            $ignoredlines .= $transid . ": The method must be echeck\n";
            continue;
        }
        // Get course and context
        $course = $DB->get_record('course', array('id' => $order->courseid));
        if (!$course) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
            continue;
        }
        $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
        if (!$coursecontext) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
            continue;
        }
        // Get user
        $user = $DB->get_record('user', array('id' => $order->userid));
        if (!$user) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this user: "******"\n";
            continue;
        }
        // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
        if ($role = get_default_course_role($course)) {
            if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
                $timestart = $timeend = 0;
                if ($course->enrolperiod) {
                    $timestart = time();
                    $timeend = $timestart + $course->enrolperiod;
                }
                // Enrol user
                $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid));
                $plugin->enrol_user($pinstance, $user->id, $pinstance->roleid, $timestart, $timeend);
                $imported++;
                if ($plugin->get_config('enrol_mailstudents')) {
                    $sendem[] = $order->id;
                }
            }
        }
    }
    fclose($handle);
    /// Send email to admin
    if (!empty($ignoredlines)) {
        $admin = get_admin();
        $eventdata = new stdClass();
        $eventdata->modulename = 'moodle';
        $eventdata->component = 'enrol_authorize';
        $eventdata->name = 'authorize_enrolment';
        $eventdata->userfrom = $admin;
        $eventdata->userto = $admin;
        $eventdata->subject = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))) . ': Authorize.net CSV ERROR LOG';
        $eventdata->fullmessage = $ignoredlines;
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml = '';
        $eventdata->smallmessage = '';
        message_send($eventdata);
    }
    /// Send welcome messages to users
    if (!empty($sendem)) {
        send_welcome_messages($sendem);
    }
    /// Show result
    notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}");
}
Example #3
0
/**
 * authorize_print_order_details
 *
 * @param int $orderno
 */
function authorize_print_order_details($orderno)
{
    global $CFG, $USER;
    global $strs, $authstrs;
    $cmdcapture = optional_param(ORDER_CAPTURE, '', PARAM_ALPHA);
    $cmddelete = optional_param(ORDER_DELETE, '', PARAM_ALPHA);
    $cmdrefund = optional_param(ORDER_REFUND, '', PARAM_ALPHA);
    $cmdvoid = optional_param(ORDER_VOID, '', PARAM_ALPHA);
    $unenrol = optional_param('unenrol', 0, PARAM_BOOL);
    $confirm = optional_param('confirm', 0, PARAM_BOOL);
    $table = new stdClass();
    $table->width = '100%';
    $table->size = array('30%', '70%');
    $table->align = array('right', 'left');
    $order = get_record('enrol_authorize', 'id', $orderno);
    if (!$order) {
        notice("Order {$orderno} not found.", "index.php");
        return;
    }
    $course = get_record('course', 'id', $order->courseid);
    $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
    if ($USER->id != $order->userid) {
        // Current user viewing someone else's order
        require_capability('enrol/authorize:managepayments', $coursecontext);
    }
    echo "<form action=\"index.php\" method=\"post\">\n";
    echo "<div>";
    echo "<input type=\"hidden\" name=\"order\" value=\"{$orderno}\" />\n";
    echo "<input type=\"hidden\" name=\"sesskey\" value=\"" . sesskey() . "\" />";
    $settled = authorize_settled($order);
    $status = authorize_get_status_action($order);
    $table->data[] = array("<b>{$authstrs->paymentmethod}:</b>", $order->paymentmethod == AN_METHOD_CC ? $authstrs->methodcc : $authstrs->methodecheck);
    $table->data[] = array("<b>{$authstrs->orderid}:</b>", $orderno);
    $table->data[] = array("<b>{$authstrs->transid}:</b>", $order->transid);
    $table->data[] = array("<b>{$authstrs->amount}:</b>", "{$order->currency} {$order->amount}");
    if (empty($cmdcapture) and empty($cmdrefund) and empty($cmdvoid) and empty($cmddelete)) {
        $color = authorize_get_status_color($status->status);
        $table->data[] = array("<b>{$strs->course}:</b>", format_string($course->shortname));
        $table->data[] = array("<b>{$strs->status}:</b>", "<font style='color:{$color}'>" . $authstrs->{$status->status} . "</font>");
        if ($order->paymentmethod == AN_METHOD_CC) {
            $table->data[] = array("<b>{$authstrs->nameoncard}:</b>", $order->ccname);
        } else {
            $table->data[] = array("<b>{$authstrs->echeckfirslasttname}:</b>", $order->ccname);
        }
        $table->data[] = array("<b>{$strs->time}:</b>", userdate($order->timecreated));
        $table->data[] = array("<b>{$authstrs->settlementdate}:</b>", $settled ? userdate($order->settletime) : $authstrs->notsettled);
    }
    $table->data[] = array("&nbsp;", "<hr size='1' />\n");
    if (!empty($cmdcapture) and confirm_sesskey()) {
        // CAPTURE
        if (!in_array(ORDER_CAPTURE, $status->actions)) {
            $a = new stdClass();
            $a->action = $authstrs->capture;
            print_error('youcantdo', 'enrol_authorize', '', $a);
        }
        if (empty($confirm)) {
            $strcaptureyes = get_string('captureyes', 'enrol_authorize');
            $table->data[] = array("<b>{$strs->confirm}:</b>", "{$strcaptureyes} <br />\n            <input type='hidden' name='confirm' value='1' /><input type='submit' name='" . ORDER_CAPTURE . "' value='{$authstrs->capture}' />\n            &nbsp;&nbsp;&nbsp;<a href='index.php?order={$orderno}'>{$strs->no}</a>");
        } else {
            $message = '';
            $extra = NULL;
            if (AN_APPROVED != authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
                $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", $message);
            } else {
                if (empty($CFG->an_test)) {
                    $user = get_record('user', 'id', $order->userid);
                    if (enrol_into_course($course, $user, 'authorize')) {
                        if (!empty($CFG->enrol_mailstudents)) {
                            send_welcome_messages($order->id);
                        }
                        redirect("index.php?order={$orderno}");
                    } else {
                        $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", "Error while trying to enrol " . fullname($user) . " in '" . format_string($course->shortname) . "'");
                    }
                } else {
                    $table->data[] = array(get_string('testmode', 'enrol_authorize'), get_string('testwarning', 'enrol_authorize'));
                }
            }
        }
        print_table($table);
    } elseif (!empty($cmdrefund) and confirm_sesskey()) {
        // REFUND
        if (!in_array(ORDER_REFUND, $status->actions)) {
            $a = new stdClass();
            $a->action = $authstrs->refund;
            print_error('youcantdo', 'enrol_authorize', '', $a);
        }
        $refunded = 0.0;
        $sql = "SELECT SUM(amount) AS refunded FROM {$CFG->prefix}enrol_authorize_refunds " . "WHERE (orderid = '" . $orderno . "') AND (status = '" . AN_STATUS_CREDIT . "')";
        if ($refundval = get_field_sql($sql)) {
            $refunded = floatval($refundval);
        }
        $upto = round($order->amount - $refunded, 2);
        if ($upto <= 0) {
            error("Refunded to original amount.");
        } else {
            $amount = round(optional_param('amount', $upto), 2);
            if ($amount > $upto or empty($confirm)) {
                $a = new stdClass();
                $a->upto = $upto;
                $strcanbecredit = get_string('canbecredit', 'enrol_authorize', $a);
                $strhowmuch = get_string('howmuch', 'enrol_authorize');
                $cbunenrol = print_checkbox('unenrol', '1', !empty($unenrol), '', '', '', true);
                $table->data[] = array("<b>{$authstrs->unenrolstudent}</b>", $cbunenrol);
                $table->data[] = array("<b>{$strhowmuch}</b>", "<input type='hidden' name='confirm' value='1' />\n                     <input type='text' size='5' name='amount' value='{$amount}' />\n                     {$strcanbecredit}<br /><input type='submit' name='" . ORDER_REFUND . "' value='{$authstrs->refund}' />");
            } else {
                $extra = new stdClass();
                $extra->orderid = $orderno;
                $extra->amount = $amount;
                $message = '';
                $success = authorize_action($order, $message, $extra, AN_ACTION_CREDIT);
                if (AN_APPROVED == $success || AN_REVIEW == $success) {
                    if (empty($CFG->an_test)) {
                        if (empty($extra->id)) {
                            $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", 'insert record error');
                        } else {
                            if (!empty($unenrol)) {
                                role_unassign(0, $order->userid, 0, $coursecontext->id);
                            }
                            redirect("index.php?order={$orderno}");
                        }
                    } else {
                        $table->data[] = array(get_string('testmode', 'enrol_authorize'), get_string('testwarning', 'enrol_authorize'));
                    }
                } else {
                    $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", $message);
                }
            }
        }
        print_table($table);
    } elseif (!empty($cmdvoid) and confirm_sesskey()) {
        // VOID
        $suborderno = optional_param('suborder', 0, PARAM_INT);
        if (empty($suborderno)) {
            // cancel original transaction.
            if (!in_array(ORDER_VOID, $status->actions)) {
                $a = new stdClass();
                $a->action = $authstrs->void;
                print_error('youcantdo', 'enrol_authorize', '', $a);
            }
            if (empty($confirm)) {
                $strvoidyes = get_string('voidyes', 'enrol_authorize');
                $table->data[] = array("<b>{$strs->confirm}:</b>", "{$strvoidyes}<br /><input type='hidden' name='" . ORDER_VOID . "' value='y' />\n                     <input type='hidden' name='confirm' value='1' />\n                     <input type='submit' value='{$authstrs->void}' />\n                     &nbsp;&nbsp;&nbsp;&nbsp;<a href='index.php?order={$orderno}'>{$strs->no}</a>");
            } else {
                $extra = NULL;
                $message = '';
                if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_VOID)) {
                    if (empty($CFG->an_test)) {
                        redirect("index.php?order={$orderno}");
                    } else {
                        $table->data[] = array(get_string('testmode', 'enrol_authorize'), get_string('testwarning', 'enrol_authorize'));
                    }
                } else {
                    $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", $message);
                }
            }
        } else {
            // cancel refunded transaction
            $sql = "SELECT r.*, e.courseid, e.paymentmethod FROM {$CFG->prefix}enrol_authorize_refunds r " . "INNER JOIN {$CFG->prefix}enrol_authorize e ON r.orderid = e.id " . "WHERE r.id = '{$suborderno}' AND r.orderid = '{$orderno}' AND r.status = '" . AN_STATUS_CREDIT . "'";
            $suborder = get_record_sql($sql);
            if (!$suborder) {
                // not found
                error("Transaction can not be voided because of already been voided.");
            } else {
                $refundedstatus = authorize_get_status_action($suborder);
                if (!in_array(ORDER_VOID, $refundedstatus->actions)) {
                    $a = new stdClass();
                    $a->action = $authstrs->void;
                    print_error('youcantdo', 'enrol_authorize', '', $a);
                }
                unset($suborder->courseid);
                if (empty($confirm)) {
                    $a = new stdClass();
                    $a->transid = $suborder->transid;
                    $a->amount = $suborder->amount;
                    $strsubvoidyes = get_string('subvoidyes', 'enrol_authorize', $a);
                    $cbunenrol = print_checkbox('unenrol', '1', !empty($unenrol), '', '', '', true);
                    $table->data[] = array("<b>{$authstrs->unenrolstudent}</b>", $cbunenrol);
                    $table->data[] = array("<b>{$strs->confirm}:</b>", "{$strsubvoidyes}<br /><input type='hidden' name='" . ORDER_VOID . "' value='y' />\n                         <input type='hidden' name='confirm' value='1' />\n                         <input type='hidden' name='suborder' value='{$suborderno}' />\n                         <input type='submit' value='{$authstrs->void}' />\n                         &nbsp;&nbsp;&nbsp;&nbsp;<a href='index.php?order={$orderno}'>{$strs->no}</a>");
                } else {
                    $message = '';
                    $extra = NULL;
                    if (AN_APPROVED == authorize_action($suborder, $message, $extra, AN_ACTION_VOID)) {
                        if (empty($CFG->an_test)) {
                            if (!empty($unenrol)) {
                                role_unassign(0, $order->userid, 0, $coursecontext->id);
                            }
                            redirect("index.php?order={$orderno}");
                        } else {
                            $table->data[] = array(get_string('testmode', 'enrol_authorize'), get_string('testwarning', 'enrol_authorize'));
                        }
                    } else {
                        $table->data[] = array("<b><font color='red'>{$strs->error}:</font></b>", $message);
                    }
                }
            }
        }
        print_table($table);
    } elseif (!empty($cmddelete) and confirm_sesskey()) {
        // DELETE
        if (!in_array(ORDER_DELETE, $status->actions)) {
            $a = new stdClass();
            $a->action = $authstrs->delete;
            print_error('youcantdo', 'enrol_authorize', '', $a);
        }
        if (empty($confirm)) {
            $cbunenrol = print_checkbox('unenrol', '1', !empty($unenrol), '', '', '', true);
            $table->data[] = array("<b>{$authstrs->unenrolstudent}</b>", $cbunenrol);
            $table->data[] = array("<b>{$strs->confirm}:</b>", "<input type='hidden' name='" . ORDER_DELETE . "' value='y' />\n                 <input type='hidden' name='confirm' value='1' />\n                 <input type='submit' value='{$authstrs->delete}' />\n                 &nbsp;&nbsp;&nbsp;&nbsp;<a href='index.php?order={$orderno}'>{$strs->no}</a>");
        } else {
            if (!empty($unenrol)) {
                role_unassign(0, $order->userid, 0, $coursecontext->id);
            }
            delete_records('enrol_authorize', 'id', $orderno);
            redirect("index.php");
        }
        print_table($table);
    } else {
        // SHOW
        $actions = '';
        if (empty($status->actions)) {
            if ($order->paymentmethod == AN_METHOD_ECHECK && has_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id))) {
                $actions .= '<a href="uploadcsv.php">' . get_string('uploadcsv', 'enrol_authorize') . '</a>';
            } else {
                $actions .= $strs->none;
            }
        } else {
            foreach ($status->actions as $value) {
                $actions .= "<input type='submit' name='{$value}' value='{$authstrs->{$value}}' /> ";
            }
        }
        $table->data[] = array("<b>{$strs->action}</b>", $actions);
        print_table($table);
        if ($settled) {
            // show refunds.
            $t2 = new stdClass();
            $t2->size = array('45%', '15%', '20%', '10%', '10%');
            $t2->align = array('right', 'right', 'right', 'right', 'right');
            $t2->head = array($authstrs->settlementdate, $authstrs->transid, $strs->status, $strs->action, $authstrs->amount);
            $sql = "SELECT r.*, e.courseid, e.paymentmethod FROM {$CFG->prefix}enrol_authorize_refunds r " . "INNER JOIN {$CFG->prefix}enrol_authorize e ON r.orderid = e.id " . "WHERE r.orderid = '{$orderno}'";
            $refunds = get_records_sql($sql);
            if ($refunds) {
                $sumrefund = floatval(0.0);
                foreach ($refunds as $rf) {
                    $substatus = authorize_get_status_action($rf);
                    $subactions = '&nbsp;';
                    if (empty($substatus->actions)) {
                        $subactions .= $strs->none;
                    } else {
                        foreach ($substatus->actions as $vl) {
                            $subactions .= "<a href='index.php?{$vl}=y&amp;sesskey={$USER->sesskey}&amp;order={$orderno}&amp;suborder={$rf->id}'>{$authstrs->{$vl}}</a> ";
                        }
                    }
                    $sign = '';
                    $color = authorize_get_status_color($substatus->status);
                    if ($substatus->status == 'refunded' or $substatus->status == 'settled') {
                        $sign = '-';
                        $sumrefund += floatval($rf->amount);
                    }
                    $t2->data[] = array(userdate($rf->settletime), $rf->transid, "<font style='color:{$color}'>" . $authstrs->{$substatus->status} . "</font>", $subactions, format_float($sign . $rf->amount, 2));
                }
                $t2->data[] = array('', '', get_string('total'), $order->currency, format_float('-' . $sumrefund, 2));
            } else {
                $t2->data[] = array('', '', get_string('noreturns', 'enrol_authorize'), '', '');
            }
            echo "<h4>" . get_string('returns', 'enrol_authorize') . "</h4>\n";
            print_table($t2);
        }
    }
    echo '</div>';
    echo '</form>';
}
Example #4
0
 /**
  * This function is run by admin/cron.php every time if admin has enabled this plugin.
  *
  * Everyday at settlement time (default is 00:05), it cleans up some tables
  * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
  *
  * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
  *
  * @access public
  */
 public function cron()
 {
     global $CFG, $DB;
     $oneday = 86400;
     $timenow = time();
     $settlementtime = AuthorizeNet::getsettletime($timenow);
     $timediff30 = $settlementtime - 30 * $oneday;
     $mconfig = get_config('enrol/authorize');
     mtrace("Processing authorize cron...");
     if (intval($mconfig->an_dailysettlement) < $settlementtime) {
         set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
         mtrace("    Daily cron:");
         $this->cron_daily();
         mtrace("    Done");
     }
     mtrace("    Scheduled capture", ": ");
     if (empty($CFG->an_review) or !empty($CFG->an_test) or intval($CFG->an_capture_day) < 1 or !check_curl_available()) {
         mtrace("disabled");
         return;
         // order review disabled or test mode or manual capture or openssl wasn't loaded.
     }
     $timediffcnf = $settlementtime - intval($CFG->an_capture_day) * $oneday;
     $select = "(status = ?) AND (timecreated < ?) AND (timecreated > ?)";
     $params = array(AN_STATUS_AUTH, $timediffcnf, $timediff30);
     if (!($ordercount = $DB->count_records_select('enrol_authorize', $select, $params))) {
         mtrace("no pending orders");
         return;
     }
     $eachconn = intval($mconfig->an_eachconnsecs);
     $eachconn = $eachconn > 60 ? 60 : ($eachconn <= 0 ? 3 : $eachconn);
     if ($ordercount * $eachconn + intval($mconfig->an_lastcron) > $timenow) {
         mtrace("blocked");
         return;
     }
     set_config('an_lastcron', $timenow, 'enrol/authorize');
     mtrace("    {$ordercount} orders are being processed now", ": ");
     $faults = '';
     $sendem = array();
     $elapsed = time();
     @set_time_limit(0);
     $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
     $lastcourseid = 0;
     $rs = $DB->get_recordset_select('enrol_authorize', $select, $params, 'courseid');
     foreach ($rs as $order) {
         $message = '';
         $extra = NULL;
         if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
             if ($lastcourseid != $order->courseid) {
                 $lastcourseid = $order->courseid;
                 $course = $DB->get_record('course', array('id' => $lastcourseid));
                 $role = get_default_course_role($course);
                 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
             }
             $timestart = $timeend = 0;
             if ($course->enrolperiod) {
                 $timestart = $timenow;
                 $timeend = $order->settletime + $course->enrolperiod;
             }
             $user = $DB->get_record('user', array('id' => $order->userid));
             if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
                 $this->log .= "User({$user->id}) has been enrolled to course({$course->id}).\n";
                 if (!empty($CFG->enrol_mailstudents)) {
                     $sendem[] = $order->id;
                 }
             } else {
                 $faults .= "Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                 foreach ($order as $okey => $ovalue) {
                     $faults .= "   {$okey} = {$ovalue}\n";
                 }
             }
         } else {
             $this->log .= "Error, Order# {$order->id}: " . $message . "\n";
         }
     }
     $rs->close();
     mtrace("processed");
     $timenow = time();
     $elapsed = $timenow - $elapsed;
     $eachconn = ceil($elapsed / $ordercount);
     set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
     $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
     $adminuser = get_admin();
     if (!empty($faults)) {
         $eventdata = new object();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $adminuser;
         $eventdata->userto = $adminuser;
         $eventdata->subject = "AUTHORIZE.NET CRON FAULTS";
         $eventdata->fullmessage = $faults;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         events_trigger('message_send', $eventdata);
     }
     if (!empty($CFG->enrol_mailadmins)) {
         $eventdata = new object();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $adminuser;
         $eventdata->userto = $adminuser;
         $eventdata->subject = "AUTHORIZE.NET CRON LOG";
         $eventdata->fullmessage = $this->log;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         events_trigger('message_send', $eventdata);
     }
     // Send emails to students about which courses have enrolled.
     if (!empty($sendem)) {
         mtrace("    sending welcome messages to students", ": ");
         send_welcome_messages($sendem);
         mtrace("sent");
     }
 }
Example #5
0
/**
 * authorize_print_order
 *
 * @param object $order
 */
function authorize_print_order($orderid)
{
    global $CFG, $USER, $DB, $OUTPUT, $PAGE;
    global $strs, $authstrs;
    $plugin = enrol_get_plugin('authorize');
    $an_test = $plugin->get_config('an_test');
    $do = optional_param('do', '', PARAM_ALPHA);
    $unenrol = optional_param('unenrol', 0, PARAM_BOOL);
    $confirm = optional_param('confirm', 0, PARAM_BOOL);
    if (!($order = $DB->get_record('enrol_authorize', array('id' => $orderid)))) {
        print_error('orderidnotfound', '', "{$CFG->wwwroot}/enrol/authorize/index.php", $orderid);
    }
    if (!($course = $DB->get_record('course', array('id' => $order->courseid)))) {
        print_error('invalidcourseid', '', "{$CFG->wwwroot}/enrol/authorize/index.php");
    }
    if (!($user = $DB->get_record('user', array('id' => $order->userid)))) {
        print_error('nousers', '', "{$CFG->wwwroot}/enrol/authorize/index.php");
    }
    $coursecontext = context_course::instance($course->id);
    if ($USER->id != $order->userid) {
        // Current user viewing someone else's order
        require_capability('enrol/authorize:managepayments', $coursecontext);
    }
    $settled = AuthorizeNet::settled($order);
    $statusandactions = authorize_get_status_action($order);
    $color = authorize_get_status_color($statusandactions->status);
    $buttons = '';
    if (empty($do)) {
        if (empty($statusandactions->actions)) {
            if (AN_METHOD_ECHECK == $order->paymentmethod && has_capability('enrol/authorize:uploadcsv', context_user::instance($USER->id))) {
                $buttons .= "<form method='get' action='uploadcsv.php'><div><input type='submit' value='" . get_string('uploadcsv', 'enrol_authorize') . "' /></div></form>";
            }
        } else {
            foreach ($statusandactions->actions as $val) {
                $buttons .= authorize_print_action_button($orderid, $val);
            }
        }
    }
    if (SITEID != $course->id) {
        $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
        $PAGE->navbar->add($shortname, new moodle_url('/course/view.php', array('id' => $course->id)));
    }
    $PAGE->navbar->add($authstrs->paymentmanagement, 'index.php?course=' . $course->id);
    $PAGE->navbar->add($authstrs->orderid . ': ' . $orderid, 'index.php');
    $PAGE->set_course($course);
    $PAGE->set_title("{$course->shortname}: {$authstrs->paymentmanagement}");
    $PAGE->set_heading($authstrs->orderdetails);
    $PAGE->set_cacheable(false);
    $PAGE->set_button($buttons);
    echo $OUTPUT->header();
    $table = new html_table();
    $table->width = '100%';
    $table->size = array('30%', '70%');
    $table->align = array('right', 'left');
    if (AN_METHOD_CC == $order->paymentmethod) {
        $table->data[] = array("<b>{$authstrs->paymentmethod}:</b>", $authstrs->methodcc);
        $table->data[] = array("<b>{$authstrs->nameoncard}:</b>", $order->ccname . ' (<b><a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '">' . fullname($user) . '</a></b>)');
        $table->data[] = array("<b>{$authstrs->cclastfour}:</b>", $order->refundinfo);
    } else {
        $table->data[] = array("<b>{$authstrs->paymentmethod}:</b>", $authstrs->methodecheck);
        $table->data[] = array("<b>{$authstrs->echeckfirslasttname}:</b>", $order->ccname . ' (<b><a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '">' . fullname($user) . '</a></b>)');
        $table->data[] = array("<b>{$authstrs->isbusinesschecking}:</b>", $order->refundinfo == 1 ? $strs->yes : $strs->no);
    }
    $table->data[] = array("<b>{$authstrs->amount}:</b>", "{$order->currency} {$order->amount}");
    $table->data[] = array("<b>{$authstrs->transid}:</b>", $order->transid);
    $table->data[] = array("<b>{$strs->time}:</b>", userdate($order->timecreated));
    $table->data[] = array("<b>{$authstrs->settlementdate}:</b>", $settled ? userdate($order->settletime) : $authstrs->notsettled);
    $table->data[] = array("<b>{$strs->status}:</b>", "<b><font style='color:{$color}'>" . $authstrs->{$statusandactions->status} . "</font></b>");
    if (ORDER_CAPTURE == $do && in_array(ORDER_CAPTURE, $statusandactions->actions)) {
        if ($confirm && confirm_sesskey()) {
            $message = '';
            $extra = NULL;
            if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
                if (empty($an_test)) {
                    if (enrol_into_course($course, $user, 'authorize')) {
                        if ($plugin->get_config('enrol_mailstudents')) {
                            send_welcome_messages($orderid);
                        }
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}");
                    } else {
                        $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", "Error while trying to enrol " . fullname($user) . " in '" . $shortname . "'", 20);
                    }
                } else {
                    redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", get_string('testwarning', 'enrol_authorize'), 10);
                }
            } else {
                redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $message, 20);
            }
        }
        $table->data[] = array("<b>{$strs->confirm}:</b>", get_string('captureyes', 'enrol_authorize') . '<br />' . authorize_print_action_button($orderid, ORDER_CAPTURE, 0, true, false, $strs->no));
        echo html_writer::table($table);
    } elseif (ORDER_REFUND == $do && in_array(ORDER_REFUND, $statusandactions->actions)) {
        $refunded = 0.0;
        $sql = "SELECT SUM(amount) AS refunded\n                  FROM {enrol_authorize_refunds}\n                 WHERE (orderid = ?)\n                   AND (status = ?)";
        if ($refundval = $DB->get_field_sql($sql, array($orderid, AN_STATUS_CREDIT))) {
            $refunded = floatval($refundval);
        }
        $upto = round($order->amount - $refunded, 2);
        if ($upto <= 0) {
            print_error('refoundtoorigi', '', "{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $order->amount);
        }
        $amount = round(optional_param('amount', $upto, PARAM_RAW), 2);
        if ($amount > $upto) {
            print_error('refoundto', '', "{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $upto);
        }
        if ($confirm && confirm_sesskey()) {
            $extra = new stdClass();
            $extra->orderid = $orderid;
            $extra->amount = $amount;
            $message = '';
            $success = AuthorizeNet::process($order, $message, $extra, AN_ACTION_CREDIT);
            if (AN_APPROVED == $success || AN_REVIEW == $success) {
                if (empty($an_test)) {
                    if (empty($extra->id)) {
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", "insert record error", 20);
                    } else {
                        if (!empty($unenrol)) {
                            $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid));
                            $plugin->unenrol_user($pinstance, $order->userid);
                            //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
                        }
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}");
                    }
                } else {
                    redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", get_string('testwarning', 'enrol_authorize'), 10);
                }
            } else {
                redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $message, 20);
            }
        }
        $a = new stdClass();
        $a->upto = $upto;
        $extrahtml = get_string('howmuch', 'enrol_authorize') . ' <input type="text" size="5" name="amount" value="' . $amount . '" /> ' . get_string('canbecredit', 'enrol_authorize', $a) . '<br />';
        $table->data[] = array("<b>{$strs->confirm}:</b>", authorize_print_action_button($orderid, ORDER_REFUND, 0, true, $authstrs->unenrolstudent, $strs->no, $extrahtml));
        echo html_writer::table($table);
    } elseif (ORDER_DELETE == $do && in_array(ORDER_DELETE, $statusandactions->actions)) {
        if ($confirm && confirm_sesskey()) {
            if (!empty($unenrol)) {
                $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid));
                $plugin->unenrol_user($pinstance, $order->userid);
                //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
            }
            $DB->delete_records('enrol_authorize', array('id' => $orderid));
            redirect("{$CFG->wwwroot}/enrol/authorize/index.php");
        }
        $table->data[] = array("<b>{$strs->confirm}:</b>", authorize_print_action_button($orderid, ORDER_DELETE, 0, true, $authstrs->unenrolstudent, $strs->no));
        echo html_writer::table($table);
    } elseif (ORDER_VOID == $do) {
        // special case: cancel original or refunded transaction?
        $suborderid = optional_param('suborder', 0, PARAM_INT);
        if (empty($suborderid) && in_array(ORDER_VOID, $statusandactions->actions)) {
            // cancel original
            if ($confirm && confirm_sesskey()) {
                $extra = NULL;
                $message = '';
                if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_VOID)) {
                    if (empty($an_test)) {
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}");
                    } else {
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", get_string('testwarning', 'enrol_authorize'), 10);
                    }
                } else {
                    redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $message, 20);
                }
            }
            $table->data[] = array("<b>{$strs->confirm}:</b>", get_string('voidyes', 'enrol_authorize') . '<br />' . authorize_print_action_button($orderid, ORDER_VOID, 0, true, false, $strs->no));
            echo html_writer::table($table);
        } elseif (!empty($suborderid)) {
            // cancel refunded
            $sql = "SELECT r.*, e.courseid, e.paymentmethod\n                      FROM {enrol_authorize_refunds} r\n                INNER JOIN {enrol_authorize} e\n                        ON r.orderid = e.id\n                     WHERE r.id = ?\n                       AND r.orderid = ?\n                       AND r.status = ?";
            $suborder = $DB->get_record_sql($sql, array($suborderid, $orderid, AN_STATUS_CREDIT));
            if (!$suborder) {
                // not found
                print_error('transactionvoid', '', "{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}");
            }
            $refundedstatus = authorize_get_status_action($suborder);
            unset($suborder->courseid);
            if (in_array(ORDER_VOID, $refundedstatus->actions)) {
                if ($confirm && confirm_sesskey()) {
                    $message = '';
                    $extra = NULL;
                    if (AN_APPROVED == AuthorizeNet::process($suborder, $message, $extra, AN_ACTION_VOID)) {
                        if (empty($an_test)) {
                            if (!empty($unenrol)) {
                                $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid));
                                $plugin->unenrol_user($pinstance, $order->userid);
                                //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
                            }
                            redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}");
                        } else {
                            redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", get_string('testwarning', 'enrol_authorize'), 10);
                        }
                    } else {
                        redirect("{$CFG->wwwroot}/enrol/authorize/index.php?order={$orderid}", $message, 20);
                    }
                }
                $a = new stdClass();
                $a->transid = $suborder->transid;
                $a->amount = $suborder->amount;
                $table->data[] = array("<b>{$strs->confirm}:</b>", get_string('subvoidyes', 'enrol_authorize', $a) . '<br />' . authorize_print_action_button($orderid, ORDER_VOID, $suborderid, true, $authstrs->unenrolstudent, $strs->no));
                echo html_writer::table($table);
            }
        }
    } else {
        echo html_writer::table($table);
        if ($settled) {
            // show refunds.
            $t2 = new html_table();
            $t2->size = array('45%', '15%', '20%', '10%', '10%');
            $t2->align = array('right', 'right', 'right', 'right', 'right');
            $t2->head = array($authstrs->settlementdate, $authstrs->transid, $strs->status, $strs->action, $authstrs->amount);
            $sql = "SELECT r.*, e.courseid, e.paymentmethod\n                      FROM {enrol_authorize_refunds} r\n                INNER JOIN {enrol_authorize} e\n                        ON r.orderid = e.id\n                     WHERE r.orderid = ?";
            if ($refunds = $DB->get_records_sql($sql, array($orderid))) {
                $sumrefund = floatval(0.0);
                foreach ($refunds as $rf) {
                    $subactions = '';
                    $substatus = authorize_get_status_action($rf);
                    if (empty($substatus->actions)) {
                        $subactions .= $strs->none;
                    } else {
                        foreach ($substatus->actions as $vl) {
                            $subactions .= authorize_print_action_button($orderid, $vl, $rf->id);
                        }
                    }
                    $sign = '';
                    $color = authorize_get_status_color($substatus->status);
                    if ($substatus->status == 'refunded' or $substatus->status == 'settled') {
                        $sign = '-';
                        $sumrefund += floatval($rf->amount);
                    }
                    $t2->data[] = array(userdate($rf->settletime), $rf->transid, "<b><font style='color:{$color}'>" . $authstrs->{$substatus->status} . "</font></b>", $subactions, format_float($sign . $rf->amount, 2));
                }
                $t2->data[] = array('', '', get_string('total'), $order->currency, format_float('-' . $sumrefund, 2));
            } else {
                $t2->data[] = array('', '', get_string('noreturns', 'enrol_authorize'), '', '');
            }
            echo "<h4>" . get_string('returns', 'enrol_authorize') . "</h4>\n";
            echo html_writer::table($t2);
        }
    }
    echo $OUTPUT->footer();
}
Example #6
0
function authorize_process_csv($filename)
{
    global $CFG, $SITE;
    /// We need these fields
    $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID');
    /// Open the file and get first line
    $handle = fopen($filename, "r");
    if (!$handle) {
        error('CANNOT OPEN CSV FILE');
    }
    $firstline = fgetcsv($handle, 8192, ",");
    $numfields = count($firstline);
    if ($numfields != 49 && $numfields != 70) {
        @fclose($handle);
        error('INVALID CSV FILE; Each line must include 49 or 70 fields');
    }
    /// Re-sort fields
    $csvfields = array();
    foreach ($myfields as $myfield) {
        $csvindex = array_search($myfield, $firstline);
        if ($csvindex === false) {
            $csvfields = array();
            break;
        }
        $csvfields[$myfield] = $csvindex;
    }
    if (empty($csvfields)) {
        @fclose($handle);
        error("<b>INVALID CSV FILE:</b> First line must include 'Header Fields' and\n               the file must be type of <br />'Expanded Fields/Comma Separated'<br />or<br />\n              'Expanded Fields with CAVV Result Code/Comma Separated'");
    }
    /// Read lines
    $sendem = array();
    $ignoredlines = '';
    $imported = 0;
    $updated = 0;
    $ignored = 0;
    while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
        if (count($data) != $numfields) {
            $ignored++;
            // ignore empty lines
            continue;
        }
        $transid = $data[$csvfields['Transaction ID']];
        $transtype = $data[$csvfields['Transaction Type']];
        $transstatus = $data[$csvfields['Transaction Status']];
        $reftransid = $data[$csvfields['Reference Transaction ID']];
        $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
        if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
            if ($order = get_record('enrol_authorize', 'transid', $transid)) {
                $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
                update_record('enrol_authorize', $order);
                $updated++;
                // Updated order status
            }
            continue;
        }
        if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
            if ($order = get_record('enrol_authorize', 'transid', $reftransid)) {
                if (AN_METHOD_ECHECK == $order->paymentmethod) {
                    $refund = get_record('enrol_authorize_refunds', 'transid', $transid);
                    if ($refund) {
                        $refund->status = AN_STATUS_CREDIT;
                        $refund->settletime = $settlementdate;
                        update_record('enrol_authorize_refunds', $refund);
                        $updated++;
                    } else {
                        $ignored++;
                        $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
                    }
                }
            } else {
                $ignored++;
                $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
            }
            continue;
        }
        if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
            $ignored++;
            $ignoredlines .= $transid . ": Not settled\n";
            continue;
        }
        // TransactionId must match
        $order = get_record('enrol_authorize', 'transid', $transid);
        if (!$order) {
            $ignored++;
            $ignoredlines .= $transid . ": Not our business\n";
            continue;
        }
        // Authorized/Captured and Settled
        $order->status = AN_STATUS_AUTHCAPTURE;
        $order->settletime = $settlementdate;
        update_record('enrol_authorize', $order);
        $updated++;
        // Updated order status and settlement date
        if ($order->paymentmethod != AN_METHOD_ECHECK) {
            $ignored++;
            $ignoredlines .= $transid . ": The method must be echeck\n";
            continue;
        }
        // Get course and context
        $course = get_record('course', 'id', $order->courseid);
        if (!$course) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
            continue;
        }
        $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
        if (!$coursecontext) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
            continue;
        }
        // Get user
        $user = get_record('user', 'id', $order->userid);
        if (!$user) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this user: "******"\n";
            continue;
        }
        // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
        if ($role = get_default_course_role($course)) {
            if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
                $timestart = $timeend = 0;
                if ($course->enrolperiod) {
                    $timestart = time();
                    $timeend = $timestart + $course->enrolperiod;
                }
                if (role_assign($role->id, $user->id, 0, $coursecontext->id, $timestart, $timeend, 0, 'authorize')) {
                    $imported++;
                    if (!empty($CFG->enrol_mailstudents)) {
                        $sendem[] = $order->id;
                    }
                } else {
                    $ignoredlines .= $transid . ": Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                }
            }
        }
    }
    fclose($handle);
    /// Send email to admin
    if (!empty($ignoredlines)) {
        $admin = get_admin();
        email_to_user($admin, $admin, "{$SITE->fullname}: Authorize.net CSV ERROR LOG", $ignoredlines);
    }
    /// Send welcome messages to users
    if (!empty($sendem)) {
        send_welcome_messages($sendem);
    }
    /// Show result
    notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}");
}