Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / enrol / authorize / enrol.php
blobb88131bbffb064bd1c0b8dfb2cfec56e7b6aa2b5
1 <?php // $Id$
3 require_once($CFG->dirroot.'/enrol/enrol.class.php');
4 require_once($CFG->dirroot.'/enrol/authorize/const.php');
5 require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
7 /**
8 * Authorize.net Payment Gateway plugin
9 */
10 class enrolment_plugin_authorize
13 /**
14 * Cron log.
16 * @var string
17 * @access public
19 var $log;
22 /**
23 * Presents registration forms.
25 * @param object $course Course info
26 * @access public
28 function print_entry($course) {
29 global $CFG, $USER, $form;
31 $zerocost = zero_cost($course);
32 if ($zerocost) {
33 $manual = enrolment_factory::factory('manual');
34 if (!empty($this->errormsg)) {
35 $manual->errormsg = $this->errormsg;
37 $manual->print_entry($course);
38 return;
41 prevent_double_paid($course);
42 httpsrequired();
44 if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
45 if (empty($CFG->loginhttps)) {
46 print_error('httpsrequired', 'enrol_authorize');
47 } else {
48 $wwwsroot = str_replace('http:','https:', $CFG->wwwroot);
49 redirect("$wwwsroot/course/enrol.php?id=$course->id");
50 exit;
54 $strcourses = get_string('courses');
55 $strloginto = get_string('loginto', '', $course->shortname);
57 $navlinks = array();
58 $navlinks[] = array('name' => $strcourses, 'link' => "$CFG->wwwroot/course/", 'type' => 'misc');
59 $navlinks[] = array('name' => $strloginto, 'link' => null, 'type' => 'misc');
60 $navigation = build_navigation($navlinks);
62 print_header($strloginto, $course->fullname, $navigation);
63 print_course($course, '80%');
65 if ($course->password) {
66 print_heading(get_string('choosemethod', 'enrol_authorize'), 'center');
69 print_simple_box_start('center', '80%');
70 if ($USER->username == 'guest') { // only real guest user, not for users with guest role
71 $curcost = get_course_cost($course);
72 echo '<div align="center">';
73 echo '<p>'.get_string('paymentrequired').'</p>';
74 echo '<p><b>'.get_string('cost').": $curcost[currency] $curcost[cost]".'</b></p>';
75 echo '<p><a href="'.$CFG->httpswwwroot.'/login/">'.get_string('loginsite').'</a></p>';
76 echo '</div>';
78 else {
79 require_once($CFG->dirroot.'/enrol/authorize/enrol_form.php');
80 $frmenrol = new enrol_authorize_form('enrol.php', compact('course'));
81 if ($frmenrol->get_data()) {
82 $authorizeerror = '';
83 switch ($form->paymentmethod) {
84 case AN_METHOD_CC:
85 $authorizeerror = $this->cc_submit($form, $course);
86 break;
88 case AN_METHOD_ECHECK:
89 $authorizeerror = $this->echeck_submit($form, $course);
90 break;
92 if (!empty($authorizeerror)) {
93 error($authorizeerror);
96 $frmenrol->display();
98 print_simple_box_end();
100 if ($course->password) {
101 $password = '';
102 include($CFG->dirroot.'/enrol/manual/enrol.html');
105 print_footer();
109 function print_enrolmentkeyfrom($course)
111 $manual = enrolment_factory::factory('manual');
112 $manual->print_enrolmentkeyfrom($course);
117 * Validates registration forms and enrols student to course.
119 * @param object $form Form parameters
120 * @param object $course Course info
121 * @access public
123 function check_entry($form, $course)
125 global $CFG;
127 if (zero_cost($course) || (!empty($course->password) && !empty($form->enrol) && $form->enrol == 'manual')) {
128 $manual = enrolment_factory::factory('manual');
129 $manual->check_entry($form, $course);
130 if (!empty($manual->errormsg)) {
131 $this->errormsg = $manual->errormsg;
139 * The user submitted credit card form.
141 * @param object $form Form parameters
142 * @param object $course Course info
143 * @access private
145 function cc_submit($form, $course)
147 global $CFG, $USER, $SESSION;
148 require_once('authorizenetlib.php');
150 prevent_double_paid($course);
152 $useripno = getremoteaddr();
153 $curcost = get_course_cost($course);
154 $exp_date = sprintf("%02d", $form->ccexpiremm) . $form->ccexpireyyyy;
156 // NEW CC ORDER
157 $timenow = time();
158 $order = new stdClass();
159 $order->paymentmethod = AN_METHOD_CC;
160 $order->refundinfo = substr($form->cc, -4);
161 $order->ccname = $form->firstname . " " . $form->lastname;
162 $order->courseid = $course->id;
163 $order->userid = $USER->id;
164 $order->status = AN_STATUS_NONE; // it will be changed...
165 $order->settletime = 0; // cron changes this.
166 $order->transid = 0; // Transaction Id
167 $order->timecreated = $timenow;
168 $order->amount = $curcost['cost'];
169 $order->currency = $curcost['currency'];
170 $order->id = insert_record("enrol_authorize", $order);
171 if (!$order->id) {
172 email_to_admin("Error while trying to insert new data", $order);
173 return "Insert record error. Admin has been notified!";
176 $extra = new stdClass();
177 $extra->x_card_num = $form->cc;
178 $extra->x_card_code = $form->cvv;
179 $extra->x_exp_date = $exp_date;
180 $extra->x_currency_code = $curcost['currency'];
181 $extra->x_amount = $curcost['cost'];
182 $extra->x_first_name = $form->firstname;
183 $extra->x_last_name = $form->lastname;
184 $extra->x_country = $form->cccountry;
185 $extra->x_address = $form->ccaddress;
186 $extra->x_state = $form->ccstate;
187 $extra->x_city = $form->cccity;
188 $extra->x_zip = $form->cczip;
190 $extra->x_invoice_num = $order->id;
191 $extra->x_description = $course->shortname;
193 $extra->x_cust_id = $USER->id;
194 $extra->x_email = $USER->email;
195 $extra->x_customer_ip = $useripno;
196 $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE';
197 $extra->x_phone = '';
198 $extra->x_fax = '';
200 if (!empty($CFG->an_authcode) && !empty($form->ccauthcode)) {
201 $action = AN_ACTION_CAPTURE_ONLY;
202 $extra->x_auth_code = $form->ccauthcode;
204 elseif (!empty($CFG->an_review)) {
205 $action = AN_ACTION_AUTH_ONLY;
207 else {
208 $action = AN_ACTION_AUTH_CAPTURE;
211 $message = '';
212 if (AN_APPROVED != authorize_action($order, $message, $extra, $action, $form->cctype)) {
213 email_to_admin($message, $order);
214 return $message;
217 $SESSION->ccpaid = 1; // security check: don't duplicate payment
219 if (AN_ACTION_AUTH_ONLY == $action) { // review enabled, inform payment managers and redirect the user who have paid to main page.
220 $a = new stdClass;
221 $a->url = "$CFG->wwwroot/enrol/authorize/index.php?order=$order->id";
222 $a->orderid = $order->id;
223 $a->transid = $order->transid;
224 $a->amount = "$order->currency $order->amount";
225 $a->expireon = userdate(authorize_getsettletime($timenow + (30 * 3600 * 24)));
226 $a->captureon = userdate(authorize_getsettletime($timenow + (intval($CFG->an_capture_day) * 3600 * 24)));
227 $a->course = $course->fullname;
228 $a->user = fullname($USER);
229 $a->acstatus = ($CFG->an_capture_day > 0) ? get_string('yes') : get_string('no');
230 $emailmessage = get_string('adminneworder', 'enrol_authorize', $a);
231 $a = new stdClass;
232 $a->course = $course->shortname;
233 $a->orderid = $order->id;
234 $emailsubject = get_string('adminnewordersubject', 'enrol_authorize', $a);
235 $context = get_context_instance(CONTEXT_COURSE, $course->id);
236 if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
237 foreach ($paymentmanagers as $paymentmanager) {
238 email_to_user($paymentmanager, $USER, $emailsubject, $emailmessage);
241 redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
242 return;
245 // Credit card captured, ENROL student now...
246 if (enrol_into_course($course, $USER, 'authorize')) {
247 if (!empty($CFG->enrol_mailstudents)) {
248 send_welcome_messages($order->id);
250 if (!empty($CFG->enrol_mailteachers)) {
251 $context = get_context_instance(CONTEXT_COURSE, $course->id);
252 $paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments', '', '', '0', '1');
253 $paymentmanager = array_shift($paymentmanagers);
254 $a = new stdClass;
255 $a->course = "$course->fullname";
256 $a->user = fullname($USER);
257 email_to_user($paymentmanager,
258 $USER,
259 get_string("enrolmentnew", '', format_string($course->shortname)),
260 get_string('enrolmentnewuser', '', $a));
262 if (!empty($CFG->enrol_mailadmins)) {
263 $a = new stdClass;
264 $a->course = "$course->fullname";
265 $a->user = fullname($USER);
266 $admins = get_admins();
267 foreach ($admins as $admin) {
268 email_to_user($admin,
269 $USER,
270 get_string("enrolmentnew", '', format_string($course->shortname)),
271 get_string('enrolmentnewuser', '', $a));
274 } else {
275 email_to_admin("Error while trying to enrol " . fullname($USER) . " in '$course->fullname'", $order);
278 if ($SESSION->wantsurl) {
279 $destination = $SESSION->wantsurl; unset($SESSION->wantsurl);
280 } else {
281 $destination = "$CFG->wwwroot/course/view.php?id=$course->id";
283 load_all_capabilities();
284 redirect($destination, get_string('paymentthanks', 'moodle', $course->fullname), 10);
289 * The user submitted echeck form.
291 * @param object $form Form parameters
292 * @param object $course Course info
293 * @access private
295 function echeck_submit($form, $course)
297 global $CFG, $USER, $SESSION;
298 require_once('authorizenetlib.php');
300 prevent_double_paid($course);
302 $useripno = getremoteaddr();
303 $curcost = get_course_cost($course);
304 $isbusinesschecking = ($form->acctype == 'BUSINESSCHECKING');
306 // NEW ECHECK ORDER
307 $timenow = time();
308 $order = new stdClass();
309 $order->paymentmethod = AN_METHOD_ECHECK;
310 $order->refundinfo = $isbusinesschecking ? 1 : 0;
311 $order->ccname = $form->firstname . ' ' . $form->lastname;
312 $order->courseid = $course->id;
313 $order->userid = $USER->id;
314 $order->status = AN_STATUS_NONE; // it will be changed...
315 $order->settletime = 0; // cron changes this.
316 $order->transid = 0; // Transaction Id
317 $order->timecreated = $timenow;
318 $order->amount = $curcost['cost'];
319 $order->currency = $curcost['currency'];
320 $order->id = insert_record("enrol_authorize", $order);
321 if (!$order->id) {
322 email_to_admin("Error while trying to insert new data", $order);
323 return "Insert record error. Admin has been notified!";
326 $extra = new stdClass();
327 $extra->x_bank_aba_code = $form->abacode;
328 $extra->x_bank_acct_num = $form->accnum;
329 $extra->x_bank_acct_type = $form->acctype;
330 $extra->x_echeck_type = $isbusinesschecking ? 'CCD' : 'WEB';
331 $extra->x_bank_name = $form->bankname;
332 $extra->x_currency_code = $curcost['currency'];
333 $extra->x_amount = $curcost['cost'];
334 $extra->x_first_name = $form->firstname;
335 $extra->x_last_name = $form->lastname;
336 $extra->x_country = $USER->country;
337 $extra->x_address = $USER->address;
338 $extra->x_city = $USER->city;
339 $extra->x_state = '';
340 $extra->x_zip = '';
342 $extra->x_invoice_num = $order->id;
343 $extra->x_description = $course->shortname;
345 $extra->x_cust_id = $USER->id;
346 $extra->x_email = $USER->email;
347 $extra->x_customer_ip = $useripno;
348 $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE';
349 $extra->x_phone = '';
350 $extra->x_fax = '';
352 $message = '';
353 if (AN_REVIEW != authorize_action($order, $message, $extra, AN_ACTION_AUTH_CAPTURE)) {
354 email_to_admin($message, $order);
355 return $message;
358 $SESSION->ccpaid = 1; // security check: don't duplicate payment
359 redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
364 * Gets access icons.
366 * @param object $course
367 * @return string
368 * @access public
370 function get_access_icons($course) {
372 $manual = enrolment_factory::factory('manual');
373 $str = $manual->get_access_icons($course);
374 $curcost = get_course_cost($course);
376 if (abs($curcost['cost']) > 0.00) {
377 $strrequirespayment = get_string("requirespayment");
378 $strcost = get_string("cost");
379 $currency = $curcost['currency'];
381 switch ($currency) {
382 case 'USD': $currency = 'US$'; break;
383 case 'CAD': $currency = 'C$'; break;
384 case 'EUR': $currency = '&euro;'; break;
385 case 'GBP': $currency = '&pound;'; break;
386 case 'JPY': $currency = '&yen;'; break;
389 $str .= '<div class="cost" title="'.$strrequirespayment.'">'.$strcost.': ';
390 $str .= $currency . ' ' . $curcost['cost'].'</div>';
393 return $str;
398 * Shows config form & errors
400 * @param object $frm
401 * @access public
403 function config_form($frm)
405 global $CFG;
406 $mconfig = get_config('enrol/authorize');
408 if (!check_openssl_loaded()) {
409 notify('PHP must be compiled with SSL support (--with-openssl)');
412 if (empty($CFG->loginhttps) and substr($CFG->wwwroot, 0, 5) !== 'https') {
413 $a = new stdClass;
414 $a->url = "$CFG->wwwroot/$CFG->admin/settings.php?section=httpsecurity";
415 notify(get_string('adminconfighttps', 'enrol_authorize', $a));
416 return; // notice breaks the form and xhtml later
418 elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
419 $wwwsroot = qualified_me();
420 $wwwsroot = str_replace('http:', 'https:', $wwwsroot);
421 $a = new stdClass;
422 $a->url = $wwwsroot;
423 notify(get_string('adminconfighttpsgo', 'enrol_authorize', $a));
424 return; // notice breaks the form and xhtml later
427 if (!empty($frm->an_review)) {
428 $captureday = intval($frm->an_capture_day);
429 $emailexpired = intval($frm->an_emailexpired);
430 if ($captureday > 0 || $emailexpired > 0) {
431 $lastcron = get_field_sql('SELECT max(lastcron) FROM ' . $CFG->prefix . 'modules');
432 if ((time() - intval($lastcron) > 3600 * 24)) {
433 notify(get_string('admincronsetup', 'enrol_authorize'));
438 if (($count = count_records('enrol_authorize', 'status', AN_STATUS_AUTH))) {
439 $a = new stdClass;
440 $a->count = $count;
441 $a->url = $CFG->wwwroot."/enrol/authorize/index.php?status=".AN_STATUS_AUTH;
442 notify(get_string('adminpendingorders', 'enrol_authorize', $a));
445 if (data_submitted()) {
446 if (empty($mconfig->an_login)) {
447 notify("an_login required");
449 if (empty($mconfig->an_tran_key) && empty($mconfig->an_password)) {
450 notify("an_tran_key or an_password required");
454 include($CFG->dirroot.'/enrol/authorize/config_form.php');
459 * process_config
461 * @param object $config
462 * @return bool true if it will be saved.
463 * @access public
465 function process_config($config)
467 global $CFG;
468 $mconfig = get_config('enrol/authorize');
470 // site settings
471 if (($cost = optional_param('enrol_cost', 5, PARAM_INT)) > 0) {
472 set_config('enrol_cost', $cost);
474 set_config('enrol_currency', optional_param('enrol_currency', 'USD', PARAM_ALPHA));
475 set_config('enrol_mailstudents', optional_param('enrol_mailstudents', 0, PARAM_BOOL));
476 set_config('enrol_mailteachers', optional_param('enrol_mailteachers', 0, PARAM_BOOL));
477 set_config('enrol_mailadmins', optional_param('enrol_mailadmins', 0, PARAM_BOOL));
479 // optional authorize.net settings
480 set_config('an_avs', optional_param('an_avs', 0, PARAM_BOOL));
481 set_config('an_authcode', optional_param('an_authcode', 0, PARAM_BOOL));
482 set_config('an_test', optional_param('an_test', 0, PARAM_BOOL));
483 set_config('an_referer', optional_param('an_referer', 'http://', PARAM_URL));
485 $acceptmethods = optional_param('acceptmethods', get_list_of_payment_methods(), PARAM_ALPHA);
486 set_config('an_acceptmethods', implode(',', $acceptmethods));
487 $acceptccs = optional_param('acceptccs', array_keys(get_list_of_creditcards()), PARAM_ALPHA);
488 set_config('an_acceptccs', implode(',', $acceptccs));
489 $acceptechecktypes = optional_param('acceptechecktypes', get_list_of_bank_account_types(), PARAM_ALPHA);
490 set_config('an_acceptechecktypes', implode(',', $acceptechecktypes));
492 $cutoff_hour = optional_param('an_cutoff_hour', 0, PARAM_INT);
493 $cutoff_min = optional_param('an_cutoff_min', 5, PARAM_INT);
494 set_config('an_cutoff', $cutoff_hour * 60 + $cutoff_min);
496 // cron depencies
497 $reviewval = optional_param('an_review', 0, PARAM_BOOL);
498 $captureday = optional_param('an_capture_day', 5, PARAM_INT);
499 $emailexpired = optional_param('an_emailexpired', 2, PARAM_INT);
500 $emailexpiredteacher = optional_param('an_emailexpiredteacher', 0, PARAM_BOOL);
501 $sorttype = optional_param('an_sorttype', 'ttl', PARAM_ALPHA);
503 $captureday = ($captureday > 29) ? 29 : (($captureday < 0) ? 0 : $captureday);
504 $emailexpired = ($emailexpired > 5) ? 5 : (($emailexpired < 0) ? 0 : $emailexpired);
506 if (!empty($reviewval) && ($captureday > 0 || $emailexpired > 0)) {
507 $lastcron = get_field_sql('SELECT max(lastcron) FROM ' . $CFG->prefix . 'modules');
508 if (time() - intval($lastcron) > 3600 * 24) {
509 return false;
513 set_config('an_review', $reviewval);
514 set_config('an_capture_day', $captureday);
515 set_config('an_emailexpired', $emailexpired);
516 set_config('an_emailexpiredteacher', $emailexpiredteacher);
517 set_config('an_sorttype', $sorttype);
519 // https and openssl library is required
520 if ((substr($CFG->wwwroot, 0, 5) !== 'https' and empty($CFG->loginhttps)) or !check_openssl_loaded()) {
521 return false;
524 // REQUIRED fields;
525 // an_login
526 $loginval = optional_param('an_login', '');
527 if (empty($loginval) && empty($mconfig->an_login)) {
528 return false;
530 $loginval = !empty($loginval) ? rc4encrypt($loginval) : strval($mconfig->an_login);
531 set_config('an_login', $loginval, 'enrol/authorize');
533 // an_tran_key, an_password
534 $tranval = optional_param('an_tran_key', '');
535 $tranval = !empty($tranval) ? rc4encrypt($tranval) : (isset($mconfig->an_tran_key)?$mconfig->an_tran_key:'');
536 $passwordval = optional_param('an_password', '');
537 $passwordval = !empty($passwordval) ? rc4encrypt($passwordval) :(isset($mconfig->an_password)?$mconfig->an_password:'');
538 $deletecurrent = optional_param('delete_current', '0', PARAM_BOOL);
539 if (!empty($deletecurrent) and !empty($tranval)) {
540 unset_config('an_password', 'enrol/authorize');
541 $passwordval = '';
543 elseif (!empty($passwordval)) {
544 set_config('an_password', $passwordval, 'enrol/authorize');
546 if (empty($tranval) and empty($passwordval)) {
547 return false;
549 if (!empty($tranval)) {
550 set_config('an_tran_key', $tranval, 'enrol/authorize');
553 return true;
557 * This function is run by admin/cron.php every time if admin has enabled this plugin.
559 * Everyday at settlement time (default is 00:05), it cleans up some tables
560 * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
562 * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
564 * @access public
566 function cron()
568 global $CFG;
569 require_once($CFG->dirroot.'/enrol/authorize/authorizenetlib.php');
571 $oneday = 86400;
572 $timenow = time();
573 $settlementtime = authorize_getsettletime($timenow);
574 $timediff30 = $settlementtime - (30 * $oneday);
575 $mconfig = get_config('enrol/authorize');
577 mtrace("Processing authorize cron...");
579 if (intval($mconfig->an_dailysettlement) < $settlementtime) {
580 set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
581 mtrace(" daily cron; some cleanups and sending email to admins the count of pending orders expiring", ": ");
582 $this->cron_daily();
583 mtrace("done");
586 mtrace(" scheduled capture", ": ");
587 if (empty($CFG->an_review) or (!empty($CFG->an_test)) or (intval($CFG->an_capture_day) < 1) or (!check_openssl_loaded())) {
588 mtrace("disabled");
589 return; // order review disabled or test mode or manual capture or openssl wasn't loaded.
592 $timediffcnf = $settlementtime - (intval($CFG->an_capture_day) * $oneday);
593 $select = "(status = '" .AN_STATUS_AUTH. "') AND (timecreated < '$timediffcnf') AND (timecreated > '$timediff30')";
594 if (!($ordercount = count_records_select('enrol_authorize', $select))) {
595 mtrace("no pending orders");
596 return;
599 $eachconn = intval($mconfig->an_eachconnsecs);
600 $eachconn = (($eachconn > 60) ? 60 : (($eachconn <= 0) ? 3 : $eachconn));
601 if (($ordercount * $eachconn) + intval($mconfig->an_lastcron) > $timenow) {
602 mtrace("blocked");
603 return;
605 set_config('an_lastcron', $timenow, 'enrol/authorize');
607 mtrace(" $ordercount orders are being processed now", ": ");
609 $faults = '';
610 $sendem = array();
611 $elapsed = time();
612 @set_time_limit(0);
613 $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
615 $lastcourseid = 0;
616 for ($rs = get_recordset_select('enrol_authorize', $select, 'courseid'); ($order = rs_fetch_next_record($rs)); )
618 $message = '';
619 $extra = NULL;
620 if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
621 if ($lastcourseid != $order->courseid) {
622 $lastcourseid = $order->courseid;
623 $course = get_record('course', 'id', $lastcourseid);
624 $role = get_default_course_role($course);
625 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
627 $timestart = $timeend = 0;
628 if ($course->enrolperiod) {
629 $timestart = $timenow;
630 $timeend = $order->settletime + $course->enrolperiod;
632 $user = get_record('user', 'id', $order->userid);
633 if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
634 $this->log .= "User($user->id) has been enrolled to course($course->id).\n";
635 if (!empty($CFG->enrol_mailstudents)) {
636 $sendem[] = $order->id;
639 else {
640 $faults .= "Error while trying to enrol ".fullname($user)." in '$course->fullname' \n";
641 foreach ($order as $okey => $ovalue) {
642 $faults .= " $okey = $ovalue\n";
646 else {
647 $this->log .= "Error, Order# $order->id: " . $message . "\n";
650 rs_close($rs);
651 mtrace("processed");
653 $timenow = time();
654 $elapsed = $timenow - $elapsed;
655 $eachconn = ceil($elapsed / $ordercount);
656 set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
658 $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
660 $adminuser = get_admin();
661 if (!empty($faults)) {
662 email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON FAULTS", $faults);
664 if (!empty($CFG->enrol_mailadmins)) {
665 email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON LOG", $this->log);
668 // Send emails to students about which courses have enrolled.
669 if (!empty($sendem)) {
670 mtrace(" sending welcome messages to students", ": ");
671 send_welcome_messages($sendem);
672 mtrace("sent");
677 * Daily cron. It executes at settlement time (default is 00:05).
679 * @access private
681 function cron_daily()
683 global $CFG, $SITE;
684 require_once($CFG->dirroot.'/enrol/authorize/authorizenetlib.php');
686 $oneday = 86400;
687 $timenow = time();
688 $onepass = $timenow - $oneday;
689 $settlementtime = authorize_getsettletime($timenow);
690 $timediff30 = $settlementtime - (30 * $oneday);
692 // Delete orders that no transaction was made.
693 $select = "(status='".AN_STATUS_NONE."') AND (timecreated<'$timediff30')";
694 delete_records_select('enrol_authorize', $select);
696 // Pending orders are expired with in 30 days.
697 $select = "(status='".AN_STATUS_AUTH."') AND (timecreated<'$timediff30')";
698 execute_sql("UPDATE {$CFG->prefix}enrol_authorize SET status='".AN_STATUS_EXPIRE."' WHERE $select", false);
700 // Delete expired orders 60 days later.
701 $timediff60 = $settlementtime - (60 * $oneday);
702 $select = "(status='".AN_STATUS_EXPIRE."') AND (timecreated<'$timediff60')";
703 delete_records_select('enrol_authorize', $select);
705 // XXX TODO SEND EMAIL to 'enrol/authorize:uploadcsv'
706 // get_users_by_capability() does not handling user level resolving
707 // After user resolving, get_admin() to get_users_by_capability()
708 $adminuser = get_admin();
709 $select = "status IN(".AN_STATUS_UNDERREVIEW.",".AN_STATUS_APPROVEDREVIEW.") AND (timecreated<'$onepass') AND (timecreated>'$timediff60')";
710 $count = count_records_select('enrol_authorize', $select);
711 if ($count) {
712 $a = new stdClass;
713 $a->count = $count;
714 $a->course = $SITE->shortname;
715 $subject = get_string('pendingechecksubject', 'enrol_authorize', $a);
716 $a = new stdClass;
717 $a->count = $count;
718 $a->url = $CFG->wwwroot.'/enrol/authorize/uploadcsv.php';
719 $message = get_string('pendingecheckemail', 'enrol_authorize', $a);
720 @email_to_user($adminuser, $adminuser, $subject, $message);
723 // Daily warning email for pending orders expiring.
724 if (empty($CFG->an_emailexpired)) {
725 return; // not enabled
728 // Pending orders count will be expired.
729 $timediffem = $settlementtime - ((30 - intval($CFG->an_emailexpired)) * $oneday);
730 $select = "(status='". AN_STATUS_AUTH ."') AND (timecreated<'$timediffem') AND (timecreated>'$timediff30')";
731 $count = count_records_select('enrol_authorize', $select);
732 if (!$count) {
733 return;
736 // Email to admin
737 $a = new stdClass;
738 $a->pending = $count;
739 $a->days = $CFG->an_emailexpired;
740 $a->course = $SITE->shortname;
741 $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
742 $a = new stdClass;
743 $a->pending = $count;
744 $a->days = $CFG->an_emailexpired;
745 $a->course = $SITE->fullname;
746 $a->enrolurl = "$CFG->wwwroot/$CFG->admin/enrol_config.php?enrol=authorize";
747 $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?status='.AN_STATUS_AUTH;
748 $message = get_string('pendingordersemail', 'enrol_authorize', $a);
749 email_to_user($adminuser, $adminuser, $subject, $message);
751 // Email to teachers
752 if (empty($CFG->an_emailexpiredteacher)) {
753 return; // email feature disabled for teachers.
756 $sorttype = empty($CFG->an_sorttype) ? 'ttl' : $CFG->an_sorttype;
757 $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,
758 COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl
759 FROM {$CFG->prefix}enrol_authorize e
760 INNER JOIN {$CFG->prefix}course c ON c.id = e.courseid
761 WHERE (e.status = ". AN_STATUS_AUTH .")
762 AND (e.timecreated < $timediffem)
763 AND (e.timecreated > $timediff30)
764 GROUP BY e.courseid
765 ORDER BY $sorttype DESC";
767 for ($rs = get_recordset_sql($sql); ($courseinfo = rs_fetch_next_record($rs)); )
769 $lastcourse = $courseinfo->courseid;
770 $context = get_context_instance(CONTEXT_COURSE, $lastcourse);
771 if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
772 $a = new stdClass;
773 $a->course = $courseinfo->shortname;
774 $a->pending = $courseinfo->cnt;
775 $a->days = $CFG->an_emailexpired;
776 $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
777 $a = new stdClass;
778 $a->course = $courseinfo->fullname;
779 $a->pending = $courseinfo->cnt;
780 $a->currency = $courseinfo->currency;
781 $a->sumcost = $courseinfo->ttl;
782 $a->days = $CFG->an_emailexpired;
783 $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?course='.$lastcourse.'&amp;status='.AN_STATUS_AUTH;
784 $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a);
785 foreach ($paymentmanagers as $paymentmanager) {
786 email_to_user($paymentmanager, $adminuser, $subject, $message);
790 rs_close($rs);