6dc069e162c909e72c0e4d747fc88ec6781f0f66
[moodle.git] / enrol / authorize / locallib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Authorize enrolment plugin.
19  *
20  * This plugin allows you to set up paid courses, using authorize.net.
21  *
22  * @package    enrol
23  * @subpackage authorize
24  * @copyright  2010 Eugene Venter
25  * @author     Eugene Venter
26  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27  */
29 if (!defined('MOODLE_INTERNAL')) {
30     die('Direct access to this script is forbidden.');
31 }
33 define('ORDER_CAPTURE', 'capture');
34 define('ORDER_DELETE',  'delete');
35 define('ORDER_REFUND',  'refund');
36 define('ORDER_VOID',    'void');
38 /**
39  * authorize_print_orders
40  *
41  */
42 function authorize_print_orders($courseid, $userid) {
43     global $course;
44     global $CFG, $USER, $SITE, $DB, $OUTPUT, $PAGE;
45     global $strs, $authstrs;
47     $plugin = enrol_get_plugin('authorize');
49     require_once($CFG->libdir.'/tablelib.php');
51     $perpage = optional_param('perpage', 10, PARAM_INT);
52     $showonlymy = optional_param('showonlymy', 0, PARAM_BOOL);
53     $searchquery = optional_param('searchquery', '0', PARAM_INT);
54     $searchtype = optional_param('searchtype', 'orderid', PARAM_ALPHA);
55     $status = optional_param('status', AN_STATUS_NONE, PARAM_INT);
57     $coursecontext = get_context_instance(CONTEXT_USER, $USER->id);
59     $searchmenu = array('orderid' => $authstrs->orderid, 'transid' => $authstrs->transid, 'cclastfour' => $authstrs->cclastfour);
60     $buttons = "<form method='post' action='index.php' autocomplete='off'><div>";
61     $buttons .= html_writer::select($searchmenu, 'searchtype', $searchtype, false);
62     $buttons .= "<input type='text' size='16' name='searchquery' value='' />";
63     $buttons .= "<input type='submit' value='$strs->search' />";
64     $buttons .= "</div></form>";
66     if (has_capability('enrol/authorize:uploadcsv', $coursecontext)) {
67         $buttons .= "<form method='get' action='uploadcsv.php'><div><input type='submit' value='".get_string('uploadcsv', 'enrol_authorize')."' /></div></form>";
68     }
70     $canmanagepayments = has_capability('enrol/authorize:managepayments', $coursecontext);
71     if ($showonlymy || !$canmanagepayments) {
72         $userid = $USER->id;
73     }
75     $baseurl = $CFG->wwwroot.'/enrol/authorize/index.php?user='.$userid;
77     $params = array('userid'=>$userid);
78     $sql = "SELECT c.id, c.fullname FROM {course} c JOIN {enrol_authorize} e ON c.id = e.courseid ";
79     $sql .= ($userid > 0) ? "WHERE (e.userid=:userid) " : '';
80     $sql .= "ORDER BY c.sortorder, c.fullname";
81     if (($popupcrs = $DB->get_records_sql_menu($sql, $params))) {
82         $popupcrs = array($SITE->id => $SITE->fullname) + $popupcrs;
83     }
84     $popupmenu = empty($popupcrs) ? '' : $OUTPUT->single_select(new moodle_url($baseurl.'&status='.$status), 'course', $popupcrs, $courseid, null, 'coursesmenu');
85     $popupmenu .= '<br />';
86     $statusmenu = array(
87         AN_STATUS_NONE => $strs->all,
88         AN_STATUS_AUTH | AN_STATUS_UNDERREVIEW | AN_STATUS_APPROVEDREVIEW => $authstrs->allpendingorders,
89         AN_STATUS_AUTH => $authstrs->authorizedpendingcapture,
90         AN_STATUS_AUTHCAPTURE => $authstrs->authcaptured,
91         AN_STATUS_CREDIT => $authstrs->refunded,
92         AN_STATUS_VOID => $authstrs->cancelled,
93         AN_STATUS_EXPIRE => $authstrs->expired,
94         AN_STATUS_UNDERREVIEW => $authstrs->underreview,
95         AN_STATUS_APPROVEDREVIEW => $authstrs->approvedreview,
96         AN_STATUS_REVIEWFAILED => $authstrs->reviewfailed,
97         AN_STATUS_TEST => $authstrs->tested
98     );
100     $popupmenu .= $OUTPUT->single_select(new moodle_url($baseurl.'&course='.$courseid), 'status', $statusmenu, $status, null, 'statusmenu');
101     if ($canmanagepayments) {
102         $popupmenu .= '<br />';
103         $PAGE->requires->js('/enrol/authorize/authorize.js');
104         $aid = $OUTPUT->add_action_handler(new component_action('click', 'authorize_jump_to_mypayments', array('userid' => $USER->id, 'status' => $status)));
105         $popupmenu .= html_writer::checkbox('enrol_authorize', 1, $userid == $USER->id, get_string('mypaymentsonly', 'enrol_authorize'), array('id'=>$aid));
106     }
108     if (SITEID != $courseid) {
109         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
110         $PAGE->navbar->add($shortname, new moodle_url('/course/view.php', array('id'=>$course->id)));
111     }
112     $PAGE->navbar->add($authstrs->paymentmanagement, 'index.php');
113     $PAGE->set_title("$course->shortname: $authstrs->paymentmanagement");
114     $PAGE->set_heading($authstrs->paymentmanagement);
115     $PAGE->set_headingmenu($popupmenu);
116     $PAGE->set_button($buttons);
117     echo $OUTPUT->header();
119     $table = new flexible_table('enrol-authorize');
120     $table->set_attribute('width', '100%');
121     $table->set_attribute('cellspacing', '0');
122     $table->set_attribute('cellpadding', '3');
123     $table->set_attribute('id', 'orders');
124     $table->set_attribute('class', 'generaltable generalbox');
126     if ($perpage > 100) { $perpage = 100; }
127     $perpagemenus = array(5 => 5, 10 => 10, 20 => 20, 50 => 50, 100 => 100);
128     $perpagemenu = $OUTPUT->single_select(new moodle_url($baseurl.'&status='.$status.'&course='.$courseid), 'perpage', $perpagemenus, $perpage, array(''=>'choosedots'), 'perpagemenu');
129     $table->define_columns(array('id', 'userid', 'timecreated', 'status', 'action'));
130     $table->define_headers(array($authstrs->orderid, $authstrs->shopper, $strs->time, $strs->status, $perpagemenu));
131     $table->define_baseurl($baseurl."&amp;status=$status&amp;course=$courseid&amp;perpage=$perpage");
133     $table->no_sorting('action');
134     $table->sortable(true, 'id', SORT_DESC);
135     $table->pageable(true);
136     $table->setup();
138     $select = "SELECT e.id, e.paymentmethod, e.refundinfo, e.transid, e.courseid, e.userid, e.status, e.ccname, e.timecreated, e.settletime ";
139     $from   = "FROM {enrol_authorize} e ";
140     $where  = "WHERE (1=1) ";
141     $params = array();
143     if (!empty($searchquery)) {
144         switch($searchtype) {
145             case 'orderid':
146                 $where = "WHERE (e.id = :searchquery) ";
147                 $params['searchquery'] = $searchquery;
148                 break;
150             case 'transid':
151                 $where = "WHERE (e.transid = :searchquery) ";
152                 $params['searchquery'] = $searchquery;
153                 break;
155             case 'cclastfour':
156                 $searchquery = sprintf("%04d", $searchquery);
157                 $where = "WHERE (e.refundinfo = :searchquery) AND (e.paymentmethod=:method) ";
158                 $params['searchquery'] = $searchquery;
159                 $params['method'] = AN_METHOD_CC;
160                 break;
161         }
162     }
163     else {
164         switch ($status)
165         {
166             case AN_STATUS_NONE:
167                 if (!$plugin->get_config('an_test')) {
168                     $where .= "AND (e.status != :status) ";
169                     $params['status'] = AN_STATUS_NONE;
170                 }
171                 break;
173             case AN_STATUS_TEST:
174                 $newordertime = time() - 120; // -2 minutes. Order may be still in process.
175                 $where .= "AND (e.status = :status) AND (e.transid = '0') AND (e.timecreated < :newordertime) ";
176                 $params['status'] = AN_STATUS_NONE;
177                 $params['newordertime'] = $newordertime;
178                 break;
180             case AN_STATUS_AUTH | AN_STATUS_UNDERREVIEW | AN_STATUS_APPROVEDREVIEW:
181                 $where .= 'AND (e.status IN(:status1,:status2,:status3)) ';
182                 $params['status1'] = AN_STATUS_AUTH;
183                 $params['status2'] = AN_STATUS_UNDERREVIEW;
184                 $params['status3'] = AN_STATUS_APPROVEDREVIEW;
185                 break;
187             case AN_STATUS_CREDIT:
188                 $from .= "INNER JOIN {enrol_authorize_refunds} r ON e.id = r.orderid ";
189                 $where .= "AND (e.status = :status) ";
190                 $params['status'] = AN_STATUS_AUTHCAPTURE;
191                 break;
193             default:
194                 $where .= "AND (e.status = :status) ";
195                 $params['status'] = $status;
196                 break;
197         }
199         if (SITEID != $courseid) {
200             $where .= "AND (e.courseid = :courseid) ";
201             $params['courseid'] = $courseid;
202         }
203     }
205     // This must be always LAST where!!!
206     if ($userid > 0) {
207         $where .= "AND (e.userid = :userid) ";
208         $params['userid'] = $userid;
209     }
211     if (($sort = $table->get_sql_sort())) {
212         $sort = ' ORDER BY ' . $sort;
213     }
215     $totalcount = $DB->count_records_sql('SELECT COUNT(*) ' . $from . $where, $params);
216     $table->initialbars($totalcount > $perpage);
217     $table->pagesize($perpage, $totalcount);
219     if (($records = $DB->get_records_sql($select . $from . $where . $sort, $params, $table->get_page_start(), $table->get_page_size()))) {
220         foreach ($records as $record) {
221             $actionstatus = authorize_get_status_action($record);
222             $color = authorize_get_status_color($actionstatus->status);
223             $actions = '';
225             if (empty($actionstatus->actions)) {
226                 $actions .= $strs->none;
227             }
228             else {
229                 foreach ($actionstatus->actions as $val) {
230                     $actions .= authorize_print_action_button($record->id, $val);
231                 }
232             }
234             $table->add_data(array(
235                 "<a href='index.php?order=$record->id'>$record->id</a>",
236                 $record->ccname,
237                 userdate($record->timecreated),
238                 "<font style='color:$color'>" . $authstrs->{$actionstatus->status} . "</font>",
239                 $actions
240             ));
241         }
242     }
244     $table->print_html();
245     echo $OUTPUT->footer();
248 /**
249  * authorize_print_order
250  *
251  * @param object $order
252  */
253 function authorize_print_order($orderid)
255     global $CFG, $USER, $DB, $OUTPUT, $PAGE;
256     global $strs, $authstrs;
258     $plugin = enrol_get_plugin('authorize');
259     $an_test = $plugin->get_config('an_test');
261     $do = optional_param('do', '', PARAM_ALPHA);
262     $unenrol = optional_param('unenrol', 0, PARAM_BOOL);
263     $confirm = optional_param('confirm', 0, PARAM_BOOL);
265     if (!$order = $DB->get_record('enrol_authorize', array('id'=>$orderid))) {
266         print_error('orderidnotfound', '',
267                 "$CFG->wwwroot/enrol/authorize/index.php", $orderid);
268     }
270     if (!$course = $DB->get_record('course', array('id'=>$order->courseid))) {
271         print_error('invalidcourseid', '', "$CFG->wwwroot/enrol/authorize/index.php");
272     }
274     if (!$user = $DB->get_record('user', array('id'=>$order->userid))) {
275         print_error('nousers', '', "$CFG->wwwroot/enrol/authorize/index.php");
276     }
278     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
279     if ($USER->id != $order->userid) { // Current user viewing someone else's order
280         require_capability('enrol/authorize:managepayments', $coursecontext);
281     }
283     $settled = AuthorizeNet::settled($order);
284     $statusandactions = authorize_get_status_action($order);
285     $color = authorize_get_status_color($statusandactions->status);
287     $buttons = '';
288     if (empty($do))
289     {
290         if (empty($statusandactions->actions)) {
291             if ((AN_METHOD_ECHECK == $order->paymentmethod) && has_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id))) {
292                 $buttons .= "<form method='get' action='uploadcsv.php'><div><input type='submit' value='".get_string('uploadcsv', 'enrol_authorize')."' /></div></form>";
293             }
294         }
295         else {
296             foreach ($statusandactions->actions as $val) {
297                 $buttons .= authorize_print_action_button($orderid, $val);
298             }
299         }
300     }
302     if (SITEID != $course->id) {
303         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
304         $PAGE->navbar->add($shortname, new moodle_url('/course/view.php', array('id'=>$course->id)));
305     }
306     $PAGE->navbar->add($authstrs->paymentmanagement, 'index.php?course='.$course->id);
307     $PAGE->navbar->add($authstrs->orderid . ': ' . $orderid, 'index.php');
308     $PAGE->set_course($course);
309     $PAGE->set_title("$course->shortname: $authstrs->paymentmanagement");
310     $PAGE->set_heading($authstrs->orderdetails);
311     $PAGE->set_cacheable(false);
312     $PAGE->set_button($buttons);
313     echo $OUTPUT->header();
315     $table = new html_table();
316     $table->width = '100%';
317     $table->size = array('30%', '70%');
318     $table->align = array('right', 'left');
320     if (AN_METHOD_CC == $order->paymentmethod) {
321         $table->data[] = array("<b>$authstrs->paymentmethod:</b>", $authstrs->methodcc);
322         $table->data[] = array("<b>$authstrs->nameoncard:</b>", $order->ccname . ' (<b><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'">'.fullname($user).'</a></b>)');
323         $table->data[] = array("<b>$authstrs->cclastfour:</b>", $order->refundinfo);
324     }
325     else {
326         $table->data[] = array("<b>$authstrs->paymentmethod:</b>", $authstrs->methodecheck);
327         $table->data[] = array("<b>$authstrs->echeckfirslasttname:</b>", $order->ccname . ' (<b><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'">'.fullname($user).'</a></b>)');
328         $table->data[] = array("<b>$authstrs->isbusinesschecking:</b>", ($order->refundinfo == 1) ? $strs->yes : $strs->no);
329     }
331     $table->data[] = array("<b>$authstrs->amount:</b>", "$order->currency $order->amount");
332     $table->data[] = array("<b>$authstrs->transid:</b>", $order->transid);
333     $table->data[] = array("<b>$strs->time:</b>", userdate($order->timecreated));
334     $table->data[] = array("<b>$authstrs->settlementdate:</b>", $settled ? userdate($order->settletime) : $authstrs->notsettled);
335     $table->data[] = array("<b>$strs->status:</b>", "<b><font style='color:$color'>" . $authstrs->{$statusandactions->status} . "</font></b>");
337     if (ORDER_CAPTURE == $do && in_array(ORDER_CAPTURE, $statusandactions->actions)) {
338         if ($confirm && confirm_sesskey()) {
339             $message = '';
340             $extra = NULL;
341             if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
342                 if (empty($an_test)) {
343                     if (enrol_into_course($course, $user, 'authorize')) {
344                         if ($plugin->get_config('enrol_mailstudents')) {
345                             send_welcome_messages($orderid);
346                         }
347                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
348                     }
349                     else {
350                         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
351                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", "Error while trying to enrol ".fullname($user)." in '" . $shortname . "'", 20);
352                     }
353                 }
354                 else {
355                     redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", get_string('testwarning', 'enrol_authorize'), 10);
356                 }
357             }
358             else {
359                 redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $message, 20);
360             }
361         }
362         $table->data[] = array("<b>$strs->confirm:</b>", get_string('captureyes', 'enrol_authorize') . '<br />' .
363                                authorize_print_action_button($orderid, ORDER_CAPTURE, 0, true, false, $strs->no));
364         echo html_writer::table($table);
365     }
366     elseif (ORDER_REFUND == $do && in_array(ORDER_REFUND, $statusandactions->actions)) {
367         $refunded = 0.0;
368         $sql = "SELECT SUM(amount) AS refunded
369                   FROM {enrol_authorize_refunds}
370                  WHERE (orderid = ?)
371                    AND (status = ?)";
373         if (($refundval = $DB->get_field_sql($sql, array($orderid, AN_STATUS_CREDIT)))) {
374             $refunded = floatval($refundval);
375         }
376         $upto = round($order->amount - $refunded, 2);
377         if ($upto <= 0) {
378             print_error('refoundtoorigi', '',
379                     "$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $order->amount);
380         }
381         $amount = round(optional_param('amount', $upto, PARAM_RAW), 2);
382         if ($amount > $upto) {
383             print_error('refoundto', '',
384                     "$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $upto);
385         }
386         if ($confirm && confirm_sesskey()) {
387             $extra = new stdClass;
388             $extra->orderid = $orderid;
389             $extra->amount = $amount;
390             $message = '';
391             $success = AuthorizeNet::process($order, $message, $extra, AN_ACTION_CREDIT);
392             if (AN_APPROVED == $success || AN_REVIEW == $success) {
393                 if (empty($an_test)) {
394                     if (empty($extra->id)) {
395                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", "insert record error", 20);
396                     }
397                     else {
398                         if (!empty($unenrol)) {
399                             $pinstance = $DB->get_record('enrol', array('id'=>$order->instanceid));
400                             $plugin->unenrol_user($pinstance, $order->userid);
401                             //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
402                         }
403                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
404                     }
405                 }
406                 else {
407                     redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", get_string('testwarning', 'enrol_authorize'), 10);
408                 }
409             }
410             else {
411                 redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $message, 20);
412             }
413         }
414         $a = new stdClass;
415         $a->upto = $upto;
416         $extrahtml = get_string('howmuch', 'enrol_authorize') .
417                      ' <input type="text" size="5" name="amount" value="'.$amount.'" /> ' .
418                      get_string('canbecredit', 'enrol_authorize', $a) . '<br />';
419         $table->data[] = array("<b>$strs->confirm:</b>",
420                                authorize_print_action_button($orderid, ORDER_REFUND, 0, true, $authstrs->unenrolstudent, $strs->no, $extrahtml));
421         echo html_writer::table($table);
422     }
423     elseif (ORDER_DELETE == $do && in_array(ORDER_DELETE, $statusandactions->actions)) {
424         if ($confirm && confirm_sesskey()) {
425             if (!empty($unenrol)) {
426                 $pinstance = $DB->get_record('enrol', array('id'=>$order->instanceid));
427                 $plugin->unenrol_user($pinstance, $order->userid);
428                 //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
429             }
430             $DB->delete_records('enrol_authorize', array('id'=>$orderid));
431             redirect("$CFG->wwwroot/enrol/authorize/index.php");
432         }
433         $table->data[] = array("<b>$strs->confirm:</b>",
434                                authorize_print_action_button($orderid, ORDER_DELETE, 0, true, $authstrs->unenrolstudent,$strs->no));
435         echo html_writer::table($table);
436     }
437     elseif (ORDER_VOID == $do) { // special case: cancel original or refunded transaction?
438         $suborderid = optional_param('suborder', 0, PARAM_INT);
439         if (empty($suborderid) && in_array(ORDER_VOID, $statusandactions->actions)) { // cancel original
440             if ($confirm && confirm_sesskey()) {
441                 $extra = NULL;
442                 $message = '';
443                 if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_VOID)) {
444                     if (empty($an_test)) {
445                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
446                     }
447                     else {
448                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", get_string('testwarning', 'enrol_authorize'), 10);
449                     }
450                 }
451                 else {
452                     redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $message, 20);
453                 }
454             }
455             $table->data[] = array("<b>$strs->confirm:</b>", get_string('voidyes', 'enrol_authorize') . '<br />' .
456                                    authorize_print_action_button($orderid, ORDER_VOID, 0, true, false, $strs->no));
457             echo html_writer::table($table);
458         }
459         elseif (!empty($suborderid)) { // cancel refunded
460             $sql = "SELECT r.*, e.courseid, e.paymentmethod
461                       FROM {enrol_authorize_refunds} r
462                 INNER JOIN {enrol_authorize} e
463                         ON r.orderid = e.id
464                      WHERE r.id = ?
465                        AND r.orderid = ?
466                        AND r.status = ?";
468             $suborder = $DB->get_record_sql($sql, array($suborderid, $orderid, AN_STATUS_CREDIT));
469             if (!$suborder) { // not found
470                 print_error('transactionvoid', '', "$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
471             }
472             $refundedstatus = authorize_get_status_action($suborder);
473             unset($suborder->courseid);
474             if (in_array(ORDER_VOID, $refundedstatus->actions)) {
475                 if ($confirm && confirm_sesskey()) {
476                     $message = '';
477                     $extra = NULL;
478                     if (AN_APPROVED == AuthorizeNet::process($suborder, $message, $extra, AN_ACTION_VOID)) {
479                         if (empty($an_test)) {
480                             if (!empty($unenrol)) {
481                                 $pinstance = $DB->get_record('enrol', array('id'=>$order->instanceid));
482                                 $plugin->unenrol_user($pinstance, $order->userid);
483                                 //role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
484                             }
485                             redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
486                         }
487                         else {
488                             redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", get_string('testwarning', 'enrol_authorize'), 10);
489                         }
490                     }
491                     else {
492                         redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid", $message, 20);
493                     }
494                 }
495                 $a = new stdClass;
496                 $a->transid = $suborder->transid;
497                 $a->amount = $suborder->amount;
498                 $table->data[] = array("<b>$strs->confirm:</b>", get_string('subvoidyes', 'enrol_authorize', $a) . '<br />' .
499                                        authorize_print_action_button($orderid, ORDER_VOID, $suborderid, true, $authstrs->unenrolstudent, $strs->no));
500                 echo html_writer::table($table);
501             }
502         }
503     }
504     else {
505         echo html_writer::table($table);
507         if ($settled) { // show refunds.
508             $t2 = new html_table();
509             $t2->size = array('45%', '15%', '20%', '10%', '10%');
510             $t2->align = array('right', 'right', 'right', 'right', 'right');
511             $t2->head = array($authstrs->settlementdate, $authstrs->transid, $strs->status, $strs->action, $authstrs->amount);
513             $sql = "SELECT r.*, e.courseid, e.paymentmethod
514                       FROM {enrol_authorize_refunds} r
515                 INNER JOIN {enrol_authorize} e
516                         ON r.orderid = e.id
517                      WHERE r.orderid = ?";
519             if (($refunds = $DB->get_records_sql($sql, array($orderid)))) {
520                 $sumrefund = floatval(0.0);
521                 foreach ($refunds as $rf) {
522                     $subactions = '';
523                     $substatus = authorize_get_status_action($rf);
524                     if (empty($substatus->actions)) {
525                         $subactions .= $strs->none;
526                     }
527                     else {
528                         foreach ($substatus->actions as $vl) {
529                             $subactions .= authorize_print_action_button($orderid, $vl, $rf->id);
530                         }
531                     }
532                     $sign = '';
533                     $color = authorize_get_status_color($substatus->status);
534                     if ($substatus->status == 'refunded' or $substatus->status == 'settled') {
535                         $sign = '-';
536                         $sumrefund += floatval($rf->amount);
537                     }
538                     $t2->data[] = array(
539                         userdate($rf->settletime),
540                         $rf->transid,
541                         "<b><font style='color:$color'>" .$authstrs->{$substatus->status} . "</font></b>",
542                         $subactions,
543                         format_float($sign . $rf->amount, 2)
544                     );
545                 }
546                 $t2->data[] = array('','',get_string('total'),$order->currency,format_float('-'.$sumrefund, 2));
547             }
548             else {
549                 $t2->data[] = array('','',get_string('noreturns', 'enrol_authorize'),'','');
550             }
551             echo "<h4>" . get_string('returns', 'enrol_authorize') . "</h4>\n";
552             echo html_writer::table($t2);
553         }
554     }
556     echo $OUTPUT->footer();
559 /**
560  * authorize_get_status_action
561  *
562  * @param object $order Order details.
563  * @return object
564  */
565 function authorize_get_status_action($order)
567     global $CFG;
568     static $newordertime = 0;
570     if (0 == $newordertime) {
571         $newordertime = time() - 120; // -2 minutes. Order may be still in process.
572     }
574     $ret = new stdClass();
575     $ret->actions = array();
577     $canmanage = has_capability('enrol/authorize:managepayments', get_context_instance(CONTEXT_COURSE, $order->courseid));
579     if (floatval($order->transid) == 0) { // test transaction or new order
580         if ($order->timecreated < $newordertime) {
581             if ($canmanage) {
582                 $ret->actions = array(ORDER_DELETE);
583             }
584             $ret->status = 'tested';
585         }
586         else {
587             $ret->status = 'new';
588         }
589         return $ret;
590     }
592     switch ($order->status) {
593         case AN_STATUS_AUTH:
594             if (AuthorizeNet::expired($order)) {
595                 if ($canmanage) {
596                     $ret->actions = array(ORDER_DELETE);
597                 }
598                 $ret->status = 'expired';
599             }
600             else {
601                 if ($canmanage) {
602                     $ret->actions = array(ORDER_CAPTURE, ORDER_VOID);
603                 }
604                 $ret->status = 'authorizedpendingcapture';
605             }
606             return $ret;
608         case AN_STATUS_AUTHCAPTURE:
609             if (AuthorizeNet::settled($order)) {
610                 if ($canmanage) {
611                     if (($order->paymentmethod == AN_METHOD_CC) || ($order->paymentmethod == AN_METHOD_ECHECK && !empty($order->refundinfo))) {
612                         $ret->actions = array(ORDER_REFUND);
613                     }
614                 }
615                 $ret->status = 'settled';
616             }
617             else {
618                 if ($order->paymentmethod == AN_METHOD_CC && $canmanage) {
619                     $ret->actions = array(ORDER_VOID);
620                 }
621                 $ret->status = 'capturedpendingsettle';
622             }
623             return $ret;
625         case AN_STATUS_CREDIT:
626             if (AuthorizeNet::settled($order)) {
627                 $ret->status = 'settled';
628             }
629             else {
630                 if ($order->paymentmethod == AN_METHOD_CC && $canmanage) {
631                     $ret->actions = array(ORDER_VOID);
632                 }
633                 $ret->status = 'refunded';
634             }
635             return $ret;
637         case AN_STATUS_VOID:
638             $ret->status = 'cancelled';
639             return $ret;
641         case AN_STATUS_EXPIRE:
642             if ($canmanage) {
643                 $ret->actions = array(ORDER_DELETE);
644             }
645             $ret->status = 'expired';
646             return $ret;
648         case AN_STATUS_UNDERREVIEW:
649             $ret->status = 'underreview';
650             return $ret;
652         case AN_STATUS_APPROVEDREVIEW:
653             $ret->status = 'approvedreview';
654             return $ret;
656         case AN_STATUS_REVIEWFAILED:
657             if ($canmanage) {
658                 $ret->actions = array(ORDER_DELETE);
659             }
660             $ret->status = 'reviewfailed';
661             return $ret;
663         default:
664             return $ret;
665     }
669 function authorize_get_status_color($status)
671     $color = 'black';
672     switch ($status)
673     {
674         case 'settled':
675         case 'capturedpendingsettle':
676             $color = '#339900'; // green
677             break;
679         case 'underreview':
680         case 'approvedreview':
681         case 'authorizedpendingcapture':
682             $color = '#FF6600'; // orange
683             break;
685         case 'new':
686         case 'tested':
687             $color = '#003366'; // blue
688             break;
690         case 'expired':
691         case 'cancelled':
692         case 'refunded';
693         case 'reviewfailed':
694             $color = '#FF0033'; // red
695             break;
696     }
697     return $color;
700 function authorize_print_action_button($orderid, $do, $suborderid=0, $confirm=false, $unenrol=false, $nobutton=false, $extrahtml='')
702     global $CFG, $OUTPUT;
703     global $authstrs;
705     $ret =  '<form action="'.$CFG->wwwroot.'/enrol/authorize/index.php'.'" method="post"><div>' .
706             '<input type="hidden" name="order" value="'.$orderid.'" />' .
707             '<input type="hidden" name="do" value="'.$do.'" />' .
708             '<input type="hidden" name="sesskey" value="'. sesskey() . '" />';
709     if (!empty($suborderid)) {
710         $ret .= '<input type="hidden" name="suborder" value="'.$suborderid.'" />';
711     }
712     if (!empty($confirm)) {
713         $ret .= '<input type="hidden" name="confirm" value="1" />';
714     }
715     if (!empty($unenrol)) {
716         $ret .= html_writer::checkbox('unenrol', 1, false, $unenrol) . '<br />';
717     }
718     $ret .= $extrahtml;
719     $ret .= '<input type="submit" value="'.$authstrs->$do.'" />' .
720             '</div></form>';
721     if (!empty($nobutton)) {
722         $ret .= '<form method="get" action="index.php"><div><input type="hidden" name="order" value="'.$orderid.'" /><input type="submit" value="'.$nobutton.'" /></div></form>';
723     }
724     return $ret;