diff --git a/enrol/authorize/authorizenet.class.php b/enrol/authorize/authorizenet.class.php
index 9181964..08fb8e5 100644
--- a/enrol/authorize/authorizenet.class.php
+++ b/enrol/authorize/authorizenet.class.php
@@ -1,4 +1,31 @@
 <?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize enrolment plugin.
+ *
+ * This plugin allows you to set up paid courses, using authorize.net.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
 
 if (!defined('MOODLE_INTERNAL')) {
     die('Direct access to this script is forbidden.');
@@ -27,14 +54,13 @@ class AuthorizeNet
      */
     public static function getsettletime($time)
     {
-        global $CFG;
+        $mconfig = get_config('enrol_authorize');
 
-        $cutoff = intval($CFG->an_cutoff);
-        $mins = $cutoff % 60;
-        $hrs = ($cutoff - $mins) / 60;
-        $cutofftime = strtotime("$hrs:$mins", $time);
+        $cutoff_hour = intval($mconfig->an_cutoff_min);
+        $cutoff_min = intval($mconfig->an_cutoff_hour);
+        $cutofftime = strtotime("{$cutoff_hour}:{$cutoff_min}", $time);
         if ($cutofftime < $time) {
-            $cutofftime = strtotime("$hrs:$mins", $time + (24 * 3600));
+            $cutofftime = strtotime("{$cutoff_hour}:{$cutoff_min}", $time + (24 * 3600));
         }
         return $cutofftime;
     }
@@ -98,22 +124,24 @@ class AuthorizeNet
         static $constpd = array();
         require_once($CFG->libdir.'/filelib.php');
 
+        $mconfig = get_config('enrol_authorize');
+
         if (empty($constpd)) {
-            $mconfig = get_config('enrol/authorize');
+            $mconfig = get_config('enrol_authorize');
             $constpd = array(
                 'x_version'         => '3.1',
                 'x_delim_data'      => 'True',
                 'x_delim_char'      => self::AN_DELIM,
                 'x_encap_char'      => self::AN_ENCAP,
                 'x_relay_response'  => 'FALSE',
-                'x_login'           => rc4decrypt($mconfig->an_login)
+                'x_login'           => $mconfig->an_login
             );
 
             if (!empty($mconfig->an_tran_key)) {
-                $constpd['x_tran_key'] = rc4decrypt($mconfig->an_tran_key);
+                $constpd['x_tran_key'] = $mconfig->an_tran_key;
             }
             else {
-                $constpd['x_password'] = rc4decrypt($mconfig->an_password);
+                $constpd['x_password'] = $mconfig->an_password;
             }
         }
 
@@ -141,7 +169,7 @@ class AuthorizeNet
 
         $pd = $constpd;
         $pd['x_method'] = $method;
-        $test = !empty($CFG->an_test);
+        $test = !empty($mconfig->an_test);
         $pd['x_test_request'] = ($test ? 'TRUE' : 'FALSE');
 
         switch ($action) {
@@ -242,8 +270,8 @@ class AuthorizeNet
         }
 
         $headers = array('Connection' => 'close');
-        if (! (empty($CFG->an_referer) || $CFG->an_referer == "http://")) {
-            $headers['Referer'] = $CFG->an_referer;
+        if (! (empty($mconfig->an_referer) || $mconfig->an_referer == "http://")) {
+            $headers['Referer'] = $mconfig->an_referer;
         }
 
         @ignore_user_abort(true);
@@ -251,7 +279,7 @@ class AuthorizeNet
             @set_time_limit(300);
         }
 
-        $host = $test ? 'certification.authorize.net' : 'secure.authorize.net';
+        $host = $test ? 'test.authorize.net' : 'secure.authorize.net';
         $data = download_file_content("https://$host:443/gateway/transact.dll", $headers, $pd, false, 300, 60, true);
         if (!$data) {
             $message = "No connection to https://$host:443";
@@ -333,7 +361,7 @@ class AuthorizeNet
             if ($message == '[[' . $reasonstr . ']]') {
                 $message = isset($response[3]) ? $response[3] : 'unknown error';
             }
-            if ($method == AN_METHOD_CC && !empty($CFG->an_avs) && $response[5] != "P") {
+            if ($method == AN_METHOD_CC && !empty($mconfig->an_avs) && $response[5] != "P") {
                 $avs = "avs" . strtolower($response[5]);
                 $stravs = get_string($avs, "enrol_authorize");
                 $message .= "<br />" . get_string("avsresult", "enrol_authorize", $stravs);
@@ -346,8 +374,13 @@ class AuthorizeNet
                         {
                             if (!empty($cctype)) {
                                 $ccaccepts = get_list_of_creditcards();
+
                                 unset($ccaccepts[$cctype]);
-                                set_config('an_acceptccs', implode(',', array_keys($ccaccepts)));
+                                set_config("an_acceptcc_{$cctype}", 0, 'enrol_authorize');
+
+                                foreach ($ccaccepts as $key=>$val) {
+                                    set_config("an_acceptcc_{$key}", 1, 'enrol_authorize');
+                                }
                                 message_to_admin("$message ($cctype) This is new config(an_acceptccs):", $ccaccepts);
                             }
                             break;
@@ -355,14 +388,14 @@ class AuthorizeNet
                     // Echecks only
                     case self::AN_REASON_ACHONLY:
                         {
-                            set_config('an_acceptmethods', AN_METHOD_ECHECK);
+                            set_config("an_acceptmethod_".AN_METHOD_ECHECK, 1, 'enrol_authorize');
                             message_to_admin("$message This is new config(an_acceptmethods):", array(AN_METHOD_ECHECK));
                             break;
                         }
                     // Echecks aren't accepted
                     case self::AN_REASON_NOACH:
                         {
-                            set_config('an_acceptmethods', AN_METHOD_CC);
+                            set_config("an_acceptmethod_".AN_METHOD_CC, 1, 'enrol_authorize');
                             message_to_admin("$message This is new config(an_acceptmethods):", array(AN_METHOD_CC));
                             break;
                         }
@@ -375,14 +408,15 @@ class AuthorizeNet
                                     // CCD=BUSINESSCHECKING
                                     case 'CCD':
                                         {
-                                            set_config('an_acceptechecktypes', 'CHECKING,SAVINGS');
+                                            set_config('an_acceptecheck_CHECKING', 1, 'enrol_authorize');
+                                            set_config('an_acceptecheck_SAVINGS', 1, 'enrol_authorize');
                                             message_to_admin("$message This is new config(an_acceptechecktypes):", array('CHECKING','SAVINGS'));
                                         }
                                         break;
                                     // WEB=CHECKING or SAVINGS
                                     case 'WEB':
                                         {
-                                            set_config('an_acceptechecktypes', 'BUSINESSCHECKING');
+                                            set_config('an_acceptecheck_BUSINESSCHECKING', 1, 'enrol_authorize');
                                             message_to_admin("$message This is new config(an_acceptechecktypes):", array('BUSINESSCHECKING'));
                                         }
                                         break;
diff --git a/enrol/authorize/config_form.php b/enrol/authorize/config_form.php
deleted file mode 100755
index 730654c..0000000
--- a/enrol/authorize/config_form.php
+++ /dev/null
@@ -1,243 +0,0 @@
-<?php
-
-if (!defined('MOODLE_INTERNAL')) {
-    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
-}
-
-
-if (!isset($frm->enrol_cost)) $frm->enrol_cost = '5';
-if (!isset($frm->enrol_currency)) $frm->enrol_currency = 'USD';
-if (!isset($frm->enrol_mailstudents)) $frm->enrol_mailstudents = '';
-if (!isset($frm->enrol_mailteachers)) $frm->enrol_mailteachers = '';
-if (!isset($frm->enrol_mailadmins)) $frm->enrol_mailadmins = '';
-
-if (!isset($frm->an_login)) $frm->an_login = '';
-if (!isset($frm->an_tran_key)) $frm->an_tran_key = '';
-if (!isset($frm->an_password)) $frm->an_password = '';
-if (!isset($frm->delete_current)) $frm->delete_current = '';
-if (!isset($frm->an_referer)) $frm->an_referer = 'http://';
-if (!isset($frm->an_avs)) $frm->an_avs = '';
-if (!isset($frm->an_authcode)) $frm->an_authcode = '';
-if (!isset($frm->an_test)) $frm->an_test = '';
-if (!isset($frm->an_review)) $frm->an_review = '';
-if (!isset($frm->an_capture_day)) $frm->an_capture_day = '5';
-if (!isset($frm->an_emailexpired)) $frm->an_emailexpired = '2';
-if (!isset($frm->an_emailexpiredteacher)) $frm->an_emailexpiredteacher = '';
-if (!isset($frm->an_sorttype)) $frm->an_sorttype = 'ttl';
-
-if (isset($CFG->an_cutoff)) {
-    $cutoff = intval($CFG->an_cutoff);
-    $mins = $cutoff % 60; $hrs = ($cutoff - $mins) / 60;
-    $frm->an_cutoff_hour = $hrs; $frm->an_cutoff_min = $mins;
-}
-if (!isset($frm->an_cutoff_hour)) {
-    $timezone = round(get_user_timezone_offset(), 1);
-    $frm->an_cutoff_hour = intval($timezone);
-    $frm->an_cutoff_min = (intval(round($timezone)) != intval($timezone)) ? 35 : 5;
-}
-
-if (!isset($frm->acceptmethods)) {
-    $frm->acceptmethods = get_list_of_payment_methods();
-    $CFG->an_acceptmethods = implode(',', $frm->acceptmethods);
-}
-
-if (!isset($frm->acceptccs)) {
-    $frm->acceptccs = array_keys(get_list_of_creditcards());
-    $CFG->an_acceptccs = implode(',', $frm->acceptccs);
-}
-
-if (!isset($frm->acceptechecktypes)) {
-    $frm->acceptechecktypes = get_list_of_bank_account_types();
-    $CFG->an_acceptechecktypes = implode(',', $frm->acceptechecktypes);
-}
-
-?>
-
-<table cellspacing="0" cellpadding="5" border="0" class="boxaligncenter">
-
-<tr valign="top">
-    <td colspan="2" align="right"><a href="../enrol/authorize/index.php"><?php print_string("paymentmanagement", "enrol_authorize") ?></a></td>
-</tr>
-
-<tr valign="top"><td colspan="2"><h4><?php print_string("adminauthorizewide", "enrol_authorize") ?></h4></td></tr>
-
-<tr valign="top">
-    <td align="right">enrol_cost:</td>
-    <td><input type="text" size="5" name="enrol_cost" value="<?php p($frm->enrol_cost) ?>" /><br />
-        <?php print_string("costdefault") ?>. <?php print_string("costdefaultdesc", "enrol_authorize") ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">enrol_currency:</td>
-    <td><?php
-        echo html_writer::select(get_string_manager()->get_list_of_currencies(), "enrol_currency", $frm->enrol_currency, false);
-        ?>
-        <br />
-        <?php print_string("currency") ?>
-    </td>
-</tr>
-
-<tr valign="top"><td colspan="2"><h4><?php print_string("adminauthorizesettings", "enrol_authorize") ?></h4></td></tr>
-
-<tr valign="top">
-    <td align="right">&nbsp;&nbsp;</td>
-    <td><?php print_string("logininfo", "enrol_authorize") ?><br />
-    <?php if (!optional_param('verifyaccount', 0, PARAM_INT) && isset($mconfig->an_login) && (isset($mconfig->an_tran_key) || isset($mconfig->an_password))) { ?>
-        <br /><a href="enrol_config.php?enrol=authorize&amp;verifyaccount=1"><b><?php print_string("verifyaccount", "enrol_authorize") ?></b></a><br />
-    <?php } ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_login:<br /><?php echo (isset($mconfig->an_login)) ? '<span style="color:green">'.get_string('dataentered', 'enrol_authorize').'</span>' : ''; ?></td>
-    <td><?php print_string("anlogin", "enrol_authorize") ?><br /><input type="text" name="an_login" size="26" value="" /><sup>*</sup></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_tran_key:<br /><?php echo (isset($mconfig->an_tran_key)) ? '<span style="color:green">'.get_string('dataentered', 'enrol_authorize').'</span>' : ''; ?></td>
-    <td><?php print_string("antrankey", "enrol_authorize") ?><br /><input type="text" name="an_tran_key" size="26" value="" /><sup>#1</sup></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_password:<br /><?php echo (isset($mconfig->an_password)) ? '<span style="color:green">'.get_string('dataentered', 'enrol_authorize').'</span>' : ''; ?></td>
-    <td><?php print_string("anpassword", "enrol_authorize") ?><br /><input type="text" name="an_password" size="26" value="" /><sup>#2</sup></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">delete_current:</td>
-    <td><?php echo html_writer::checkbox('delete_current', '1', !empty($frm->delete_current), get_string("deletecheck", "moodle", get_string('oldpassword')));?> <br />
-        <hr /></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_referer:</td>
-    <td><input type="text" name="an_referer" size="35" value="<?php p($frm->an_referer) ?>" /><br />
-        <?php print_string("anreferer", "enrol_authorize") ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_cutoff:</td>
-    <td><?php
-        $curtime = make_timestamp(2000,1,1,$frm->an_cutoff_hour,$frm->an_cutoff_min);
-        $hourselector = html_writer::select_time('hours', 'an_cutoff_hour', $curtime);
-        $minselector = html_writer::select_time('minutes', 'an_cutoff_min', $curtime);
-        echo $hourselector . $minselector;
-        ?><br />
-        <?php print_string("cutofftime", "enrol_authorize") ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_avs:</td>
-    <td><?php echo html_writer::checkbox('an_avs', '1', !empty($frm->an_avs), get_string("adminavs", "enrol_authorize")); ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_authcode:</td>
-    <td><?php echo html_writer::checkbox('an_authcode', '1', !empty($frm->an_authcode), get_string("adminauthcode", "enrol_authorize"));  ?>
-        <?php echo $OUTPUT->old_help_icon('authorize/authcode', 'authcode', 'enrol'); ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_test:</td>
-    <td><?php echo html_writer::checkbox('an_test', '1', !empty($frm->an_test), get_string("antestmode", "enrol_authorize"));  ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">accepts:</td>
-    <td><?php print_string("adminaccepts", "enrol_authorize") ?><br /><br /><?php
-    $paymentmethodsenabled = get_list_of_payment_methods();
-    $allpaymentmethods = get_list_of_payment_methods(true);
-    foreach ($allpaymentmethods as $key) {
-        if ($key == AN_METHOD_CC) {
-            echo html_writer::checkbox('acceptmethods[]', AN_METHOD_CC, in_array(AN_METHOD_CC, $paymentmethodsenabled), get_string('method'.AN_METHOD_CC,'enrol_authorize'));
-            echo("<ul>"); // blockquote breaks <span> and <br> tags
-            $acceptedccs = array_keys(get_list_of_creditcards());
-            $allccs = get_list_of_creditcards(true);
-            foreach ($allccs as $key => $val) {
-                echo "<li>";
-                echo html_writer::checkbox('acceptccs[]', $key, in_array($key, $acceptedccs), $val);
-                echo "</li>";
-            }
-            echo("</ul>");
-        }
-        elseif ($key == AN_METHOD_ECHECK) {
-            echo html_writer::checkbox('acceptmethods[]', AN_METHOD_ECHECK, in_array(AN_METHOD_ECHECK, $paymentmethodsenabled), get_string('method'.AN_METHOD_ECHECK, 'enrol_authorize'));
-            echo("<ul>"); // blockquote breaks <span> and <br> tags
-            $echecktypesenabled = get_list_of_bank_account_types();
-            $allechecktypes = get_list_of_bank_account_types(true);
-            foreach ($allechecktypes as $key) {
-                echo "<li>";
-                echo html_writer::checkbox('acceptechecktypes[]', $key, in_array($key, $echecktypesenabled), get_string('echeck'.strtolower($key)));
-                echo "</li>";
-            }
-            echo("</ul>");
-        }
-    }
-    ?><br /></td>
-</tr>
-
-<tr valign="top"><td colspan="2"><h4><?php print_string("adminauthorizeccapture", "enrol_authorize") ?>
-                                     <?php echo $OUTPUT->old_help_icon('authorize/orderreview', 'orderreview', 'enrol'); ?>
-                                 </h4></td></tr>
-
-<tr valign="top">
-    <td align="right">an_review:</td>
-    <td><?php echo html_writer::checkbox('an_review', '1', !empty($frm->an_review), get_string("adminreview", "enrol_authorize")); ?>
-        <?php echo $OUTPUT->old_help_icon('authorize/review', get_string('adminhelpreviewtitle', 'enrol_authorize'), 'enrol'); ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_capture_day:</td>
-    <td><input type="text" name="an_capture_day" size="2" maxlength="2" value="<?php p($frm->an_capture_day) ?>" />
-        <?php echo $OUTPUT->old_help_icon('authorize/captureday', get_string('adminhelpcapturetitle', 'enrol_authorize'), 'enrol'); ?><br />
-        <?php print_string("reviewday", "enrol_authorize", $frm->an_capture_day) ?></td>
-</tr>
-
-<tr valign="top"><td colspan="2"><h4><?php print_string("adminauthorizeemail", "enrol_authorize") ?></h4></td></tr>
-
-<tr valign="top">
-    <td align="right">an_emailexpired:</td>
-    <td><input type="text" name="an_emailexpired" size="1" maxlength="1" value="<?php p($frm->an_emailexpired) ?>" /><br />
-        <?php print_string("adminemailexpired", "enrol_authorize", $frm->an_emailexpired) ?><br />
-        <?php print_string("adminemailexpsetting", "enrol_authorize") ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_emailexpiredteacher:</td>
-    <td><?php echo html_writer::checkbox('an_emailexpiredteacher', '1', !empty($frm->an_emailexpiredteacher), get_string("adminemailexpiredteacher", "enrol_authorize"));  ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">an_sorttype:</td>
-    <td><?php
-    $sorts = array('ttl' => get_string('adminemailexpiredsortsum', 'enrol_authorize'),
-                   'cnt' => get_string('adminemailexpiredsortcount', 'enrol_authorize'));
-    echo html_writer::select($sorts, "an_sorttype", $frm->an_sorttype, false);
-    ?>
-    <br />
-    <?php print_string("adminemailexpiredsort", "enrol_authorize") ?></td>
-</tr>
-
-<tr valign="top">
-    <td align="right">enrol_mailstudents:</td>
-    <td><?php echo html_writer::checkbox('enrol_mailstudents', '1', !empty($frm->enrol_mailstudents), get_string("mailstudents")); ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">enrol_mailteachers:</td>
-    <td><?php echo html_writer::checkbox('enrol_mailteachers', '1', !empty($frm->enrol_mailteachers), get_string("mailteachers"));  ?><br />
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right">enrol_mailadmins:</td>
-    <td><?php echo html_writer::checkbox('enrol_mailadmins', '1', !empty($frm->enrol_mailadmins), get_string("mailadmins"));  ?><br />
-    </td>
-</tr>
-
-</table>
diff --git a/enrol/authorize/db/access.php b/enrol/authorize/db/access.php
index 5ef473c..38a7409 100644
--- a/enrol/authorize/db/access.php
+++ b/enrol/authorize/db/access.php
@@ -2,6 +2,39 @@
 
 $capabilities = array(
 
+    'enrol/authorize:config' => array(
+        'captype' => 'write',
+        'contextlevel' => CONTEXT_COURSE,
+        'legacy' => array(
+            'manager' => CAP_ALLOW,
+        )
+    ),
+
+    'enrol/authorize:manage' => array(
+        'captype' => 'write',
+        'contextlevel' => CONTEXT_COURSE,
+        'legacy' => array(
+            'manager' => CAP_ALLOW,
+            'editingteacher' => CAP_ALLOW,
+        )
+    ),
+
+    'enrol/authorize:unenrol' => array(
+        'captype' => 'write',
+        'contextlevel' => CONTEXT_COURSE,
+        'legacy' => array(
+            'manager' => CAP_ALLOW,
+        )
+    ),
+
+    'enrol/authorize:unenrolself' => array(
+        'captype' => 'write',
+        'contextlevel' => CONTEXT_COURSE,
+        'legacy' => array(
+        )
+    ),
+
+
     'enrol/authorize:managepayments' => array(
         'riskbitmask' => RISK_PERSONAL,
         'captype' => 'write',
diff --git a/enrol/authorize/db/install.xml b/enrol/authorize/db/install.xml
index 6ac4bd3..0a65b29 100644
--- a/enrol/authorize/db/install.xml
+++ b/enrol/authorize/db/install.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8" ?>
-<XMLDB PATH="enrol/authorize/db" VERSION="20080927" COMMENT="XMLDB file for Moodle enrol/authorize"
+<XMLDB PATH="enrol/authorize/db" VERSION="20100812" COMMENT="XMLDB file for Moodle enrol/authorize"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd"
 >
@@ -10,8 +10,9 @@
         <FIELD NAME="paymentmethod" TYPE="char" LENGTH="6" NOTNULL="true" DEFAULT="cc" SEQUENCE="false" PREVIOUS="id" NEXT="refundinfo"/>
         <FIELD NAME="refundinfo" TYPE="int" LENGTH="4" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="paymentmethod" NEXT="ccname"/>
         <FIELD NAME="ccname" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" PREVIOUS="refundinfo" NEXT="courseid"/>
-        <FIELD NAME="courseid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="ccname" NEXT="userid"/>
-        <FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="courseid" NEXT="transid"/>
+        <FIELD NAME="courseid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="ccname" NEXT="instanceid"/>
+        <FIELD NAME="instanceid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="courseid" NEXT="userid"/>
+        <FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="instanceid" NEXT="transid"/>
         <FIELD NAME="transid" TYPE="int" LENGTH="20" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="userid" NEXT="status"/>
         <FIELD NAME="status" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="transid" NEXT="timecreated"/>
         <FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="status" NEXT="settletime"/>
@@ -47,4 +48,4 @@
       </INDEXES>
     </TABLE>
   </TABLES>
-</XMLDB>
+</XMLDB>
\ No newline at end of file
diff --git a/enrol/authorize/db/upgrade.php b/enrol/authorize/db/upgrade.php
index a5e9d8f..573e7fa 100644
--- a/enrol/authorize/db/upgrade.php
+++ b/enrol/authorize/db/upgrade.php
@@ -82,7 +82,16 @@ function xmldb_enrol_authorize_upgrade($oldversion) {
         upgrade_plugin_savepoint(true, 2009042700, 'enrol', 'authorize');
     }
 
+    // Add instanceid field to enrol_authorize table
+    if ($oldversion < 2010081203) {
+        $table = new xmldb_table('enrol_authorize');
+        $field = new xmldb_field('instanceid');
+        if (!$dbman->field_exists($table, $field)) {
+            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'userid');
+            $dbman->add_field($table, $field);
+        }
+        upgrade_plugin_savepoint(true, 2010081203, 'enrol', 'authorize');
+    }
+
     return true;
 }
-
-
diff --git a/enrol/authorize/edit.php b/enrol/authorize/edit.php
new file mode 100644
index 0000000..8196969
--- /dev/null
+++ b/enrol/authorize/edit.php
@@ -0,0 +1,95 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Adds new instance of enrol_authorize to specified course
+ * or edits current instance.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require('../../config.php');
+require_once('edit_form.php');
+
+$courseid   = required_param('courseid', PARAM_INT);
+$instanceid = optional_param('id', 0, PARAM_INT); // instanceid
+
+$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
+$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
+
+require_login($course);
+require_capability('enrol/authorize:config', $context);
+
+$PAGE->set_url('/enrol/authorize/edit.php', array('courseid'=>$course->id, 'id'=>$instanceid));
+$PAGE->set_pagelayout('admin');
+
+$return = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
+if (!enrol_is_enabled('authorize')) {
+    redirect($return);
+}
+
+$plugin = enrol_get_plugin('authorize');
+
+if ($instanceid) {
+    $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'authorize', 'id'=>$instanceid), '*', MUST_EXIST);
+} else {
+    require_capability('moodle/course:enrolconfig', $context);
+    // no instance yet, we have to add new instance
+    navigation_node::override_active_url(new moodle_url('/enrol/instances.php', array('id'=>$course->id)));
+    $instance = new object();
+    $instance->id       = null;
+    $instance->courseid = $course->id;
+}
+
+$mform = new enrol_authorize_edit_form(NULL, array($instance, $plugin, $context));
+
+if ($mform->is_cancelled()) {
+    redirect($return);
+
+} else if ($data = $mform->get_data()) {
+    if ($instance->id) {
+        $instance->status         = $data->status;
+        $instance->name           = $data->name;
+        $instance->cost           = $data->cost;
+        $instance->currency       = $data->currency;
+        //$instance->roleid         = $data->roleid;
+        $instance->enrolperiod    = $data->enrolperiod;
+        $instance->enrolstartdate = $data->enrolstartdate;
+        $instance->enrolenddate   = $data->enrolenddate;
+        $instance->timemodified   = time();
+        $DB->update_record('enrol', $instance);
+
+    } else {
+        $fields = array('status'=>$data->status, 'name'=>$data->name, 'cost'=>$data->cost, 'currency'=>$data->currency,
+                        'enrolperiod'=>$data->enrolperiod, 'enrolstartdate'=>$data->enrolstartdate, 'enrolenddate'=>$data->enrolenddate);
+        $plugin->add_instance($course, $fields);
+    }
+
+    redirect($return);
+}
+
+$PAGE->set_heading($course->fullname);
+$PAGE->set_title(get_string('pluginname', 'enrol_authorize'));
+
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('pluginname', 'enrol_authorize'));
+$mform->display();
+echo $OUTPUT->footer();
diff --git a/enrol/authorize/edit_form.php b/enrol/authorize/edit_form.php
new file mode 100644
index 0000000..d87e56e
--- /dev/null
+++ b/enrol/authorize/edit_form.php
@@ -0,0 +1,99 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Adds new instance of enrol_authorize to specified course
+ * or edits current instance.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once($CFG->libdir.'/formslib.php');
+
+class enrol_authorize_edit_form extends moodleform {
+
+    function definition() {
+        $mform = $this->_form;
+
+        list($instance, $plugin, $context) = $this->_customdata;
+
+        $mform->addElement('header', 'header', get_string('pluginname', 'enrol_authorize'));
+
+        $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
+
+        $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
+                         ENROL_INSTANCE_DISABLED => get_string('no'));
+        $mform->addElement('select', 'status', get_string('status', 'enrol_authorize'), $options);
+        $mform->setDefault('status', $plugin->get_config('status'));
+
+        $mform->addElement('text', 'cost', get_string('cost', 'enrol_authorize'), array('size'=>4));
+        $mform->setDefault('cost', $plugin->get_config('cost'));
+
+        $mform->addElement('select', 'currency', get_string('currency', 'enrol_authorize'), get_string_manager()->get_list_of_currencies());
+        $mform->setDefault('currency', $plugin->get_config('currency'));
+
+        if ($instance->id) {
+            $roles = get_default_enrol_roles($context, $instance->roleid);
+        } else {
+            $roles = get_default_enrol_roles($context, $plugin->get_config('roleid'));
+        }
+        $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_paypal'), $roles);
+        $mform->setDefault('roleid', $plugin->get_config('roleid'));
+
+        $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_authorize'), array('optional' => true, 'defaultunit' => 86400));
+        $mform->setDefault('enrolperiod', $plugin->get_config('enrolperiod'));
+
+        $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_authorize'), array('optional' => true));
+        $mform->setDefault('enrolstartdate', 0);
+
+        $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_authorize'), array('optional' => true));
+        $mform->setDefault('enrolenddate', 0);
+
+        $mform->addElement('hidden', 'id');
+        $mform->addElement('hidden', 'courseid');
+
+        $this->add_action_buttons(true, ($instance->id ? null : get_string('addinstance', 'enrol')));
+
+        $this->set_data($instance);
+    }
+
+    function validation($data, $files) {
+        global $DB, $CFG;
+        $errors = parent::validation($data, $files);
+
+        list($instance, $plugin, $context) = $this->_customdata;
+
+        if ($data['status'] == ENROL_INSTANCE_ENABLED) {
+            if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
+                $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_authorize');
+            }
+
+            if (!is_numeric($data['cost'])) {
+                $errors['cost'] = get_string('costerror', 'enrol_authorize');
+
+            }
+        }
+
+        return $errors;
+    }
+}
diff --git a/enrol/authorize/enrol.php b/enrol/authorize/enrol.php
deleted file mode 100755
index c342bab..0000000
--- a/enrol/authorize/enrol.php
+++ /dev/null
@@ -1,905 +0,0 @@
-<?php
-
-require_once($CFG->dirroot.'/enrol/authorize/const.php');
-require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
-require_once($CFG->dirroot.'/enrol/authorize/authorizenet.class.php');
-require_once($CFG->libdir.'/eventslib.php');
-
-/**
- * Authorize.net Payment Gateway plugin
- */
-class enrolment_plugin_authorize
-{
-
-    /**
-     * Cron log.
-     *
-     * @var string
-     * @access public
-     */
-    public $log;
-
-
-    /**
-     * Presents registration forms.
-     *
-     * @param object $course Course info
-     * @access public
-     */
-    public function print_entry($course)
-    {
-        global $CFG, $USER, $OUTPUT, $PAGE, $form;
-
-        $zerocost = zero_cost($course);
-        if ($zerocost) {
-            $manual = enrolment_factory::factory('manual');
-            if (!empty($this->errormsg)) {
-                $manual->errormsg = $this->errormsg;
-            }
-            $manual->print_entry($course);
-            return;
-        }
-
-        prevent_double_paid($course);
-        httpsrequired();
-
-        if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
-            if (empty($CFG->loginhttps)) {
-                print_error('httpsrequired', 'enrol_authorize');
-            } else {
-                $wwwsroot = str_replace('http:','https:', $CFG->wwwroot);
-                redirect("$wwwsroot/enrol/index.php?id=$course->id");
-                exit;
-            }
-        }
-
-        $strcourses = get_string('courses');
-        $strloginto = get_string('loginto', '', $course->shortname);
-
-        $PAGE->navbar->add($strcourses, new moodle_url('/course/'));
-        $PAGE->navbar->add($strloginto);
-        $PAGE->set_title($strloginto);
-        $PAGE->set_heading($course->fullname);
-        echo $OUTPUT->header();
-        print_course($course, '80%');
-
-        if ($course->password) {
-            echo $OUTPUT->heading(get_string('choosemethod', 'enrol_authorize'));
-        }
-
-        if ($USER->username == 'guest') { // only real guest user, not for users with guest role
-            $curcost = get_course_cost($course);
-            echo '<div class="mdl-align">';
-            echo '<p>'.get_string('paymentrequired').'</p>';
-            echo '<p><b>'.get_string('cost').": $curcost[currency] $curcost[cost]".'</b></p>';
-            echo '<p><a href="'.$CFG->httpswwwroot.'/login/">'.get_string('loginsite').'</a></p>';
-            echo '</div>';
-        }
-        else {
-            require_once($CFG->dirroot.'/enrol/authorize/enrol_form.php');
-            $frmenrol = new enrol_authorize_form('enrol.php', compact('course'));
-            if ($frmenrol->get_data()) {
-                $authorizeerror = '';
-                switch ($form->paymentmethod) {
-                    case AN_METHOD_CC:
-                        $authorizeerror = $this->cc_submit($form, $course);
-                        break;
-
-                    case AN_METHOD_ECHECK:
-                        $authorizeerror = $this->echeck_submit($form, $course);
-                        break;
-                }
-                if (!empty($authorizeerror)) {
-                    print_error('authorizeerror', 'enrol_authorize', '', $authorizeerror);
-                }
-            }
-
-            echo $OUTPUT->box_start();
-            $frmenrol->display();
-            echo $OUTPUT->box_end();
-        }
-
-        if ($course->password) {
-            $password = '';
-            include($CFG->dirroot.'/enrol/manual/enrol.html');
-        }
-
-        echo $OUTPUT->footer();
-    }
-
-
-    function print_enrolmentkeyfrom($course)
-    {
-        $manual = enrolment_factory::factory('manual');
-        $manual->print_enrolmentkeyfrom($course);
-    }
-
-
-    /**
-     * Validates registration forms and enrols student to course.
-     *
-     * @param object $form Form parameters
-     * @param object $course Course info
-     * @access public
-     */
-    public function check_entry($form, $course)
-    {
-        global $CFG;
-
-        if (zero_cost($course) || (!empty($course->password) && !empty($form->enrol) && $form->enrol == 'manual')) {
-            $manual = enrolment_factory::factory('manual');
-            $manual->check_entry($form, $course);
-            if (!empty($manual->errormsg)) {
-                $this->errormsg = $manual->errormsg;
-            }
-        }
-    }
-
-
-
-    /**
-     * The user submitted credit card form.
-     *
-     * @param object $form Form parameters
-     * @param object $course Course info
-     * @return string NULL if ok, error message otherwise.
-     * @access private
-     */
-    private function cc_submit($form, $course)
-    {
-        global $CFG, $USER, $SESSION, $OUTPUT, $DB;
-
-        prevent_double_paid($course);
-
-        $useripno = getremoteaddr();
-        $curcost = get_course_cost($course);
-        $exp_date = sprintf("%02d", $form->ccexpiremm) . $form->ccexpireyyyy;
-
-        // NEW CC ORDER
-        $timenow = time();
-        $order = new stdClass();
-        $order->paymentmethod = AN_METHOD_CC;
-        $order->refundinfo = substr($form->cc, -4);
-        $order->ccname = $form->firstname . " " . $form->lastname;
-        $order->courseid = $course->id;
-        $order->userid = $USER->id;
-        $order->status = AN_STATUS_NONE; // it will be changed...
-        $order->settletime = 0; // cron changes this.
-        $order->transid = 0; // Transaction Id
-        $order->timecreated = $timenow;
-        $order->amount = $curcost['cost'];
-        $order->currency = $curcost['currency'];
-        $order->id = $DB->insert_record("enrol_authorize", $order);
-        if (!$order->id) {
-            message_to_admin("Error while trying to insert new data", $order);
-            return "Insert record error. Admin has been notified!";
-        }
-
-        $extra = new stdClass();
-        $extra->x_card_num = $form->cc;
-        $extra->x_card_code = $form->cvv;
-        $extra->x_exp_date = $exp_date;
-        $extra->x_currency_code = $curcost['currency'];
-        $extra->x_amount = $curcost['cost'];
-        $extra->x_first_name = $form->firstname;
-        $extra->x_last_name = $form->lastname;
-        $extra->x_country = $form->cccountry;
-        $extra->x_address = $form->ccaddress;
-        $extra->x_state = $form->ccstate;
-        $extra->x_city = $form->cccity;
-        $extra->x_zip = $form->cczip;
-
-        $extra->x_invoice_num = $order->id;
-        $extra->x_description = $course->shortname;
-
-        $extra->x_cust_id = $USER->id;
-        $extra->x_email = $USER->email;
-        $extra->x_customer_ip = $useripno;
-        $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE';
-        $extra->x_phone = '';
-        $extra->x_fax = '';
-
-        if (!empty($CFG->an_authcode) && !empty($form->ccauthcode)) {
-            $action = AN_ACTION_CAPTURE_ONLY;
-            $extra->x_auth_code = $form->ccauthcode;
-        }
-        elseif (!empty($CFG->an_review)) {
-            $action = AN_ACTION_AUTH_ONLY;
-        }
-        else {
-            $action = AN_ACTION_AUTH_CAPTURE;
-        }
-
-        $message = '';
-        if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, $action, $form->cctype))
-        {
-            $SESSION->ccpaid = 1; // security check: don't duplicate payment
-
-            switch ($action)
-            {
-                // review enabled (authorize but capture: draw money but wait for settlement during 30 days)
-                // the first step is to inform payment managers and to redirect the user to main page.
-                // the next step is to accept/deny payment (AN_ACTION_PRIOR_AUTH_CAPTURE/VOID) within 30 days (payment management or scheduled-capture CRON)
-                // unless you accept payment or enable auto-capture cron, the transaction is expired after 30 days and the user cannot enrol to the course during 30 days.
-                // see also: admin/cron.php, $this->cron(), $CFG->an_capture_day...
-                case AN_ACTION_AUTH_ONLY:
-                {
-                    $a = new stdClass;
-                    $a->url = "$CFG->wwwroot/enrol/authorize/index.php?order=$order->id";
-                    $a->orderid = $order->id;
-                    $a->transid = $order->transid;
-                    $a->amount = "$order->currency $order->amount";
-                    $a->expireon = userdate(AuthorizeNet::getsettletime($timenow + (30 * 3600 * 24)));
-                    $a->captureon = userdate(AuthorizeNet::getsettletime($timenow + (intval($CFG->an_capture_day) * 3600 * 24)));
-                    $a->course = $course->fullname;
-                    $a->user = fullname($USER);
-                    $a->acstatus = ($CFG->an_capture_day > 0) ? get_string('yes') : get_string('no');
-                    $emailmessage = get_string('adminneworder', 'enrol_authorize', $a);
-                    $a = new stdClass;
-                    $a->course = $course->shortname;
-                    $a->orderid = $order->id;
-                    $emailsubject = get_string('adminnewordersubject', 'enrol_authorize', $a);
-                    $context = get_context_instance(CONTEXT_COURSE, $course->id);
-                    if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
-                        foreach ($paymentmanagers as $paymentmanager) {
-                            $eventdata = new object();
-                            $eventdata->modulename        = 'moodle';
-                            $eventdata->userfrom          = $USER;
-                            $eventdata->userto            = $paymentmanager;
-                            $eventdata->subject           = $emailsubject;
-                            $eventdata->fullmessage       = $emailmessage;
-                            $eventdata->fullmessageformat = FORMAT_PLAIN;
-                            $eventdata->fullmessagehtml   = '';
-                            $eventdata->smallmessage      = '';
-                            message_send($eventdata);
-                        }
-                    }
-                    redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
-                    break;
-                }
-
-                case AN_ACTION_CAPTURE_ONLY: // auth code received via phone and the code accepted.
-                case AN_ACTION_AUTH_CAPTURE: // real time transaction, authorize and capture.
-                {
-                    // Credit card captured, ENROL student now...
-                    if (enrol_into_course($course, $USER, 'authorize'))
-                    {
-                        if (!empty($CFG->enrol_mailstudents)) {
-                            send_welcome_messages($order->id);
-                        }
-                        if (!empty($CFG->enrol_mailteachers)) {
-                            $context = get_context_instance(CONTEXT_COURSE, $course->id);
-                            $paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments', '', '', '0', '1');
-                            $paymentmanager = array_shift($paymentmanagers);
-                            $a = new stdClass;
-                            $a->course = "$course->fullname";
-                            $a->user = fullname($USER);
-
-                            $eventdata = new object();
-                            $eventdata->modulename        = 'moodle';
-                            $eventdata->userfrom          = $USER;
-                            $eventdata->userto            = $paymentmanager;
-                            $eventdata->subject           = get_string("enrolmentnew", '', format_string($course->shortname));
-                            $eventdata->fullmessage       = get_string('enrolmentnewuser', '', $a);
-                            $eventdata->fullmessageformat = FORMAT_PLAIN;
-                            $eventdata->fullmessagehtml   = '';
-                            $eventdata->smallmessage      = '';
-                            message_send($eventdata);
-                        }
-                        if (!empty($CFG->enrol_mailadmins)) {
-                            $a = new stdClass;
-                            $a->course = "$course->fullname";
-                            $a->user = fullname($USER);
-                            $admins = get_admins();
-                            foreach ($admins as $admin) {
-                                $eventdata = new object();
-                                $eventdata->modulename  = 'moodle';
-                                $eventdata->userfrom    = $USER;
-                                $eventdata->userto      = $admin;
-                                $eventdata->subject     = get_string("enrolmentnew", '', format_string($course->shortname));
-                                $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
-                                $eventdata->fullmessageformat = FORMAT_PLAIN;
-                                $eventdata->fullmessagehtml   = '';
-                                $eventdata->smallmessage      = '';
-                                message_send($eventdata);
-                            }
-                        }
-                    }
-                    else
-                    {
-                        message_to_admin("Error while trying to enrol " . fullname($USER) . " in '$course->fullname'", $order);
-                    }
-
-                    load_all_capabilities();
-
-                    echo $OUTPUT->box_start('generalbox notice');
-                    echo '<p>'. get_string('paymentthanks', 'moodle', $course->fullname) .'</p>';
-                    echo $OUTPUT->container_start('buttons');
-                    echo $OUTPUT->single_button(new moodle_url("$CFG->wwwroot/enrol/authorize/index.php", array('order'=>$order->id)), get_string('payments'));
-                    echo $OUTPUT->single_button(new moodle_url("$CFG->wwwroot/course/view.php", array('id'=>$course->id)), $course->fullname);
-                    echo $OUTPUT->container_end();
-                    echo $OUTPUT->box_end();
-                    echo $OUTPUT->footer();
-                    exit; // break;
-                }
-            }
-            return NULL;
-        }
-        else
-        {
-            message_to_admin($message, $order);
-            return $message;
-        }
-    }
-
-
-    /**
-     * The user submitted echeck form.
-     *
-     * @param object $form Form parameters
-     * @param object $course Course info
-     * @return string NULL if ok, error message otherwise.
-     * @access private
-     */
-    private function echeck_submit($form, $course)
-    {
-        global $CFG, $USER, $SESSION, $DB;
-
-        prevent_double_paid($course);
-
-        $useripno = getremoteaddr();
-        $curcost = get_course_cost($course);
-        $isbusinesschecking = ($form->acctype == 'BUSINESSCHECKING');
-
-        // NEW ECHECK ORDER
-        $timenow = time();
-        $order = new stdClass();
-        $order->paymentmethod = AN_METHOD_ECHECK;
-        $order->refundinfo = $isbusinesschecking ? 1 : 0;
-        $order->ccname = $form->firstname . ' ' . $form->lastname;
-        $order->courseid = $course->id;
-        $order->userid = $USER->id;
-        $order->status = AN_STATUS_NONE; // it will be changed...
-        $order->settletime = 0; // cron changes this.
-        $order->transid = 0; // Transaction Id
-        $order->timecreated = $timenow;
-        $order->amount = $curcost['cost'];
-        $order->currency = $curcost['currency'];
-        $order->id = $DB->insert_record("enrol_authorize", $order);
-        if (!$order->id) {
-            message_to_admin("Error while trying to insert new data", $order);
-            return "Insert record error. Admin has been notified!";
-        }
-
-        $extra = new stdClass();
-        $extra->x_bank_aba_code = $form->abacode;
-        $extra->x_bank_acct_num = $form->accnum;
-        $extra->x_bank_acct_type = $form->acctype;
-        $extra->x_echeck_type = $isbusinesschecking ? 'CCD' : 'WEB';
-        $extra->x_bank_name = $form->bankname;
-        $extra->x_currency_code = $curcost['currency'];
-        $extra->x_amount = $curcost['cost'];
-        $extra->x_first_name = $form->firstname;
-        $extra->x_last_name = $form->lastname;
-        $extra->x_country = $USER->country;
-        $extra->x_address = $USER->address;
-        $extra->x_city = $USER->city;
-        $extra->x_state = '';
-        $extra->x_zip = '';
-
-        $extra->x_invoice_num = $order->id;
-        $extra->x_description = $course->shortname;
-
-        $extra->x_cust_id = $USER->id;
-        $extra->x_email = $USER->email;
-        $extra->x_customer_ip = $useripno;
-        $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE';
-        $extra->x_phone = '';
-        $extra->x_fax = '';
-
-        $message = '';
-        if (AN_REVIEW == AuthorizeNet::process($order, $message, $extra, AN_ACTION_AUTH_CAPTURE)) {
-            $SESSION->ccpaid = 1; // security check: don't duplicate payment
-            redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
-            return NULL;
-        }
-        else {
-            message_to_admin($message, $order);
-            return $message;
-        }
-    }
-
-
-    /**
-     * Gets access icons.
-     *
-     * @param object $course
-     * @return string
-     * @access public
-     */
-    public function get_access_icons($course)
-    {
-        $manual = enrolment_factory::factory('manual');
-        $str = $manual->get_access_icons($course);
-        $curcost = get_course_cost($course);
-
-        if (abs($curcost['cost']) > 0.00) {
-            $strrequirespayment = get_string("requirespayment");
-            $strcost = get_string("cost");
-            $currency = $curcost['currency'];
-
-            switch ($currency) {
-                case 'USD': $currency = 'US$'; break;
-                case 'CAD': $currency = 'C$'; break;
-                case 'EUR': $currency = '&euro;'; break;
-                case 'GBP': $currency = '&pound;'; break;
-                case 'JPY': $currency = '&yen;'; break;
-            }
-
-            $str .= '<div class="cost" title="'.$strrequirespayment.'">'.$strcost.': ';
-            $str .= $currency . ' ' . $curcost['cost'].'</div>';
-        }
-
-        return $str;
-    }
-
-
-    /**
-     * Shows config form & errors
-     *
-     * @param object $frm
-     * @access public
-     */
-    public function config_form($frm) {
-        global $CFG, $DB, $OUTPUT;
-        $mconfig = get_config('enrol/authorize');
-
-        if (!check_curl_available()) {
-            echo $OUTPUT->notification('PHP must be compiled with cURL+SSL support (--with-curl --with-openssl)');
-        }
-
-        if (empty($CFG->loginhttps) and substr($CFG->wwwroot, 0, 5) !== 'https') {
-            $a = new stdClass;
-            $a->url = "$CFG->wwwroot/$CFG->admin/settings.php?section=httpsecurity";
-            echo $OUTPUT->notification(get_string('adminconfighttps', 'enrol_authorize', $a));
-            return; // notice breaks the form and xhtml later
-        }
-        elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
-            $wwwsroot = qualified_me();
-            $wwwsroot = str_replace('http:', 'https:', $wwwsroot);
-            $a = new stdClass;
-            $a->url = $wwwsroot;
-            echo $OUTPUT->notification(get_string('adminconfighttpsgo', 'enrol_authorize', $a));
-            return; // notice breaks the form and xhtml later
-        }
-
-        if (optional_param('verifyaccount', 0, PARAM_INT)) {
-            echo $OUTPUT->notification(authorize_verify_account());
-        }
-
-        if (!empty($frm->an_review)) {
-            $captureday = intval($frm->an_capture_day);
-            $emailexpired = intval($frm->an_emailexpired);
-            if ($captureday > 0 || $emailexpired > 0) {
-                $lastcron = $DB->get_field_sql('SELECT max(lastcron) FROM {modules}');
-                if ((time() - intval($lastcron) > 3600 * 24)) {
-                    echo $OUTPUT->notification(get_string('admincronsetup', 'enrol_authorize'));
-                }
-            }
-        }
-
-        if (($count = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH)))) {
-            $a = new stdClass;
-            $a->count = $count;
-            $a->url = $CFG->wwwroot."/enrol/authorize/index.php?status=".AN_STATUS_AUTH;
-            echo $OUTPUT->notification(get_string('adminpendingorders', 'enrol_authorize', $a));
-        }
-
-        if (data_submitted()) {
-            if (empty($mconfig->an_login)) {
-                echo $OUTPUT->notification("an_login required");
-            }
-            if (empty($mconfig->an_tran_key) && empty($mconfig->an_password)) {
-                echo $OUTPUT->notification("an_tran_key or an_password required");
-            }
-        }
-
-        include($CFG->dirroot.'/enrol/authorize/config_form.php');
-    }
-
-
-    /**
-     * process_config
-     *
-     * @param object $config
-     * @return bool true if it will be saved.
-     * @access public
-     */
-    public function process_config($config)
-    {
-        global $CFG, $DB;
-        $mconfig = get_config('enrol/authorize');
-
-        // site settings
-        if (($cost = optional_param('enrol_cost', 5, PARAM_INT)) > 0) {
-            set_config('enrol_cost', $cost);
-        }
-        set_config('enrol_currency', optional_param('enrol_currency', 'USD', PARAM_ALPHA));
-        set_config('enrol_mailstudents', optional_param('enrol_mailstudents', 0, PARAM_BOOL));
-        set_config('enrol_mailteachers', optional_param('enrol_mailteachers', 0, PARAM_BOOL));
-        set_config('enrol_mailadmins', optional_param('enrol_mailadmins', 0, PARAM_BOOL));
-
-        // optional authorize.net settings
-        set_config('an_avs', optional_param('an_avs', 0, PARAM_BOOL));
-        set_config('an_authcode', optional_param('an_authcode', 0, PARAM_BOOL));
-        set_config('an_test', optional_param('an_test', 0, PARAM_BOOL));
-        set_config('an_referer', optional_param('an_referer', 'http://', PARAM_URL));
-
-        $acceptmethods = optional_param('acceptmethods', get_list_of_payment_methods(), PARAM_ALPHA);
-        set_config('an_acceptmethods', implode(',', $acceptmethods));
-        $acceptccs = optional_param('acceptccs', array_keys(get_list_of_creditcards()), PARAM_ALPHA);
-        set_config('an_acceptccs', implode(',', $acceptccs));
-        $acceptechecktypes = optional_param('acceptechecktypes', get_list_of_bank_account_types(), PARAM_ALPHA);
-        set_config('an_acceptechecktypes', implode(',', $acceptechecktypes));
-
-        $cutoff_hour = optional_param('an_cutoff_hour', 0, PARAM_INT);
-        $cutoff_min = optional_param('an_cutoff_min', 5, PARAM_INT);
-        set_config('an_cutoff', $cutoff_hour * 60 + $cutoff_min);
-
-        // cron depencies
-        $reviewval = optional_param('an_review', 0, PARAM_BOOL);
-        $captureday = optional_param('an_capture_day', 5, PARAM_INT);
-        $emailexpired = optional_param('an_emailexpired', 2, PARAM_INT);
-        $emailexpiredteacher = optional_param('an_emailexpiredteacher', 0, PARAM_BOOL);
-        $sorttype = optional_param('an_sorttype', 'ttl', PARAM_ALPHA);
-
-        $captureday = ($captureday > 29) ? 29 : (($captureday < 0) ? 0 : $captureday);
-        $emailexpired = ($emailexpired > 5) ? 5 : (($emailexpired < 0) ? 0 : $emailexpired);
-
-        if (!empty($reviewval) && ($captureday > 0 || $emailexpired > 0)) {
-            $lastcron = $DB->get_field_sql('SELECT max(lastcron) FROM {modules}');
-            if (time() - intval($lastcron) > 3600 * 24) {
-                return false;
-            }
-        }
-
-        set_config('an_review', $reviewval);
-        set_config('an_capture_day', $captureday);
-        set_config('an_emailexpired', $emailexpired);
-        set_config('an_emailexpiredteacher', $emailexpiredteacher);
-        set_config('an_sorttype', $sorttype);
-
-        // https and openssl library is required
-        if ((substr($CFG->wwwroot, 0, 5) !== 'https' and empty($CFG->loginhttps)) or !check_curl_available()) {
-            return false;
-        }
-
-        // REQUIRED fields;
-        // an_login
-        $loginval = optional_param('an_login', '', PARAM_RAW);
-        if (empty($loginval) && empty($mconfig->an_login)) {
-            return false;
-        }
-        $loginval = !empty($loginval) ? rc4encrypt($loginval) : strval($mconfig->an_login);
-        set_config('an_login', $loginval, 'enrol/authorize');
-
-        // an_tran_key, an_password
-        $tranval = optional_param('an_tran_key', '', PARAM_RAW);
-        $tranval = !empty($tranval) ? rc4encrypt($tranval) : (isset($mconfig->an_tran_key)?$mconfig->an_tran_key:'');
-        $passwordval = optional_param('an_password', '', PARAM_RAW);
-        $passwordval = !empty($passwordval) ? rc4encrypt($passwordval) :(isset($mconfig->an_password)?$mconfig->an_password:'');
-        $deletecurrent = optional_param('delete_current', '0', PARAM_BOOL);
-        if (!empty($deletecurrent) and !empty($tranval)) {
-            unset_config('an_password', 'enrol/authorize');
-            $passwordval = '';
-        }
-        elseif (!empty($passwordval)) {
-            set_config('an_password', $passwordval, 'enrol/authorize');
-        }
-        if (empty($tranval) and empty($passwordval)) {
-            return false;
-        }
-        if (!empty($tranval)) {
-            set_config('an_tran_key', $tranval, 'enrol/authorize');
-        }
-
-        return true;
-    }
-
-    /**
-     * 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));
-                // TODO: do some real enrolment here
-                if (role_assign($role->id, $user->id, $context->id, 'enrol_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      = '';
-            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      = '';
-            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");
-        }
-    }
-
-    /**
-     * Daily cron. It executes at settlement time (default is 00:05).
-     *
-     * @access private
-     */
-    private function cron_daily()
-    {
-        global $CFG, $SITE, $DB;
-
-        $oneday = 86400;
-        $timenow = time();
-        $onepass = $timenow - $oneday;
-        $settlementtime = AuthorizeNet::getsettletime($timenow);
-        $timediff30 = $settlementtime - (30 * $oneday);
-
-        $select = "(status=?) AND (timecreated<?)";
-        $params = array(AN_STATUS_NONE, $timediff30);
-        if ($DB->delete_records_select('enrol_authorize', $select, $params)) {
-            mtrace("        orders no transaction made have deleted");
-        }
-
-        $select = "(status=?) AND (timecreated<?)";
-        $params = array(AN_STATUS_EXPIRE, AN_STATUS_AUTH, $timediff30);
-        if ($DB->execute("UPDATE {enrol_authorize} SET status=? WHERE $select", $params)) {
-            mtrace("        pending orders to expire have updated");
-        }
-
-        $timediff60 = $settlementtime - (60 * $oneday);
-        $select = "(status=?) AND (timecreated<?)";
-        $params = array(AN_STATUS_EXPIRE, $timediff60);
-        if ($DB->delete_records_select('enrol_authorize', $select, $params)) {
-            mtrace("        orders expired older than 60 days have deleted");
-        }
-
-        $adminuser = get_admin();
-        $select = "status IN(?,?) AND (timecreated<?) AND (timecreated>?)";
-        $params = array(AN_STATUS_UNDERREVIEW, AN_STATUS_APPROVEDREVIEW, $onepass, $timediff60);
-        if (($count = $DB->count_records_select('enrol_authorize', $select, $params)) &&
-            ($csvusers = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), 'enrol/authorize:uploadcsv'))) {
-            $a = new stdClass;
-            $a->count = $count;
-            $a->course = $SITE->shortname;
-            $subject = get_string('pendingechecksubject', 'enrol_authorize', $a);
-            $a = new stdClass;
-            $a->count = $count;
-            $a->url = $CFG->wwwroot.'/enrol/authorize/uploadcsv.php';
-            $message = get_string('pendingecheckemail', 'enrol_authorize', $a);
-            foreach($csvusers as $csvuser) {
-                $eventdata = new object();
-                $eventdata->modulename        = 'moodle';
-                $eventdata->userfrom          = $adminuser;
-                $eventdata->userto            = $csvuser;
-                $eventdata->subject           = $subject;
-                $eventdata->fullmessage       = $message;
-                $eventdata->fullmessageformat = FORMAT_PLAIN;
-                $eventdata->fullmessagehtml   = '';
-                $eventdata->smallmessage      = '';
-                message_send($eventdata);
-            }
-            mtrace("        users who have 'enrol/authorize:uploadcsv' were mailed");
-        }
-
-        mtrace("        early pending order warning email for manual capture", ": ");
-        if (empty($CFG->an_emailexpired)) {
-            mtrace("not enabled");
-            return;
-        }
-
-
-        $timediffem = $settlementtime - ((30 - intval($CFG->an_emailexpired)) * $oneday);
-        $select = "(status=?) AND (timecreated<?) AND (timecreated>?)";
-        $params = array(AN_STATUS_AUTH, $timediffem, $timediff30);
-        $count = $DB->count_records_select('enrol_authorize', $select, $params);
-        if (!$count) {
-            mtrace("no orders prior to $CFG->an_emailexpired days");
-            return;
-        }
-
-        mtrace("$count orders prior to $CFG->an_emailexpired days");
-        $a = new stdClass;
-        $a->pending = $count;
-        $a->days = $CFG->an_emailexpired;
-        $a->course = $SITE->shortname;
-        $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
-        $a = new stdClass;
-        $a->pending = $count;
-        $a->days = $CFG->an_emailexpired;
-        $a->course = $SITE->fullname;
-        $a->enrolurl = "$CFG->wwwroot/$CFG->admin/enrol_config.php?enrol=authorize";
-        $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?status='.AN_STATUS_AUTH;
-        $message = get_string('pendingordersemail', 'enrol_authorize', $a);
-
-        $eventdata = new object();
-        $eventdata->modulename        = 'moodle';
-        $eventdata->userfrom          = $adminuser;
-        $eventdata->userto            = $adminuser;
-        $eventdata->subject           = $subject;
-        $eventdata->fullmessage       = $message;
-        $eventdata->fullmessageformat = FORMAT_PLAIN;
-        $eventdata->fullmessagehtml   = '';
-        $eventdata->smallmessage      = '';
-        message_send($eventdata);
-
-        // Email to payment managers
-        if (empty($CFG->an_emailexpiredteacher)) {
-            return; // email feature disabled for teachers.
-        }
-
-        $sorttype = empty($CFG->an_sorttype) ? 'ttl' : $CFG->an_sorttype;
-        $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,
-                  COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl
-                FROM {enrol_authorize} e
-                  INNER JOIN {course} c ON c.id = e.courseid
-                WHERE (e.status = ?)
-                  AND (e.timecreated < ?)
-                  AND (e.timecreated > ?)
-                GROUP BY e.courseid
-                ORDER BY $sorttype DESC";
-        $params = array(AN_STATUS_AUTH, $timediffem, $timediff30);
-
-        $rs = $DB->get_recordset_sql($sql, $params);
-        foreach ($rs as $courseinfo)
-        {
-            $lastcourse = $courseinfo->courseid;
-            $context = get_context_instance(CONTEXT_COURSE, $lastcourse);
-            if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
-                $a = new stdClass;
-                $a->course = $courseinfo->shortname;
-                $a->pending = $courseinfo->cnt;
-                $a->days = $CFG->an_emailexpired;
-                $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
-                $a = new stdClass;
-                $a->course = $courseinfo->fullname;
-                $a->pending = $courseinfo->cnt;
-                $a->currency = $courseinfo->currency;
-                $a->sumcost = $courseinfo->ttl;
-                $a->days = $CFG->an_emailexpired;
-                $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?course='.$lastcourse.'&amp;status='.AN_STATUS_AUTH;
-                $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a);
-                foreach ($paymentmanagers as $paymentmanager) {
-                    $eventdata = new object();
-                    $eventdata->modulename        = 'moodle';
-                    $eventdata->userfrom          = $adminuser;
-                    $eventdata->userto            = $paymentmanager;
-                    $eventdata->subject           = $subject;
-                    $eventdata->fullmessage       = $message;
-                    $eventdata->fullmessageformat = FORMAT_PLAIN;
-                    $eventdata->fullmessagehtml   = '';
-                    $eventdata->smallmessage      = '';
-                    message_send($eventdata);
-                }
-            }
-        }
-        $rs->close();
-    }
-}
-
diff --git a/enrol/authorize/enrol_form.php b/enrol/authorize/enrol_form.php
index 9edf255..e30ea09 100755
--- a/enrol/authorize/enrol_form.php
+++ b/enrol/authorize/enrol_form.php
@@ -1,16 +1,44 @@
 <?php
 
-if (!defined('MOODLE_INTERNAL')) {
-    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
-}
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize.Net enrol plugin implementation.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
 
 require_once($CFG->libdir.'/formslib.php');
 
 class enrol_authorize_form extends moodleform
 {
-    function definition()
-    {
-        global $CFG, $USER;
+    protected $instance;
+
+    function definition() {
+        global $USER;
+
+        $mform = $this->_form;
+        $this->instance = $this->_customdata;
+        $plugin = enrol_get_plugin('authorize');
 
         $paymentmethodsenabled = get_list_of_payment_methods();
         $paymentmethod = optional_param('paymentmethod', $paymentmethodsenabled[0], PARAM_ALPHA);
@@ -18,30 +46,27 @@ class enrol_authorize_form extends moodleform
             print_error('invalidpaymentmethod', '', '', $paymentmethod);
         }
 
-        $mform =& $this->_form;
-        $course = $this->_customdata['course'];
-
-        $mform->addElement('header', 'general', get_string('paymentrequired'));
         $othermethodstr = $this->other_method_available($paymentmethod);
         if ($othermethodstr) {
             $mform->addElement('static', '', '<div class="mdl-right">' . $othermethodstr . '</div>', '');
         }
 
-        $mform->addElement('hidden', 'id', $course->id);
+        $mform->addElement('hidden', 'id');
         $mform->setType('id', PARAM_INT);
+        $mform->setDefault('id', $this->instance->courseid);
+
+        $mform->addElement('hidden', 'instanceid');
+        $mform->setType('instanceid', PARAM_INT);
+        $mform->setDefault('instanceid', $this->instance->id);
 
         $mform->addElement('hidden', 'paymentmethod', $paymentmethod);
         $mform->setType('paymentmethod', PARAM_ALPHA);
 
         $firstlastnamestr = (AN_METHOD_CC == $paymentmethod) ? get_string('nameoncard', 'enrol_authorize') : get_string('echeckfirslasttname', 'enrol_authorize');
-        $firstlastnamegrp = array();
-        $firstlastnamegrp[] = &$mform->createElement('text', 'firstname', '', 'size="16"');
-        $firstlastnamegrp[] = &$mform->createElement('text', 'lastname', '', 'size="16"');
-        $mform->addGroup($firstlastnamegrp, 'firstlastgrp', $firstlastnamestr, '&nbsp;', false);
-        $firstlastnamegrprules = array();
-        $firstlastnamegrprules['firstname'][] = array(get_string('missingfirstname'), 'required', null, 'client');
-        $firstlastnamegrprules['lastname'][] = array(get_string('missinglastname'), 'required', null, 'client');
-        $mform->addGroupRule('firstlastgrp', $firstlastnamegrprules);
+        $mform->addElement('text', 'firstname', get_string('firstnameoncard', 'enrol_authorize'), 'size="16"');
+        $mform->addElement('text', 'lastname', get_string('lastnameoncard', 'enrol_authorize'), 'size="16"');
+        $mform->addRule('firstname', get_string('missingfirstname'), 'required', null, 'client');
+        $mform->addRule('lastname', get_string('missinglastname'), 'required', null, 'client');
         $mform->setType('firstname', PARAM_ALPHANUM);
         $mform->setType('lastname', PARAM_ALPHANUM);
         $mform->setDefault('firstname', $USER->firstname);
@@ -66,14 +91,10 @@ class enrol_authorize_form extends moodleform
             for ($i = $startyear; $i < $endyear; $i++) {
                 $yearsmenu[$i] = $i;
             }
-            $ccexpiregrp = array();
-            $ccexpiregrp[] = &$mform->createElement('select', 'ccexpiremm', '', $monthsmenu);
-            $ccexpiregrp[] = &$mform->createElement('select', 'ccexpireyyyy', '', $yearsmenu);
-            $mform->addGroup($ccexpiregrp, 'ccexpiregrp', get_string('ccexpire', 'enrol_authorize'), '&nbsp;', false);
-            $ccexpiregrprules = array();
-            $ccexpiregrprules['ccexpiremm'][] = array(get_string('missingccexpire', 'enrol_authorize'), 'required', null, 'client');
-            $ccexpiregrprules['ccexpireyyyy'][] = array(get_string('missingccexpire', 'enrol_authorize'), 'required', null, 'client');
-            $mform->addGroupRule('ccexpiregrp', $ccexpiregrprules);
+            $mform->addElement('select', 'ccexpiremm', get_string('expiremonth', 'enrol_authorize'), $monthsmenu);
+            $mform->addElement('select', 'ccexpireyyyy', get_string('expireyear', 'enrol_authorize'), $yearsmenu);
+            $mform->addRule('ccexpiremm', get_string('missingccexpiremonth', 'enrol_authorize'), 'required', null, 'client');
+            $mform->addRule('ccexpireyyyy', get_string('missingccexpireyear', 'enrol_authorize'), 'required', null, 'client');
             $mform->setType('ccexpiremm', PARAM_INT);
             $mform->setType('ccexpireyyyy', PARAM_INT);
             $mform->setDefault('ccexpiremm', '');
@@ -91,7 +112,7 @@ class enrol_authorize_form extends moodleform
             $mform->addRule('cvv', get_string('missingcvv', 'enrol_authorize'), 'required', null, 'client');
             $mform->addRule('cvv', get_string('missingcvv', 'enrol_authorize'), 'numeric', null, 'client');
 
-            if (!empty($CFG->an_authcode)) {
+            if ($plugin->get_config('an_authcode')) {
                 $ccauthgrp = array();
                 $ccauthgrp[] = &$mform->createElement('checkbox', 'haveauth', null, get_string('haveauthcode', 'enrol_authorize'));
                 $ccauthgrp[] = &$mform->createElement('static', 'nextline', null, '<br />');
@@ -105,7 +126,7 @@ class enrol_authorize_form extends moodleform
                 $mform->setDefault('ccauthcode', '');
             }
 
-            if (!empty($CFG->an_avs)) {
+            if ($plugin->get_config('an_avs')) {
                 $mform->addElement('header', '', '&nbsp;&nbsp;' . get_string('address'), '');
 
                 $mform->addElement('text', 'ccaddress', get_string('address'), 'size="30"');
@@ -113,14 +134,9 @@ class enrol_authorize_form extends moodleform
                 $mform->setDefault('ccaddress', $USER->address);
                 $mform->addRule('ccaddress', get_string('missingaddress', 'enrol_authorize'), 'required', null, 'client');
 
-                $citystategrp = array();
-                $citystategrp[] = &$mform->createElement('text', 'cccity', '', 'size="14"');
-                $citystategrp[] = &$mform->createElement('static', 'sep', null, ' - ');
-                $citystategrp[] = &$mform->createElement('text', 'ccstate', '', 'size="8"');
-                $mform->addGroup($citystategrp, 'citystategrp', get_string('city') . ' - ' . get_string('state'), '&nbsp;', false);
-                $citystategrprules = array();
-                $citystategrprules['cccity'][] = array(get_string('missingcity'), 'required', null, 'client');
-                $mform->addGroupRule('citystategrp', $citystategrprules);
+                $mform->addElement('text', 'cccity', get_string('cccity', 'enrol_authorize'), 'size="14"');
+                $mform->addElement('text', 'ccstate', get_string('ccstate', 'enrol_authorize'), 'size="8"');
+                $mform->addRule('cccity', get_string('missingcity'), 'required', null, 'client');
                 $mform->setType('cccity', PARAM_ALPHANUM);
                 $mform->setType('ccstate', PARAM_ALPHANUM);
                 $mform->setDefault('cccity', $USER->city);
@@ -142,9 +158,7 @@ class enrol_authorize_form extends moodleform
                 $mform->setType('ccountry', PARAM_ALPHA);
                 $mform->setDefault('cccountry', $USER->country);
             }
-        }
-        elseif (AN_METHOD_ECHECK == $paymentmethod)
-        {
+        } elseif (AN_METHOD_ECHECK == $paymentmethod) {
             $mform->addElement('text', 'abacode', get_string('echeckabacode', 'enrol_authorize'), 'size="9" maxlength="9"');
             $mform->setType('abacode', PARAM_ALPHANUM);
             $mform->setDefault('abacode', '');
@@ -182,10 +196,9 @@ class enrol_authorize_form extends moodleform
         $this->add_action_buttons(false, get_string('sendpaymentbutton', 'enrol_authorize'));
     }
 
-    function validation($data, $files)
-    {
-        global $CFG;
+    function validation($data, $files) {
         $errors = parent::validation($data, $files);
+        $plugin = enrol_get_plugin('authorize');
 
         if (AN_METHOD_CC == $data['paymentmethod'])
         {
@@ -197,14 +210,14 @@ class enrol_authorize_form extends moodleform
             $validcc = $this->validate_cc($data['cc'], $data['cctype'], $expdate);
             if (!$validcc) {
                 if ($validcc === 0) {
-                    $errors['ccexpiregrp'] = get_string('ccexpired', 'enrol_authorize');
+                    $errors['ccexpiremm'] = get_string('ccexpired', 'enrol_authorize');
                 }
                 else {
                     $errors['cc'] = get_string('ccinvalid', 'enrol_authorize');
                 }
             }
 
-            if (!empty($CFG->an_authcode) && !empty($data['haveauth']) && empty($data['ccauthcode'])) {
+            if ($plugin->get_config('an_authcode') && !empty($data['haveauth']) && empty($data['ccauthcode'])) {
                 $errors['ccauthgrp'] = get_string('missingccauthcode', 'enrol_authorize');
             }
         }
@@ -224,16 +237,14 @@ class enrol_authorize_form extends moodleform
 
     private function other_method_available($currentmethod)
     {
-        $course = $this->_customdata['course'];
 
         if ($currentmethod == AN_METHOD_CC) {
             $otheravailable = in_array(AN_METHOD_ECHECK, get_list_of_payment_methods());
-            $url = 'enrol.php?id='.$course->id.'&amp;paymentmethod='.AN_METHOD_ECHECK;
+            $url = 'index.php?id='.$this->instance->courseid.'&amp;paymentmethod='.AN_METHOD_ECHECK;
             $stringtofetch = 'usingecheckmethod';
-        }
-        else {
+        } else {
             $otheravailable = in_array(AN_METHOD_CC, get_list_of_payment_methods());
-            $url = 'enrol.php?id='.$course->id.'&amp;paymentmethod='.AN_METHOD_CC;
+            $url = 'index.php?id='.$this->instance->courseid.'&amp;paymentmethod='.AN_METHOD_CC;
             $stringtofetch = 'usingccmethod';
         }
         if ($otheravailable) {
diff --git a/enrol/authorize/import_form.php b/enrol/authorize/import_form.php
index c43123f..3af46d4 100644
--- a/enrol/authorize/import_form.php
+++ b/enrol/authorize/import_form.php
@@ -15,6 +15,18 @@
 // You should have received a copy of the GNU General Public License
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
+/**
+ * Adds new instance of enrol_authorize to specified course
+ * or edits current instance.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
 require_once($CFG->libdir.'/formslib.php');
 
 class enrol_authorize_import_form extends moodleform {
diff --git a/enrol/authorize/index.php b/enrol/authorize/index.php
index 3fd83a8..5bdee18 100644
--- a/enrol/authorize/index.php
+++ b/enrol/authorize/index.php
@@ -1,5 +1,32 @@
 <?php
 
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Adds new instance of enrol_authorize to specified course
+ * or edits current instance.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
 /// Load libraries
     require_once('../../config.php');
     require_once('const.php');
diff --git a/enrol/authorize/lang/en/enrol_authorize.php b/enrol/authorize/lang/en/enrol_authorize.php
index 24e3821..9b9dd18 100644
--- a/enrol/authorize/lang/en/enrol_authorize.php
+++ b/enrol/authorize/lang/en/enrol_authorize.php
@@ -23,22 +23,32 @@
  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
+$string['authorize:config'] = 'Configure Authorize.Net enrol instances';
+$string['authorize:manage'] = 'Manage enrolled users';
+$string['authorize:unenrol'] = 'Unenrol users from course';
+$string['authorize:unenrolself'] = 'Unenrol self from the course';
+$string['authorize:managepayments'] = 'Manage payments';
+$string['authorize:uploadcsv'] = 'Upload CSV file';
 $string['adminacceptccs'] = 'Which credit card types will be accepted?';
 $string['adminaccepts'] = 'Select payment methods allowed and their types';
-$string['adminauthcode'] = 'If an user\'s credit card cannot be captured on the internet directly, obtain authorization code over the phone from customer\'s bank.';
+$string['anauthcode'] = 'Obtain authcode';
+$string['anauthcodedesc'] = 'If a user\'s credit card cannot be captured on the internet directly, obtain authorization code over the phone from customer\'s bank.';
 $string['adminauthorizeccapture'] = 'Order Review &amp; Scheduled-Capture Settings';
 $string['adminauthorizeemail'] = 'Email Sending Settings';
-$string['adminauthorizesettings'] = 'Authorize.net Merchant Account Settings';
+$string['adminauthorizesettings'] = 'Authorize.Net Merchant Account Settings';
 $string['adminauthorizewide'] = 'General Settings';
-$string['adminavs'] = 'Check this if you have activated Address Verification System (AVS) in your authorize.net merchant account. This demands address fields like street, state, country and zip when user fills out payment form.';
+$string['anavs'] = 'Address Verification System';
+$string['anavsdesc'] = 'Check this if you have activated Address Verification System (AVS) in your authorize.Net merchant account. This demands address fields like street, state, country and zip when user fills out payment form.';
 $string['adminconfighttps'] = 'Please ensure that you have "<a href="{$a->url}">turned loginhttps ON</a>" to use this plugin<br />in Admin >> Variables >> Security >> HTTP security.';
 $string['adminconfighttpsgo'] = 'Go to the <a href="{$a->url}">secure page</a> to configure this plugin.';
-$string['admincronsetup'] = 'The cron.php maintenance script has not been run for at least 24 hours.<br />Cron must be enabled if you want to use scheduled-capture feature.<br /><b>Enable</b> \'Authorize.net plugin\' and <b>setup cron</b> properly; or <b>uncheck an_review</b> again.<br />If you disable scheduled-capture, transactions will be cancelled unless you review them within 30 days.<br />Check <b>an_review</b> and enter <b>\'0\' to an_capture_day</b> field<br />if you want to <b>manually</b> accept/deny payments within 30 days.';
-$string['adminemailexpired'] = 'This is useful for \'Manual-Capture\'. Admins are notified <b>{$a}</b> days prior to pending orders expiring.';
+$string['admincronsetup'] = 'The cron.php maintenance script has not been run for at least 24 hours.<br />Cron must be enabled if you want to use scheduled-capture feature.<br /><b>Enable</b> \'Authorize.Net plugin\' and <b>setup cron</b> properly; or <b>uncheck an_review</b> again.<br />If you disable scheduled-capture, transactions will be cancelled unless you review them within 30 days.<br />Check <b>an_review</b> and enter <b>\'0\' to an_capture_day</b> field<br />if you want to <b>manually</b> accept/deny payments within 30 days.';
+$string['anemailexpired'] = 'Expiry notification';
+$string['anemailexpireddesc'] = 'This is useful for \'Manual-Capture\'. Admins are notified the specified amount of days prior to pending orders expiring.';
 $string['adminemailexpiredsort'] = 'When the number of pending orders expiring are sent to the teachers via email, which one is important?';
 $string['adminemailexpiredsortcount'] = 'Order count';
 $string['adminemailexpiredsortsum'] = 'Total amount';
-$string['adminemailexpiredteacher'] = 'If you have enabled manual-capture (see above) and teachers can manage the payments, they may also notified about pending orders expiring. This will send an email to each course teachers about the count of the pending orders to expire.';
+$string['anemailexpiredteacher'] = 'Expiry notification - Teacher';
+$string['anemailexpiredteacherdesc'] = 'If you have enabled manual-capture (see above) and teachers can manage the payments, they may also notified about pending orders expiring. This will send an email to each course teachers about the count of the pending orders to expire.';
 $string['adminemailexpsetting'] = '(0=disable sending email, default=2, max=5)<br />(Manual capture settings for sending email: cron=enabled, an_review=checked, an_capture_day=0, an_emailexpired=1-5)';
 $string['adminhelpcapturetitle'] = 'Scheduled-Capture Day';
 $string['adminhelpreviewtitle'] = 'Order Review';
@@ -62,22 +72,23 @@ $string['adminneworder'] = 'Dear Admin,
   {$a->url}';
 $string['adminnewordersubject'] = '{$a->course}; New Pending Order: {$a->orderid}';
 $string['adminpendingorders'] = 'You have disabled scheduled-capture feature.<br />Total {$a->count} transactions with the status of \'Authorized/Pending Capture\' are to be cancelled unless you check them.<br />To accept/deny payments, go to <a href=\'{$a->url}\'>Payment Management</a> page.';
-$string['adminreview'] = 'Review order before processing the credit card.';
+$string['anreview'] = 'Review';
+$string['anreviewdesc'] = 'Review order before processing the credit card.';
 $string['adminteachermanagepay'] = 'Teachers can manage the payments of the course.';
 $string['allpendingorders'] = 'All Pending Orders';
 $string['amount'] = 'Amount';
-$string['anlogin'] = 'Authorize.net: Login name';
-$string['anpassword'] = 'Authorize.net: Password';
-$string['anreferer'] = 'Define the URL referer if you have set up this in your authorize.net merchant account. This will send a line "Referer: URL" embedded in the web request.';
-$string['antestmode'] = 'Run transactions in test mode only (no money will be drawn)';
-$string['antrankey'] = 'Authorize.net: Transaction Key';
+$string['anlogin'] = 'Authorize.Net: Login name';
+$string['anpassword'] = 'Authorize.Net: Password';
+$string['anreferer'] = 'Referer';
+$string['anrefererdesc'] = 'Define the URL referer if you have set up this in your authorize.Net merchant account. This will send a line "Referer: URL" embedded in the web request.';
+$string['antestmode'] = 'Test mode';
+$string['antestmodedesc'] = 'Run transactions in test mode only (no money will be drawn)';
+$string['antrankey'] = 'Authorize.Net: Transaction Key';
 $string['approvedreview'] = 'Approved Review';
 $string['authcaptured'] = 'Authorized / Captured';
 $string['authcode'] = 'Authorization Code';
 $string['authorizedpendingcapture'] = 'Authorized / Pending Capture';
-$string['authorizeerror'] = 'Authorize.net Error: {$a}';
-$string['authorize:managepayments'] = 'Manage payments';
-$string['authorize:uploadcsv'] = 'Upload CSV file';
+$string['authorizeerror'] = 'Authorize.Net Error: {$a}';
 $string['avsa'] = 'Address (street) matches, postal code does not';
 $string['avsb'] = 'Address information not provided';
 $string['avse'] = 'Address Verification System Error';
@@ -107,10 +118,11 @@ $string['cctype'] = 'Credit Card Type';
 $string['ccvv'] = 'Card Verification';
 $string['ccvvhelp'] = 'Look at the back of card (last 3 digits)';
 $string['costdefaultdesc'] = '<strong>In course settings, enter -1</strong> to use this default cost to course cost field.';
-$string['cutofftime'] = 'Transaction Cut-Off Time. When the last transaction is picked up for settlement?';
+$string['cutofftime'] = 'Cut-off time';
+$string['cutofftimedesc'] = 'Transaction Cut-Off Time. When the last transaction is picked up for settlement?';
 $string['dataentered'] = 'Data entered';
 $string['delete'] = 'Destroy';
-$string['description'] = 'The Authorize.net module allows you to set up paid courses via payment providers. If the cost for any course is zero, then students are not asked to pay for entry. Two ways to set the course cost (1) a site-wide cost as a default for the whole site or (2) a course setting that you can set for each course individually. The course cost overrides the site cost.<br /><br /><b>Note:</b> If you enter an enrolment key in the course settings, then students will also have the option to enrol using a key. This is useful if you have a mixture of paying and non-paying students.';
+$string['description'] = 'The Authorize.Net module allows you to set up paid courses via payment providers. Two ways to set the course cost (1) a site-wide cost as a default for the whole site or (2) a course setting that you can set for each course individually. The course cost overrides the site cost.';
 $string['echeckabacode'] = 'Bank ABA Number';
 $string['echeckaccnum'] = 'Bank Account Number';
 $string['echeckacctype'] = 'Bank Account Type';
@@ -119,7 +131,7 @@ $string['echeckbusinesschecking'] = 'Business Checking';
 $string['echeckfirslasttname'] = 'Bank Account Owner';
 $string['echeckchecking'] = 'Checking';
 $string['echecksavings'] = 'Savings';
-$string['enrolname'] = 'Authorize.net Payment Gateway';
+$string['enrolname'] = 'Authorize.Net Payment Gateway';
 $string['expired'] = 'Expired';
 $string['haveauthcode'] = 'I have already an authorization code';
 $string['howmuch'] = 'How much?';
@@ -131,15 +143,18 @@ $string['invalidaccnum'] = 'Invalid account number';
 $string['invalidacctype'] = 'Invalid account type';
 $string['isbusinesschecking'] = 'Is business checking?';
 $string['logindesc'] = 'This option must be ON. <br /><br />Please ensure that you have turned <a href="{$a->url}">loginhttps ON</a> in Admin >> Variables >> Security.<br /><br />Turning this on will make Moodle use a secure https connection just for the login and payment pages.';
-$string['logininfo'] = 'Login name, password and transaction key are not shown due to security precautions. There is no need to enter again if you have configured these fields before. You see a green text left of the box if some fields were already configured. If you enter these fields for the first time, the login name (*) is required and you must enter <strong>either</strong> the transaction key (#1) <strong>or</strong> the password (#2) in the appropriate box. We recommend you enter the transaction key due to security precautions. If you want to delete the current password, tick the checkbox.';
+$string['logininfo'] = 'When configuring your Authorize.Net account, the login name is required and you must enter <strong>either</strong> the transaction key <strong>or</strong> the password in the appropriate box. We recommend you enter the transaction key due to security precautions.';
 $string['methodcc'] = 'Credit Card';
+$string['methodccdesc'] = 'Select Credit Card and accepted types below';
 $string['methodecheck'] = 'eCheck (ACH)';
+$string['methodecheckdesc'] = 'Select eCheck and accepted types below';
 $string['missingaba'] = 'Missing ABA number';
 $string['missingaddress'] = 'Missing address';
 $string['missingbankname'] = 'Missing bank name';
 $string['missingcc'] = 'Missing card number';
 $string['missingccauthcode'] = 'Missing authorization code';
-$string['missingccexpire'] = 'Missing expiration date';
+$string['missingccexpiremonth'] = 'Missing expiration month';
+$string['missingccexpireyear'] = 'Missing expiration year';
 $string['missingcctype'] = 'Missing card type';
 $string['missingcvv'] = 'Missing verification number';
 $string['missingzip'] = 'Missing postal code';
@@ -205,7 +220,8 @@ $string['reason56'] = 'This merchant accepts eCheck (ACH) transactions only; no
 $string['refund'] = 'Refund';
 $string['refunded'] = 'Refunded';
 $string['returns'] = 'Returns';
-$string['reviewday'] = 'Capture the credit card automatically unless a teacher or administrator review the order within <b>{$a}</b> days. CRON MUST BE ENABLED.<br />(0 day means it will disable scheduled-capture, also means teacher or admin review order manually. Transaction will be cancelled if you disable scheduled-capture or unless you review it within 30 days.)';
+$string['ancaptureday'] = 'Capture day';
+$string['ancapturedaydesc'] = 'Capture the credit card automatically unless a teacher or administrator review the order within the specified days. CRON MUST BE ENABLED.<br />(0 days means it will disable scheduled-capture, also means teacher or admin review order manually. Transaction will be cancelled if you disable scheduled-capture or unless you review it within 30 days.)';
 $string['reviewfailed'] = 'Review Failed';
 $string['reviewnotify'] = 'Your payment will be reviewed. Expect an email within a few days from your teacher.';
 $string['sendpaymentbutton'] = 'Send Payment';
@@ -222,8 +238,8 @@ $string['unenrolstudent'] = 'Unenrol student?';
 $string['uploadcsv'] = 'Upload a CSV file';
 $string['usingccmethod'] = 'Enrol using <a href="{$a->url}"><strong>Credit Card</strong></a>';
 $string['usingecheckmethod'] = 'Enrol using <a href="{$a->url}"><strong>eCheck</strong></a>';
-$string['verifyaccount'] = 'Verify your authorize.net merchant account';
-$string['verifyaccountresult'] = 'Verification result: {$a}';
+$string['verifyaccount'] = 'Verify your authorize.Net merchant account';
+$string['verifyaccountresult'] = '<b>Verification result:</b> {$a}';
 $string['void'] = 'Void';
 $string['voidyes'] = 'The transaction will be cancelled. Are you sure?';
 $string['welcometocoursesemail'] = 'Dear {$a->name},
@@ -237,3 +253,19 @@ You may view your payment details or edit your profile:
  {$a->profileurl}';
 $string['youcantdo'] = 'You can\'t do this action: {$a->action}';
 $string['zipcode'] = 'Zip Code';
+$string['pluginname'] = 'Authorize';
+$string['cost'] = 'Cost';
+$string['currency'] = 'Currency';
+$string['enrolperiod'] = 'Enrolment period';
+$string['enrolstartdate'] = 'Start date';
+$string['enrolenddate'] = 'End date';
+$string['enrolenddaterror'] = 'Enrolment end date cannot be earlier than start date';
+$string['status'] = 'Allow Autorize.net enrolments';
+$string['nocost'] = 'There is no cost associated with enrolling in this course via Authorize.Net!';
+$string['firstnameoncard'] = 'Firstname on card';
+$string['lastnameoncard'] = 'Lastname on card';
+$string['expiremonth'] = 'Expiry month';
+$string['expireyear'] = 'Expiry year';
+$string['cccity'] = 'City';
+$string['ccstate'] = 'State';
+$string['unenrolselfconfirm'] = 'Do you really want to unenrol yourself from course "{$a}"?';
diff --git a/enrol/authorize/lib.php b/enrol/authorize/lib.php
new file mode 100755
index 0000000..c47d3a8
--- /dev/null
+++ b/enrol/authorize/lib.php
@@ -0,0 +1,803 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize enrolment plugin.
+ *
+ * This plugin allows you to set up paid courses, using authorize.net.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once($CFG->dirroot.'/enrol/authorize/const.php');
+require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
+require_once($CFG->dirroot.'/enrol/authorize/authorizenet.class.php');
+require_once($CFG->libdir.'/eventslib.php');
+
+/**
+ * Authorize.net Payment Gateway plugin
+ */
+class enrol_authorize_plugin extends enrol_plugin {
+     /**
+     * Cron log.
+     *
+     * @var string
+     * @access public
+     */
+    public $log;
+
+    public function roles_protected() {
+        // users wit role assign cap may tweak the roles later
+        return false;
+    }
+
+    public function allow_unenrol(stdClass $instance) {
+        // users with unenrol cap may unenrol other users manually - requires enrol/authorize:unenrol
+        return true;
+    }
+
+    public function allow_manage(stdClass $instance) {
+        // users with manage cap may tweak period and status - requires enrol/authorize:manage
+        return true;
+    }
+
+    public function show_enrolme_link(stdClass $instance) {
+        return ($instance->status == ENROL_INSTANCE_ENABLED);
+    }
+
+    /**
+     * Sets up navigation entries.
+     *
+     * @param object $instance
+     * @return void
+     */
+
+    public function add_course_navigation($instancesnode, stdClass $instance) {
+        if ($instance->enrol !== 'authorize') {
+             throw new coding_exception('Invalid enrol instance type!');
+        }
+
+        $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
+        if (has_capability('enrol/authorize:config', $context)) {
+            $managelink = new moodle_url('/enrol/authorize/edit.php', array('courseid'=>$instance->courseid, 'id'=>$instance->id));
+            $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
+        }
+    }
+
+    /**
+     * Returns edit icons for the page with list of instances
+     * @param stdClass $instance
+     * @return array
+     */
+    public function get_action_icons(stdClass $instance) {
+        global $OUTPUT;
+
+        if ($instance->enrol !== 'authorize') {
+            throw new coding_exception('invalid enrol instance!');
+        }
+        $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
+
+        $icons = array();
+
+        if (has_capability('enrol/authorize:config', $context)) {
+            $editlink = new moodle_url("/enrol/authorize/edit.php", array('courseid'=>$instance->courseid, 'id'=>$instance->id));
+            $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('i/edit', get_string('edit'), 'core', array('class'=>'icon')));
+        }
+
+        return $icons;
+    }
+
+    /**
+     * Returns link to page which may be used to add new instance of enrolment plugin in course.
+     * @param int $courseid
+     * @return moodle_url page url
+     */
+
+    public function get_newinstance_link($courseid) {
+        $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST);
+
+        if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/authorize:config', $context)) {
+            return NULL;
+        }
+
+        // multiple instances supported - different cost for different roles
+        return new moodle_url('/enrol/authorize/edit.php', array('courseid'=>$courseid));
+    }
+
+
+    /**
+     * Presents enrol registration form
+     *
+     * @param stdClass $instance
+     * @return string html text, usually a form in a text box
+     */
+    public function enrol_page_hook(stdClass $instance) {
+        global $CFG, $USER, $OUTPUT, $PAGE, $DB;
+
+
+        if ($DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id))) {
+            return null;
+        }
+
+        if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
+            return null;
+        }
+
+        if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
+            return null;
+        }
+
+        $zerocost = zero_cost($instance);
+        if ($zerocost) { // no cost, other enrolment methods (instances) should be used
+            ob_start();
+            echo '<p>'.get_string('nocost', 'enrol_authorize').'</p>';
+
+            return $OUTPUT->box(ob_get_clean());
+        }
+
+        prevent_double_paid($instance);
+
+        // Check https availability
+        if (empty($CFG->loginhttps) and substr($CFG->wwwroot, 0, 5) !== 'https') {
+            ob_start();
+            echo '<p>'.get_string('httpsrequired', 'enrol_authorize').'</p>';
+            return $OUTPUT->box(ob_get_clean());
+        } elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
+            if (empty($CFG->loginhttps)) {
+                ob_start();
+                echo '<p>'.get_string('httpsrequired', 'enrol_authorize').'</p>';
+
+                return $OUTPUT->box(ob_get_clean());
+            } else {
+                $wwwsroot = str_replace('http:','https:', $CFG->wwwroot);
+                redirect("{$wwwsroot}/enrol/index.php?id=$instance->courseid");
+                exit;
+            }
+        }
+
+        $course = $DB->get_record('course', array('id'=>$instance->courseid));
+
+        $strcourses = get_string('courses');
+        $strloginto = get_string('loginto', '', $course->shortname);
+
+        if ($USER->username == 'guest') { // only real guest user, not for users with guest role
+            ob_start();
+            $curcost = get_course_cost($instance);
+            echo '<div class="mdl-align">';
+            echo '<p>'.get_string('paymentrequired').'</p>';
+            echo '<p><b>'.get_string('cost').": {$curcost['currency']} {$curcost['cost']}".'</b></p>';
+            echo '<p><a href="'.$CFG->httpswwwroot.'/login/">'.get_string('loginsite').'</a></p>';
+            echo '</div>';
+
+            return $OUTPUT->box(ob_get_clean());
+        } else {
+            require_once($CFG->dirroot.'/enrol/authorize/enrol_form.php');
+            $form = new enrol_authorize_form(NULL, $instance);
+            if ($data = $form->get_data()) {
+                $authmessage = '';
+                switch ($data->paymentmethod) {
+                    case AN_METHOD_CC:
+                        $authmessage = $this->cc_submit($data, $course, $instance);
+                        break;
+
+                    case AN_METHOD_ECHECK:
+                        $authmessage = $this->echeck_submit($data, $course, $instance);
+                        break;
+                }
+                if (!empty($authmessage)) {
+                    return $OUTPUT->box($authmessage);
+                }
+            }
+
+            ob_start();
+
+            echo '<p><strong>'.get_string('paymentrequired').'</strong></p>';
+            $form->display();
+
+            return $OUTPUT->box(ob_get_clean());
+        }
+    }
+
+    /**
+     * The user submitted credit card form.
+     *
+     * @param object $form Form parameters
+     * @param object $course Course info
+     * @param object $instance Enrol instance
+     * @return string NULL if ok, error message otherwise.
+     * @access private
+     */
+    private function cc_submit($form, $course, $instance) {
+        global $CFG, $USER, $SESSION, $OUTPUT, $DB;
+
+        $plugin = enrol_get_plugin('authorize');
+
+        prevent_double_paid($instance);
+
+        $useripno = getremoteaddr();
+        $curcost = get_course_cost($instance);
+        $exp_date = sprintf("%02d", $form->ccexpiremm) . $form->ccexpireyyyy;
+
+        // NEW CC ORDER
+        $timenow = time();
+        $order = new stdClass();
+        $order->paymentmethod = AN_METHOD_CC;
+        $order->refundinfo = substr($form->cc, -4);
+        $order->ccname = $form->firstname . " " . $form->lastname;
+        $order->courseid = $course->id;
+        $order->instanceid = $form->instanceid;
+        $order->userid = $USER->id;
+        $order->status = AN_STATUS_NONE; // it will be changed...
+        $order->settletime = 0; // cron changes this.
+        $order->transid = 0; // Transaction Id
+        $order->timecreated = $timenow;
+        $order->amount = $curcost['cost'];
+        $order->currency = $curcost['currency'];
+        $order->id = $DB->insert_record("enrol_authorize", $order);
+        if (!$order->id) {
+            message_to_admin("Error while trying to insert new data", $order);
+            return "Insert record error. Admin has been notified!";
+        }
+
+        $extra = new stdClass();
+        $extra->x_card_num = $form->cc;
+        $extra->x_card_code = $form->cvv;
+        $extra->x_exp_date = $exp_date;
+        $extra->x_currency_code = $curcost['currency'];
+        $extra->x_amount = $curcost['cost'];
+        $extra->x_first_name = $form->firstname;
+        $extra->x_last_name = $form->lastname;
+        $extra->x_country = $form->cccountry;
+        $extra->x_address = $form->ccaddress;
+        $extra->x_state = $form->ccstate;
+        $extra->x_city = $form->cccity;
+        $extra->x_zip = $form->cczip;
+
+        $extra->x_invoice_num = $order->id;
+        $extra->x_description = $course->shortname;
+
+        $extra->x_cust_id = $USER->id;
+        $extra->x_email = $USER->email;
+        $extra->x_customer_ip = $useripno;
+        $extra->x_email_customer = $plugin->get_config('enrol_mailstudents') ? 'FALSE' : 'TRUE';
+        $extra->x_phone = '';
+        $extra->x_fax = '';
+
+        if ($plugin->get_config('an_authcode') && !empty($form->ccauthcode)) {
+            $action = AN_ACTION_CAPTURE_ONLY;
+            $extra->x_auth_code = $form->ccauthcode;
+        } elseif ($plugin->get_config('an_review')) {
+            $action = AN_ACTION_AUTH_ONLY;
+        } else {
+            $action = AN_ACTION_AUTH_CAPTURE;
+        }
+
+        $message = '';
+        if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, $action, $form->cctype)) {
+            $SESSION->ccpaid = 1; // security check: don't duplicate payment
+
+            switch ($action)
+            {
+                // review enabled (authorize but capture: draw money but wait for settlement during 30 days)
+                // the first step is to inform payment managers and to redirect the user to main page.
+                // the next step is to accept/deny payment (AN_ACTION_PRIOR_AUTH_CAPTURE/VOID) within 30 days (payment management or scheduled-capture CRON)
+                // unless you accept payment or enable auto-capture cron, the transaction is expired after 30 days and the user cannot enrol to the course during 30 days.
+                // see also: admin/cron.php, $this->cron(), $plugin->get_config('an_capture_day')...
+                case AN_ACTION_AUTH_ONLY:
+                {
+                    $a = new stdClass;
+                    $a->url = "$CFG->wwwroot/enrol/authorize/index.php?order=$order->id";
+                    $a->orderid = $order->id;
+                    $a->transid = $order->transid;
+                    $a->amount = "$order->currency $order->amount";
+                    $a->expireon = userdate(AuthorizeNet::getsettletime($timenow + (30 * 3600 * 24)));
+                    $a->captureon = userdate(AuthorizeNet::getsettletime($timenow + (intval($plugin->get_config('an_capture_day')) * 3600 * 24)));
+                    $a->course = $course->fullname;
+                    $a->user = fullname($USER);
+                    $a->acstatus = ($plugin->get_config('an_capture_day') > 0) ? get_string('yes') : get_string('no');
+                    $emailmessage = get_string('adminneworder', 'enrol_authorize', $a);
+                    $a = new stdClass;
+                    $a->course = $course->shortname;
+                    $a->orderid = $order->id;
+                    $emailsubject = get_string('adminnewordersubject', 'enrol_authorize', $a);
+                    $context = get_context_instance(CONTEXT_COURSE, $course->id);
+                    if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
+                        foreach ($paymentmanagers as $paymentmanager) {
+                            $eventdata = new object();
+                            $eventdata->modulename        = 'moodle';
+                            $eventdata->component         = 'enrol_authorize';
+                            $eventdata->name              = 'authorize_enrolment';
+                            $eventdata->userfrom          = $USER;
+                            $eventdata->userto            = $paymentmanager;
+                            $eventdata->subject           = $emailsubject;
+                            $eventdata->fullmessage       = $emailmessage;
+                            $eventdata->fullmessageformat = FORMAT_PLAIN;
+                            $eventdata->fullmessagehtml   = '';
+                            $eventdata->smallmessage      = '';
+                            message_send($eventdata);
+                        }
+                    }
+                    redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
+                    break;
+                }
+
+                case AN_ACTION_CAPTURE_ONLY: // auth code received via phone and the code accepted.
+                case AN_ACTION_AUTH_CAPTURE: // real time transaction, authorize and capture.
+                {
+                    // Credit card captured, ENROL student now...
+                    if ($instance->enrolperiod) {
+                        $timestart = time();
+                        $timeend   = $timestart + $instance->enrolperiod;
+                    } else {
+                        $timestart = 0;
+                        $timeend   = 0;
+                    }
+
+                    $plugin->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);
+
+                    // Send notifications
+                    if ($plugin->get_config('enrol_mailstudents')) {
+                        send_welcome_messages($order->id);
+                    }
+                    if ($plugin->get_config('enrol_mailteachers')) {
+                        $context = get_context_instance(CONTEXT_COURSE, $course->id);
+                        $paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments', '', '', '0', '1');
+                        $paymentmanager = array_shift($paymentmanagers);
+                        $a = new stdClass;
+                        $a->course = "$course->fullname";
+                        $a->user = fullname($USER);
+
+                        $eventdata = new object();
+                        $eventdata->modulename        = 'moodle';
+                        $eventdata->component         = 'enrol_authorize';
+                        $eventdata->name              = 'authorize_enrolment';
+                        $eventdata->userfrom          = $USER;
+                        $eventdata->userto            = $paymentmanager;
+                        $eventdata->subject           = get_string("enrolmentnew", '', format_string($course->shortname));
+                        $eventdata->fullmessage       = get_string('enrolmentnewuser', '', $a);
+                        $eventdata->fullmessageformat = FORMAT_PLAIN;
+                        $eventdata->fullmessagehtml   = '';
+                        $eventdata->smallmessage      = '';
+                        message_send($eventdata);
+                    }
+                    if ($plugin->get_config('enrol_mailadmins')) {
+                        $a = new stdClass;
+                        $a->course = "$course->fullname";
+                        $a->user = fullname($USER);
+                        $admins = get_admins();
+                        foreach ($admins as $admin) {
+                            $eventdata = new object();
+                            $eventdata->modulename  = 'moodle';
+                            $eventdata->component   = 'enrol_authorize';
+                            $eventdata->name        = 'authorize_enrolment';
+                            $eventdata->userfrom    = $USER;
+                            $eventdata->userto      = $admin;
+                            $eventdata->subject     = get_string("enrolmentnew", '', format_string($course->shortname));
+                            $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
+                            $eventdata->fullmessageformat = FORMAT_PLAIN;
+                            $eventdata->fullmessagehtml   = '';
+                            $eventdata->smallmessage      = '';
+                            message_send($eventdata);
+                        }
+                    }
+
+                    load_all_capabilities();
+
+                    echo $OUTPUT->header();
+                    echo $OUTPUT->box_start('generalbox notice');
+                    echo '<p>'. get_string('paymentthanks', 'moodle', $course->fullname) .'</p>';
+                    echo $OUTPUT->container_start('buttons');
+                    echo $OUTPUT->single_button(new moodle_url("$CFG->wwwroot/enrol/authorize/index.php", array('order'=>$order->id)), get_string('payments'));
+                    echo $OUTPUT->single_button(new moodle_url("$CFG->wwwroot/course/view.php", array('id'=>$course->id)), $course->fullname);
+                    echo $OUTPUT->container_end();
+                    echo $OUTPUT->box_end();
+                    echo $OUTPUT->footer();
+                    exit;  // show output now!
+                }
+            }
+            return NULL;
+        } else {
+            message_to_admin($message, $order);
+            return $message;
+        }
+    }
+
+    /**
+     * The user submitted echeck form.
+     *
+     * @param object $form Form parameters
+     * @param object $course Course info
+     * @param object $course Enrol instance
+     * @return string NULL if ok, error message otherwise.
+     * @access private
+     */
+    private function echeck_submit($form, $course, $instance)
+    {
+        global $CFG, $USER, $SESSION, $DB;
+
+        prevent_double_paid($instance);
+
+        $useripno = getremoteaddr();
+        $curcost = get_course_cost($instance);
+        $isbusinesschecking = ($form->acctype == 'BUSINESSCHECKING');
+
+        // NEW ECHECK ORDER
+        $timenow = time();
+        $order = new stdClass();
+        $order->paymentmethod = AN_METHOD_ECHECK;
+        $order->refundinfo = $isbusinesschecking ? 1 : 0;
+        $order->ccname = $form->firstname . ' ' . $form->lastname;
+        $order->courseid = $course->id;
+        $order->instanceid = $form->instanceid;
+        $order->userid = $USER->id;
+        $order->status = AN_STATUS_NONE; // it will be changed...
+        $order->settletime = 0; // cron changes this.
+        $order->transid = 0; // Transaction Id
+        $order->timecreated = $timenow;
+        $order->amount = $curcost['cost'];
+        $order->currency = $curcost['currency'];
+        $order->id = $DB->insert_record("enrol_authorize", $order);
+        if (!$order->id) {
+            message_to_admin("Error while trying to insert new data", $order);
+            return "Insert record error. Admin has been notified!";
+        }
+
+        $extra = new stdClass();
+        $extra->x_bank_aba_code = $form->abacode;
+        $extra->x_bank_acct_num = $form->accnum;
+        $extra->x_bank_acct_type = $form->acctype;
+        $extra->x_echeck_type = $isbusinesschecking ? 'CCD' : 'WEB';
+        $extra->x_bank_name = $form->bankname;
+        $extra->x_currency_code = $curcost['currency'];
+        $extra->x_amount = $curcost['cost'];
+        $extra->x_first_name = $form->firstname;
+        $extra->x_last_name = $form->lastname;
+        $extra->x_country = $USER->country;
+        $extra->x_address = $USER->address;
+        $extra->x_city = $USER->city;
+        $extra->x_state = '';
+        $extra->x_zip = '';
+
+        $extra->x_invoice_num = $order->id;
+        $extra->x_description = $course->shortname;
+
+        $extra->x_cust_id = $USER->id;
+        $extra->x_email = $USER->email;
+        $extra->x_customer_ip = $useripno;
+        $extra->x_email_customer = $plugin->get_config('enrol_mailstudents') ? 'TRUE' : 'FALSE';
+        $extra->x_phone = '';
+        $extra->x_fax = '';
+
+        $message = '';
+        if (AN_REVIEW == AuthorizeNet::process($order, $message, $extra, AN_ACTION_AUTH_CAPTURE)) {
+            $SESSION->ccpaid = 1; // security check: don't duplicate payment
+            redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
+            return NULL;
+        }
+        else {
+            message_to_admin($message, $order);
+            return $message;
+        }
+    }
+
+    /**
+     * 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');
+        $plugin = enrol_get_plugin('authorize');
+
+        mtrace("Processing authorize cron...");
+
+        if (!isset($mconfig->an_dailysettlement) || intval($mconfig->an_dailysettlement) < $settlementtime) {
+            set_config('an_dailysettlement', $settlementtime, 'enrol_authorize');
+            mtrace("    Daily cron:");
+            $this->cron_daily();
+            mtrace("    Done");
+        }
+
+        mtrace("    Scheduled capture", ": ");
+        if (!$mconfig->an_review or ($mconfig->an_test) or (intval($mconfig->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($mconfig->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));
+                $pinstance = $DB->get_record('enrol', array('id'=>$order->instanceid));
+                $plugin->enrol_user($pinstance, $order->userid, $pinstance->roleid, $timestart, $timeend);
+                $this->log .= "User($user->id) has been enrolled to course($course->id).\n";
+                if (!empty($mconfig->enrol_mailstudents)) {
+                    $sendem[] = $order->id;
+                }
+            } 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->component         = 'enrol_authorize';
+            $eventdata->name              = 'authorize_enrolment';
+            $eventdata->userfrom          = $adminuser;
+            $eventdata->userto            = $adminuser;
+            $eventdata->subject           = "AUTHORIZE.NET CRON FAULTS";
+            $eventdata->fullmessage       = $faults;
+            $eventdata->fullmessageformat = FORMAT_PLAIN;
+            $eventdata->fullmessagehtml   = '';
+            $eventdata->smallmessage      = '';
+            message_send($eventdata);
+        }
+        if (!empty($mconfig->enrol_mailadmins)) {
+            $eventdata = new object();
+            $eventdata->modulename        = 'moodle';
+            $eventdata->component         = 'enrol_authorize';
+            $eventdata->name              = 'authorize_enrolment';
+            $eventdata->userfrom          = $adminuser;
+            $eventdata->userto            = $adminuser;
+            $eventdata->subject           = "AUTHORIZE.NET CRON LOG";
+            $eventdata->fullmessage       = $this->log;
+            $eventdata->fullmessageformat = FORMAT_PLAIN;
+            $eventdata->fullmessagehtml   = '';
+            $eventdata->smallmessage      = '';
+            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");
+        }
+    }
+
+    /**
+     * Daily cron. It executes at settlement time (default is 00:05).
+     *
+     * @access private
+     */
+    private function cron_daily()
+    {
+        global $CFG, $SITE, $DB;
+
+        $mconfig = get_config('enrol_authorize');
+
+        $oneday = 86400;
+        $timenow = time();
+        $onepass = $timenow - $oneday;
+        $settlementtime = AuthorizeNet::getsettletime($timenow);
+        $timediff30 = $settlementtime - (30 * $oneday);
+
+        $select = "(status=?) AND (timecreated<?)";
+        $params = array(AN_STATUS_NONE, $timediff30);
+        if ($DB->delete_records_select('enrol_authorize', $select, $params)) {
+            mtrace("        orders no transaction made have deleted");
+        }
+
+        $select = "(status=?) AND (timecreated<?)";
+        $params = array(AN_STATUS_EXPIRE, AN_STATUS_AUTH, $timediff30);
+        if ($DB->execute("UPDATE {enrol_authorize} SET status=? WHERE $select", $params)) {
+            mtrace("        pending orders to expire have updated");
+        }
+
+        $timediff60 = $settlementtime - (60 * $oneday);
+        $select = "(status=?) AND (timecreated<?)";
+        $params = array(AN_STATUS_EXPIRE, $timediff60);
+        if ($DB->delete_records_select('enrol_authorize', $select, $params)) {
+            mtrace("        orders expired older than 60 days have deleted");
+        }
+
+        $adminuser = get_admin();
+        $select = "status IN(?,?) AND (timecreated<?) AND (timecreated>?)";
+        $params = array(AN_STATUS_UNDERREVIEW, AN_STATUS_APPROVEDREVIEW, $onepass, $timediff60);
+        if (($count = $DB->count_records_select('enrol_authorize', $select, $params)) &&
+            ($csvusers = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), 'enrol/authorize:uploadcsv'))) {
+            $a = new stdClass;
+            $a->count = $count;
+            $a->course = $SITE->shortname;
+            $subject = get_string('pendingechecksubject', 'enrol_authorize', $a);
+            $a = new stdClass;
+            $a->count = $count;
+            $a->url = $CFG->wwwroot.'/enrol/authorize/uploadcsv.php';
+            $message = get_string('pendingecheckemail', 'enrol_authorize', $a);
+            foreach($csvusers as $csvuser) {
+                $eventdata = new object();
+                $eventdata->modulename        = 'moodle';
+                $eventdata->component         = 'enrol_authorize';
+                $eventdata->name              = 'authorize_enrolment';
+                $eventdata->userfrom          = $adminuser;
+                $eventdata->userto            = $csvuser;
+                $eventdata->subject           = $subject;
+                $eventdata->fullmessage       = $message;
+                $eventdata->fullmessageformat = FORMAT_PLAIN;
+                $eventdata->fullmessagehtml   = '';
+                $eventdata->smallmessage      = '';
+                message_send($eventdata);
+            }
+            mtrace("        users who have 'enrol/authorize:uploadcsv' were mailed");
+        }
+
+        mtrace("        early pending order warning email for manual capture", ": ");
+        if (empty($mconfig->an_emailexpired)) {
+            mtrace("not enabled");
+            return;
+        }
+
+
+        $timediffem = $settlementtime - ((30 - intval($mconfig->an_emailexpired)) * $oneday);
+        $select = "(status=?) AND (timecreated<?) AND (timecreated>?)";
+        $params = array(AN_STATUS_AUTH, $timediffem, $timediff30);
+        $count = $DB->count_records_select('enrol_authorize', $select, $params);
+        if (!$count) {
+            mtrace("no orders prior to {$mconfig->an_emailexpired} days");
+            return;
+        }
+
+        mtrace("$count orders prior to {$mconfig->an_emailexpired} days");
+        $a = new stdClass;
+        $a->pending = $count;
+        $a->days = $mconfig->an_emailexpired;
+        $a->course = $SITE->shortname;
+        $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
+        $a = new stdClass;
+        $a->pending = $count;
+        $a->days = $mconfig->an_emailexpired;
+        $a->course = $SITE->fullname;
+        $a->enrolurl = "$CFG->wwwroot/$CFG->admin/enrol_config.php?enrol=authorize";
+        $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?status='.AN_STATUS_AUTH;
+        $message = get_string('pendingordersemail', 'enrol_authorize', $a);
+
+        $eventdata = new object();
+        $eventdata->modulename        = 'moodle';
+        $eventdata->component         = 'enrol_authorize';
+        $eventdata->name              = 'authorize_enrolment';
+        $eventdata->userfrom          = $adminuser;
+        $eventdata->userto            = $adminuser;
+        $eventdata->subject           = $subject;
+        $eventdata->fullmessage       = $message;
+        $eventdata->fullmessageformat = FORMAT_PLAIN;
+        $eventdata->fullmessagehtml   = '';
+        $eventdata->smallmessage      = '';
+        message_send($eventdata);
+
+        // Email to payment managers
+        if (empty($mconfig->an_emailexpiredteacher)) {
+            return; // email feature disabled for teachers.
+        }
+
+        $sorttype = empty($mconfig->an_sorttype) ? 'ttl' : $mconfig->an_sorttype;
+        $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,
+                  COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl
+                FROM {enrol_authorize} e
+                  INNER JOIN {course} c ON c.id = e.courseid
+                WHERE (e.status = ?)
+                  AND (e.timecreated < ?)
+                  AND (e.timecreated > ?)
+                GROUP BY e.courseid
+                ORDER BY $sorttype DESC";
+        $params = array(AN_STATUS_AUTH, $timediffem, $timediff30);
+
+        $rs = $DB->get_recordset_sql($sql, $params);
+        foreach ($rs as $courseinfo)
+        {
+            $lastcourse = $courseinfo->courseid;
+            $context = get_context_instance(CONTEXT_COURSE, $lastcourse);
+            if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
+                $a = new stdClass;
+                $a->course = $courseinfo->shortname;
+                $a->pending = $courseinfo->cnt;
+                $a->days = $mconfig->an_emailexpired;
+                $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
+                $a = new stdClass;
+                $a->course = $courseinfo->fullname;
+                $a->pending = $courseinfo->cnt;
+                $a->currency = $courseinfo->currency;
+                $a->sumcost = $courseinfo->ttl;
+                $a->days = $mconfig->an_emailexpired;
+                $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?course='.$lastcourse.'&amp;status='.AN_STATUS_AUTH;
+                $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a);
+                foreach ($paymentmanagers as $paymentmanager) {
+                    $eventdata = new object();
+                    $eventdata->modulename        = 'moodle';
+                    $eventdata->component         = 'enrol_authorize';
+                    $eventdata->name              = 'authorize_enrolment';
+                    $eventdata->userfrom          = $adminuser;
+                    $eventdata->userto            = $paymentmanager;
+                    $eventdata->subject           = $subject;
+                    $eventdata->fullmessage       = $message;
+                    $eventdata->fullmessageformat = FORMAT_PLAIN;
+                    $eventdata->fullmessagehtml   = '';
+                    $eventdata->smallmessage      = '';
+                    message_send($eventdata);
+                }
+            }
+        }
+        $rs->close();
+    }
+}
+
diff --git a/enrol/authorize/localfuncs.php b/enrol/authorize/localfuncs.php
index 456ec94..cffe4a6 100644
--- a/enrol/authorize/localfuncs.php
+++ b/enrol/authorize/localfuncs.php
@@ -1,18 +1,43 @@
 <?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize enrolment plugin.
+ *
+ * This plugin allows you to set up paid courses, using authorize.net.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
 
 require_once($CFG->libdir.'/eventslib.php');
 
-function get_course_cost($course)
-{
-    global $CFG;
+function get_course_cost($plugininstance) {
+    $defaultplugin = enrol_get_plugin('authorize');
 
     $cost = (float)0;
-    $currency = (!empty($course->currency))
-                 ? $course->currency :( empty($CFG->enrol_currency)
-                                        ? 'USD' : $CFG->enrol_currency );
+    $currency = (!empty($plugininstance->currency))
+                 ? $plugininstance->currency :( empty($defaultplugin->currency)
+                                        ? 'USD' : $defaultplugin->enrol_currency );
 
-    if (!empty($course->cost)) {
-        $cost = (float)(((float)$course->cost) < 0) ? $CFG->enrol_cost : $course->cost;
+    if (!empty($plugininstance->cost)) {
+        $cost = (float)(((float)$plugininstance->cost) < 0) ? $defaultplugin->cost : $plugininstance->cost;
     }
 
     $cost = format_float($cost, 2);
@@ -24,26 +49,26 @@ function get_course_cost($course)
     return $ret;
 }
 
-function zero_cost($course) {
-    $curcost = get_course_cost($course);
+function zero_cost($plugininstance) {
+    $curcost = get_course_cost($plugininstance);
     return (abs($curcost['cost']) < 0.01);
 }
 
-function prevent_double_paid($course)
-{
+function prevent_double_paid($plugininstance) {
     global $CFG, $SESSION, $USER, $DB;
+    $plugin = enrol_get_plugin('authorize');
 
-    $sql = "SELECT id FROM {enrol_authorize} WHERE userid = ? AND courseid = ? ";
-    $params = array($USER->id, $course->id);
+    $sql = "SELECT id FROM {enrol_authorize} WHERE userid = ? AND courseid = ? AND instanceid = ?";
+    $params = array($USER->id, $plugininstance->courseid, $plugininstance->id);
 
-    if (empty($CFG->an_test)) { // Real mode
-        $sql .= 'AND status IN(?,?,?)';
+    if (!$plugin->get_config('an_test')) { // Real mode
+        $sql .= ' AND status IN(?,?,?)';
         $params[] = AN_STATUS_AUTH;
         $params[] = AN_STATUS_UNDERREVIEW;
         $params[] = AN_STATUS_APPROVEDREVIEW;
     }
     else { // Test mode
-        $sql .= 'AND status=?';
+        $sql .= ' AND status=?';
         $params[] = AN_STATUS_NONE;
     }
 
@@ -61,9 +86,8 @@ function prevent_double_paid($course)
     }
 }
 
-function get_list_of_creditcards($getall = false)
-{
-    global $CFG;
+function get_list_of_creditcards($getall = false) {
+    $plugin = enrol_get_plugin('authorize');
 
     $alltypes = array(
         'mcd' => 'Master Card',
@@ -77,44 +101,61 @@ function get_list_of_creditcards($getall = false)
         'enr' => 'EnRoute'
     );
 
-    if ($getall or empty($CFG->an_acceptccs)) {
+    if ($getall) {
         return $alltypes;
     }
 
     $ret = array();
-    $ccs = explode(',', $CFG->an_acceptccs);
-    foreach ($ccs as $key) {
-        $ret[$key] = $alltypes[$key];
+    foreach ($alltypes as $code=>$name) {
+        if ($plugin->get_config("an_acceptcc_{$code}")) {
+            $ret[$code] = $name;
+        }
     }
+
     return $ret;
 }
 
-function get_list_of_payment_methods($getall = false)
-{
-    global $CFG;
+function get_list_of_payment_methods($getall = false) {
+    $plugin = enrol_get_plugin('authorize');
+    $method_cc = $plugin->get_config('an_acceptmethod_cc');
+    $method_echeck = $plugin->get_config('an_acceptmethod_echeck');
+
 
-    if ($getall || empty($CFG->an_acceptmethods)) {
+    if ($getall || (empty($method_cc) && empty($method_echeck))) {
         return array(AN_METHOD_CC, AN_METHOD_ECHECK);
-    }
-    else {
-        return explode(',', $CFG->an_acceptmethods);
+    } else {
+        $methods = array();
+        if ($method_cc) {
+            $methods[] = AN_METHOD_CC;
+        }
+
+        if ($method_echeck) {
+            $methods[] = AN_METHOD_ECHECK;
+        }
+
+        return $methods;
     }
 }
 
-function get_list_of_bank_account_types($getall = false)
-{
-    global $CFG;
+function get_list_of_bank_account_types($getall = false) {
+    $plugin = enrol_get_plugin('authorize');
+    $alltypes = array('CHECKING', 'BUSINESSCHECKING', 'SAVINGS');
 
-    if ($getall || empty($CFG->an_acceptechecktypes)) {
-        return array('CHECKING', 'BUSINESSCHECKING', 'SAVINGS');
-    }
-    else {
-        return explode(',', $CFG->an_acceptechecktypes);
+    if ($getall) {
+        return $alltypes;
+    } else {
+        $types = array();
+        foreach ($alltypes as $type) {
+            if ($plugin->get_config("an_acceptecheck_{$type}")) {
+                $types[] = $type;
+            }
+        }
+
+        return $types;
     }
 }
 
-function message_to_admin($subject, $data)
-{
+function message_to_admin($subject, $data) {
     global $SITE;
 
     $admin = get_admin();
@@ -124,6 +165,8 @@ function message_to_admin($subject, $data)
     $emailmessage .= print_r($data, true);
     $eventdata = new object();
     $eventdata->modulename        = 'moodle';
+    $eventdata->component         = 'enrol_authorize';
+    $eventdata->name              = 'authorize_enrolment';
     $eventdata->userfrom          = $admin;
     $eventdata->userto            = $admin;
     $eventdata->subject           = "$SITE->fullname: Authorize.net ERROR";
@@ -134,8 +177,7 @@ function message_to_admin($subject, $data)
     message_send($eventdata);
 }
 
-function send_welcome_messages($orderdata)
-{
+function send_welcome_messages($orderdata) {
     global $CFG, $SITE, $DB;
 
     if (empty($orderdata)) {
@@ -191,6 +233,8 @@ function send_welcome_messages($orderdata)
 
                 $eventdata = new object();
                 $eventdata->modulename        = 'moodle';
+                $eventdata->component         = 'enrol_authorize';
+                $eventdata->name              = 'authorize_enrolment';
                 $eventdata->userfrom          = $sender;
                 $eventdata->userto            = $user;
                 $eventdata->subject           = get_string("enrolmentnew", '', $SITE->shortname);
@@ -207,20 +251,20 @@ function send_welcome_messages($orderdata)
     }
 }
 
-function check_curl_available()
-{
+function check_curl_available() {
     return function_exists('curl_init') &&
            function_exists('stream_get_wrappers') &&
            in_array('https', stream_get_wrappers());
 }
 
-function authorize_verify_account()
-{
-    global $CFG, $USER, $SITE;
+function authorize_verify_account() {
+    global $USER, $SITE;
+    $plugin = enrol_get_plugin('authorize');
+
     require_once('authorizenet.class.php');
 
-    $original_antest = $CFG->an_test;
-    $CFG->an_test = 1; // Test mode
+    $original_antest = $plugin->get_config('an_test');
+    $plugin->set_config('an_test', 1); // Test mode
 
     $order = new stdClass();
     $order->id = -1;
@@ -257,7 +301,9 @@ function authorize_verify_account()
     else {
         $ret = get_string('verifyaccountresult', 'enrol_authorize', $message);
     }
-    $CFG->an_test = $original_antest;
+
+    $plugin->set_config('an_test', $original_antest);
+
     return $ret;
 }
 
diff --git a/enrol/authorize/locallib.php b/enrol/authorize/locallib.php
index 9e010ce..4a3a0bd 100644
--- a/enrol/authorize/locallib.php
+++ b/enrol/authorize/locallib.php
@@ -1,4 +1,30 @@
 <?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize enrolment plugin.
+ *
+ * This plugin allows you to set up paid courses, using authorize.net.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
 
 if (!defined('MOODLE_INTERNAL')) {
     die('Direct access to this script is forbidden.');
@@ -17,6 +43,9 @@ function authorize_print_orders($courseid, $userid) {
     global $course;
     global $CFG, $USER, $SITE, $DB, $OUTPUT, $PAGE;
     global $strs, $authstrs;
+
+    $plugin = enrol_get_plugin('authorize');
+
     require_once($CFG->libdir.'/tablelib.php');
 
     $perpage = optional_param('perpage', 10, PARAM_INT);
@@ -132,7 +161,7 @@ function authorize_print_orders($courseid, $userid) {
         switch ($status)
         {
             case AN_STATUS_NONE:
-                if (empty($CFG->an_test)) {
+                if (!$plugin->get_config('an_test')) {
                     $where .= "AND (e.status != :status) ";
                     $params['status'] = AN_STATUS_NONE;
                 }
@@ -223,6 +252,9 @@ 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);
@@ -269,6 +301,7 @@ function authorize_print_order($orderid)
     }
     $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);
@@ -302,9 +335,9 @@ function authorize_print_order($orderid)
             $message = '';
             $extra = NULL;
             if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
-                if (empty($CFG->an_test)) {
+                if (empty($an_test)) {
                     if (enrol_into_course($course, $user, 'authorize')) {
-                        if (!empty($CFG->enrol_mailstudents)) {
+                        if ($plugin->get_config('enrol_mailstudents')) {
                             send_welcome_messages($orderid);
                         }
                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
@@ -352,13 +385,15 @@ function authorize_print_order($orderid)
             $message = '';
             $success = AuthorizeNet::process($order, $message, $extra, AN_ACTION_CREDIT);
             if (AN_APPROVED == $success || AN_REVIEW == $success) {
-                if (empty($CFG->an_test)) {
+                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)) {
-                            role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
+                            $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");
                     }
@@ -383,7 +418,9 @@ function authorize_print_order($orderid)
     elseif (ORDER_DELETE == $do && in_array(ORDER_DELETE, $statusandactions->actions)) {
         if ($confirm && confirm_sesskey()) {
             if (!empty($unenrol)) {
-                role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
+                $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");
@@ -399,7 +436,7 @@ function authorize_print_order($orderid)
                 $extra = NULL;
                 $message = '';
                 if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_VOID)) {
-                    if (empty($CFG->an_test)) {
+                    if (empty($an_test)) {
                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
                     }
                     else {
@@ -434,9 +471,11 @@ function authorize_print_order($orderid)
                     $message = '';
                     $extra = NULL;
                     if (AN_APPROVED == AuthorizeNet::process($suborder, $message, $extra, AN_ACTION_VOID)) {
-                        if (empty($CFG->an_test)) {
+                        if (empty($an_test)) {
                             if (!empty($unenrol)) {
-                                role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
+                                $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");
                         }
diff --git a/enrol/authorize/settings.php b/enrol/authorize/settings.php
new file mode 100644
index 0000000..fb4356b
--- /dev/null
+++ b/enrol/authorize/settings.php
@@ -0,0 +1,176 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Paypal enrolments plugin settings and presets.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter - based on code by others
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once('localfuncs.php');
+require_once('const.php');
+
+if ($ADMIN->fulltree) {
+    global $CFG, $DB, $OUTPUT;
+    $mconfig = get_config('enrol_authorize');
+
+    // Check curl availability
+    if (!check_curl_available()) {
+        $settings->add(new admin_setting_heading('enrol_authorize_notification', '', 'PHP must be compiled with cURL+SSL support (--with-curl --with-openssl)'));
+        return;
+    }
+
+    // Check https availability
+    if (empty($CFG->loginhttps) and substr($CFG->wwwroot, 0, 5) !== 'https') {
+        $a = new stdClass;
+        $a->url = "$CFG->wwwroot/$CFG->admin/settings.php?section=httpsecurity";
+        $settings->add(new admin_setting_heading('enrol_authorize_notification', '', get_string('adminconfighttps', 'enrol_authorize', $a)));
+        return;
+    } elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
+        $wwwsroot = qualified_me();
+        $wwwsroot = str_replace('http:', 'https:', $wwwsroot);
+        $a = new stdClass;
+        $a->url = $wwwsroot;
+        $settings->add(new admin_setting_heading('enrol_authorize_notification', '', get_string('adminconfighttpsgo', 'enrol_authorize', $a)));
+        return;
+    }
+
+    // Account verification notification
+    if (optional_param('verifyaccount', 0, PARAM_INT)) {
+        $settings->add(new admin_setting_heading('enrol_authorize_notification', '', authorize_verify_account()));
+    }
+
+    // Review check
+    if (!empty($mconfig->an_review)) {
+        $captureday = intval($mconfig->an_capture_day);
+        $emailexpired = intval($mconfig->an_emailexpired);
+        if ($captureday > 0 || $emailexpired > 0) {
+            $lastcron = $DB->get_field_sql('SELECT max(lastcron) FROM {modules}');
+            if ((time() - intval($lastcron) > 3600 * 24)) {
+                $settings->add(new admin_setting_heading('enrol_authorize_cron_notification', '', get_string('admincronsetup', 'enrol_authorize')));
+            }
+        }
+    }
+
+    // Pending orders check
+    if (($count = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH)))) {
+        $a = new stdClass;
+        $a->count = $count;
+        $a->url = $CFG->wwwroot."/enrol/authorize/index.php?status=".AN_STATUS_AUTH;
+        $settings->add(new admin_setting_heading('enrol_authorize_status_notification', '', get_string('adminpendingorders', 'enrol_authorize', $a)));
+    }
+
+
+    // Set up the form
+
+    $settings->add(new admin_setting_heading('enrol_authorize_settings', '', get_string('description', 'enrol_authorize')));
+
+    //--- sitewide settings ---------------------------------------------------------------------------------
+    $settings->add(new admin_setting_heading('enrol_authorize_sitewide',
+        get_string("adminauthorizewide", "enrol_authorize"), ''));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/cost', get_string('cost', 'enrol_authorize'), '', 5, PARAM_FLOAT, 4));
+
+    $settings->add(new admin_setting_configselect('enrol_authorize/currency', get_string('currency', 'enrol_authorize'), '', 'USD', get_string_manager()->get_list_of_currencies()));
+
+    if (!optional_param('verifyaccount', 0, PARAM_INT) && isset($mconfig->an_login) && (isset($mconfig->an_tran_key) || isset($mconfig->an_password))) {
+
+        $settings->add(new admin_setting_heading('enrol_authorize_verification', '',
+            '<a href="settings.php?section=enrolsettingsauthorize&amp;verifyaccount=1"><b>'.
+            get_string("verifyaccount", "enrol_authorize").'</b></a>'));
+    }
+
+    //--- authorize.net settings ----------------------------------------------------------------------------
+    $settings->add(new admin_setting_heading('enrol_authorize_net_settings',
+        get_string("adminauthorizesettings", "enrol_authorize"), get_string('logininfo', 'enrol_authorize')));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/an_login', get_string('anlogin', 'enrol_authorize'), '', ''));
+
+    $settings->add(new admin_setting_configpasswordunmask('enrol_authorize/an_tran_key', get_string('antrankey', 'enrol_authorize'), '', ''));
+
+    $settings->add(new admin_setting_configpasswordunmask('enrol_authorize/an_password', get_string('anpassword', 'enrol_authorize'), '', ''));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/an_referer', get_string('anreferer', 'enrol_authorize'), get_string('anrefererdesc', 'enrol_authorize'), 'http://'));
+
+    $settings->add(new admin_setting_configtime('enrol_authorize/an_cutoff_hour', 'an_cutoff_min', get_string('cutofftime', 'enrol_authorize'), get_string('cutofftimedesc', 'enrol_authorize'), ''));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_avs', get_string('anavs', 'enrol_authorize'), get_string('anavsdesc', 'enrol_authorize'), 0));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_authcode', get_string('anauthcode', 'enrol_authorize'), get_string('anauthcodedesc', 'enrol_authorize'), 0));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_test', get_string('antestmode', 'enrol_authorize'), get_string('antestmodedesc', 'enrol_authorize'), 0));
+
+    $paymentmethods = get_list_of_payment_methods(true);
+    $settings->add(new admin_setting_heading('enrol_authorize_net_payment_method_settings',
+        '', get_string('adminaccepts', 'enrol_authorize')));
+    foreach ($paymentmethods as $key) {
+        if ($key == AN_METHOD_CC) {
+            $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_acceptmethod_'.AN_METHOD_CC,
+                                                            get_string('method'.AN_METHOD_CC, 'enrol_authorize'),
+                                                            get_string('method'.AN_METHOD_CC.'desc', 'enrol_authorize'),
+                                                            0));
+            $ccs = get_list_of_creditcards(true);
+            foreach ($ccs as $key => $val) {
+                $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_acceptcc_'.$key,
+                                                                $val,
+                                                                '', 0));
+            }
+        } elseif ($key == AN_METHOD_ECHECK) {
+            $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_acceptmethod_'.AN_METHOD_ECHECK,
+                                                            get_string('method'.AN_METHOD_ECHECK, 'enrol_authorize'),
+                                                            get_string('method'.AN_METHOD_ECHECK.'desc', 'enrol_authorize'),
+                                                            0));
+            $echecktypes = get_list_of_bank_account_types(true);
+            foreach ($echecktypes as $value) {
+                $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_acceptecheck_'.$value,
+                                                                $value,
+                                                                '', 0));
+            }
+        }
+    }
+
+    //--- order review and capture settings -----------------------------------------------------------------
+    $settings->add(new admin_setting_heading('enrol_authorize_capture',
+        get_string("adminauthorizeccapture", "enrol_authorize"), ''));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/an_review', get_string('anreview', 'enrol_authorize'), get_string('anreviewdesc', 'enrol_authorize'), 0));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/an_capture_day', get_string('ancaptureday', 'enrol_authorize'), get_string('ancapturedaydesc', 'enrol_authorize'), 5, PARAM_INT, 4));
+
+
+    //--- email sending settings ----------------------------------------------------------------------------
+    $settings->add(new admin_setting_heading('enrol_authorize_email',
+        get_string("adminauthorizeemail", "enrol_authorize"), ''));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/an_emailexpired', get_string('anemailexpired', 'enrol_authorize'), get_string('anemailexpireddesc', 'enrol_authorize'), 5, PARAM_INT, 4));
+
+    $settings->add(new admin_setting_configtext('enrol_authorize/an_emailexpiredteacher', get_string('anemailexpiredteacher', 'enrol_authorize'), get_string('anemailexpiredteacherdesc', 'enrol_authorize'), 5, PARAM_INT, 4));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/mailstudents', get_string('mailstudents'), '', 0));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/mailteachers', get_string('mailteachers'), '', 0));
+
+    $settings->add(new admin_setting_configcheckbox('enrol_authorize/mailadmin', get_string('mailadmins'), '', 0));
+
+}
diff --git a/enrol/authorize/unenrolself.php b/enrol/authorize/unenrolself.php
new file mode 100644
index 0000000..2333bd9
--- /dev/null
+++ b/enrol/authorize/unenrolself.php
@@ -0,0 +1,64 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Authorize.Net enrolment plugin - support for user self unenrolment.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require('../../config.php');
+
+$enrolid = required_param('enrolid', PARAM_INT);
+$confirm = optional_param('confirm', 0, PARAM_BOOL);
+
+$instance = $DB->get_record('enrol', array('id'=>$enrolid, 'enrol'=>'authorize'), '*', MUST_EXIST);
+$course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
+$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
+
+require_login();
+if (!is_enrolled($context)) {
+    redirect(new moodle_url('/'));
+}
+require_login($course);
+
+$plugin = enrol_get_plugin('authorize');
+
+// security defined inside following function
+if (!$plugin->get_unenrolself_link($instance)) {
+    redirect(new moodle_url('/course/view.php', array('id'=>$course->id)));
+}
+
+$PAGE->set_url('/enrol/authorize/unenrolself.php', array('enrolid'=>$instance->id));
+$PAGE->set_title($plugin->get_instance_name($instance));
+
+if ($confirm and confirm_sesskey()) {
+    $plugin->unenrol_user($instance, $USER->id);
+    add_to_log($course->id, 'course', 'unenrol', '../enrol/users.php?id='.$course->id, $course->id); //there should be userid somewhere!
+    redirect(new moodle_url('/index.php'));
+}
+
+echo $OUTPUT->header();
+$yesurl = new moodle_url($PAGE->url, array('confirm'=>1, 'sesskey'=>sesskey()));
+$nourl = new moodle_url('/course/view.php', array('id'=>$course->id));
+$message = get_string('unenrolselfconfirm', 'enrol_authorize', format_string($course->fullname));
+echo $OUTPUT->confirm($message, $yesurl, $nourl);
+echo $OUTPUT->footer();
diff --git a/enrol/authorize/uploadcsv.php b/enrol/authorize/uploadcsv.php
index 11da31f..3f4b4f2 100644
--- a/enrol/authorize/uploadcsv.php
+++ b/enrol/authorize/uploadcsv.php
@@ -1,5 +1,4 @@
 <?php
-
 // This file is part of Moodle - http://moodle.org/
 //
 // Moodle is free software: you can redistribute it and/or modify
@@ -15,6 +14,16 @@
 // You should have received a copy of the GNU General Public License
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
+/**
+ * Authorize.Net enrolment plugin - support for user self unenrolment.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
 /// Load libraries
 require_once('../../config.php');
 require_once($CFG->dirroot.'/enrol/authorize/const.php');
@@ -62,6 +71,8 @@ echo $OUTPUT->footer();
 function authorize_process_csv($filename) {
     global $CFG, $SITE, $DB;
 
+    $plugin = enrol_get_plugin('authorize');
+
     /// We need these fields
     $myfields = array(
         'Transaction ID',           // enrol_authorize.transid or enrol_authorize_refunds.transid; See: Reference Transaction ID
@@ -214,15 +225,13 @@ function authorize_process_csv($filename) {
                     $timestart = time();
                     $timeend = $timestart + $course->enrolperiod;
                 }
-                //TODO: do some real enrolment here
-                if (role_assign($role->id, $user->id, $coursecontext->id, 'enrol_authorize')) {
-                    $imported++;
-                    if (!empty($CFG->enrol_mailstudents)) {
-                        $sendem[] = $order->id;
-                    }
-                }
-                else {
-                    $ignoredlines .= $transid . ": Error while trying to enrol " . fullname($user) . " in '$course->fullname' \n";
+                // 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;
                 }
             }
         }
@@ -235,6 +244,8 @@ function authorize_process_csv($filename) {
 
         $eventdata = new object();
         $eventdata->modulename        = 'moodle';
+        $eventdata->component         = 'enrol_authorize';
+        $eventdata->name              = 'authorize_enrolment';
         $eventdata->userfrom          = $admin;
         $eventdata->userto            = $admin;
         $eventdata->subject           = "$SITE->fullname: Authorize.net CSV ERROR LOG";
diff --git a/enrol/authorize/version.php b/enrol/authorize/version.php
index 933bb16..fbdccd0 100755
--- a/enrol/authorize/version.php
+++ b/enrol/authorize/version.php
@@ -1,6 +1,31 @@
 <?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
-$plugin->version  = 2009042700;
-$plugin->requires = 2007101507;
+/**
+ * Authorize.Net enrolment plugin version specification.
+ *
+ * @package    enrol
+ * @subpackage authorize
+ * @copyright  2010 Eugene Venter
+ * @author     Eugene Venter
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
 
+defined('MOODLE_INTERNAL') || die();
 
+$plugin->version  = 2010081203;
+$plugin->requires = 2007101507;
+$plugin->cron = 180;
