Added check for <text> fields that contain markup (an error!)
[moodle-linuxchix.git] / enrol / authorize / enrol.php
blob7732f85754af1ddff5c3018e4c97bf9e88e95032
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 error(get_string('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 $revieworder = false;
201 $action = AN_ACTION_AUTH_CAPTURE;
203 if (!empty($CFG->an_authcode) && !empty($form->ccauthcode)) {
204 $action = AN_ACTION_CAPTURE_ONLY;
205 $extra->x_auth_code = $form->ccauthcode;
207 elseif (!empty($CFG->an_review)) {
208 $revieworder = true;
209 $action = AN_ACTION_AUTH_ONLY;
212 $message = '';
213 if (AN_APPROVED != authorize_action($order, $message, $extra, $action, $form->cctype)) {
214 email_to_admin($message, $order);
215 return $message;
218 $SESSION->ccpaid = 1; // security check: don't duplicate payment
219 if ($order->transid == 0) { // TEST MODE
220 if ($revieworder) {
221 redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
223 else {
224 enrol_into_course($course, $USER, 'authorize');
225 redirect("$CFG->wwwroot/course/view.php?id=$course->id");
227 return;
230 if ($revieworder) { // review enabled, inform payment managers and redirect the user who have paid to main page.
231 $a = new stdClass;
232 $a->url = "$CFG->wwwroot/enrol/authorize/index.php?order=$order->id";
233 $a->orderid = $order->id;
234 $a->transid = $order->transid;
235 $a->amount = "$order->currency $order->amount";
236 $a->expireon = userdate(authorize_getsettletime($timenow + (30 * 3600 * 24)));
237 $a->captureon = userdate(authorize_getsettletime($timenow + (intval($CFG->an_capture_day) * 3600 * 24)));
238 $a->course = $course->fullname;
239 $a->user = fullname($USER);
240 $a->acstatus = ($CFG->an_capture_day > 0) ? get_string('yes') : get_string('no');
241 $emailmessage = get_string('adminneworder', 'enrol_authorize', $a);
242 $a = new stdClass;
243 $a->course = $course->shortname;
244 $a->orderid = $order->id;
245 $emailsubject = get_string('adminnewordersubject', 'enrol_authorize', $a);
246 $context = get_context_instance(CONTEXT_COURSE, $course->id);
247 if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
248 foreach ($paymentmanagers as $paymentmanager) {
249 email_to_user($paymentmanager, $USER, $emailsubject, $emailmessage);
252 redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
253 return;
256 // Credit card captured, ENROL student now...
257 if (enrol_into_course($course, $USER, 'authorize')) {
258 if (!empty($CFG->enrol_mailstudents)) {
259 send_welcome_messages($order->id);
261 if (!empty($CFG->enrol_mailteachers)) {
262 $context = get_context_instance(CONTEXT_COURSE, $course->id);
263 $paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments', '', '', '0', '1');
264 $paymentmanager = array_shift($paymentmanagers);
265 $a = new stdClass;
266 $a->course = "$course->fullname";
267 $a->user = fullname($USER);
268 email_to_user($paymentmanager,
269 $USER,
270 get_string("enrolmentnew", '', format_string($course->shortname)),
271 get_string('enrolmentnewuser', '', $a));
273 if (!empty($CFG->enrol_mailadmins)) {
274 $a = new stdClass;
275 $a->course = "$course->fullname";
276 $a->user = fullname($USER);
277 $admins = get_admins();
278 foreach ($admins as $admin) {
279 email_to_user($admin,
280 $USER,
281 get_string("enrolmentnew", '', format_string($course->shortname)),
282 get_string('enrolmentnewuser', '', $a));
285 } else {
286 email_to_admin("Error while trying to enrol " . fullname($USER) . " in '$course->fullname'", $order);
289 if ($SESSION->wantsurl) {
290 $destination = $SESSION->wantsurl; unset($SESSION->wantsurl);
291 } else {
292 $destination = "$CFG->wwwroot/course/view.php?id=$course->id";
294 load_all_capabilities();
295 redirect($destination, get_string('paymentthanks', 'moodle', $course->fullname), 10);
300 * The user submitted echeck form.
302 * @param object $form Form parameters
303 * @param object $course Course info
304 * @access private
306 function echeck_submit($form, $course)
308 global $CFG, $USER, $SESSION;
309 require_once('authorizenetlib.php');
311 prevent_double_paid($course);
313 $useripno = getremoteaddr();
314 $curcost = get_course_cost($course);
315 $isbusinesschecking = ($form->acctype == 'BUSINESSCHECKING');
317 // NEW ECHECK ORDER
318 $timenow = time();
319 $order = new stdClass();
320 $order->paymentmethod = AN_METHOD_ECHECK;
321 $order->refundinfo = $isbusinesschecking ? 1 : 0;
322 $order->ccname = $form->firstname . ' ' . $form->lastname;
323 $order->courseid = $course->id;
324 $order->userid = $USER->id;
325 $order->status = AN_STATUS_NONE; // it will be changed...
326 $order->settletime = 0; // cron changes this.
327 $order->transid = 0; // Transaction Id
328 $order->timecreated = $timenow;
329 $order->amount = $curcost['cost'];
330 $order->currency = $curcost['currency'];
331 $order->id = insert_record("enrol_authorize", $order);
332 if (!$order->id) {
333 email_to_admin("Error while trying to insert new data", $order);
334 return "Insert record error. Admin has been notified!";
337 $extra = new stdClass();
338 $extra->x_bank_aba_code = $form->abacode;
339 $extra->x_bank_acct_num = $form->accnum;
340 $extra->x_bank_acct_type = $form->acctype;
341 $extra->x_echeck_type = $isbusinesschecking ? 'CCD' : 'WEB';
342 $extra->x_bank_name = $form->bankname;
343 $extra->x_currency_code = $curcost['currency'];
344 $extra->x_amount = $curcost['cost'];
345 $extra->x_first_name = $form->firstname;
346 $extra->x_last_name = $form->lastname;
347 $extra->x_country = $USER->country;
348 $extra->x_address = $USER->address;
349 $extra->x_city = $USER->city;
350 $extra->x_state = '';
351 $extra->x_zip = '';
353 $extra->x_invoice_num = $order->id;
354 $extra->x_description = $course->shortname;
356 $extra->x_cust_id = $USER->id;
357 $extra->x_email = $USER->email;
358 $extra->x_customer_ip = $useripno;
359 $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE';
360 $extra->x_phone = '';
361 $extra->x_fax = '';
363 $message = '';
364 if (AN_REVIEW != authorize_action($order, $message, $extra, AN_ACTION_AUTH_CAPTURE)) {
365 email_to_admin($message, $order);
366 return $message;
369 $SESSION->ccpaid = 1; // security check: don't duplicate payment
370 redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30');
375 * Gets access icons.
377 * @param object $course
378 * @return string
379 * @access public
381 function get_access_icons($course) {
383 $manual = enrolment_factory::factory('manual');
384 $str = $manual->get_access_icons($course);
385 $curcost = get_course_cost($course);
387 if (abs($curcost['cost']) > 0.00) {
388 $strrequirespayment = get_string("requirespayment");
389 $strcost = get_string("cost");
390 $currency = $curcost['currency'];
392 switch ($currency) {
393 case 'USD': $currency = 'US$'; break;
394 case 'CAD': $currency = 'C$'; break;
395 case 'EUR': $currency = '&euro;'; break;
396 case 'GBP': $currency = '&pound;'; break;
397 case 'JPY': $currency = '&yen;'; break;
400 $str .= '<div class="cost" title="'.$strrequirespayment.'">'.$strcost.': ';
401 $str .= $currency . ' ' . $curcost['cost'].'</div>';
404 return $str;
409 * Shows config form & errors
411 * @param object $frm
412 * @access public
414 function config_form($frm)
416 global $CFG;
417 $mconfig = get_config('enrol/authorize');
419 if (!check_openssl_loaded()) {
420 notify('PHP must be compiled with SSL support (--with-openssl)');
423 if (empty($CFG->loginhttps) and substr($CFG->wwwroot, 0, 5) !== 'https') {
424 $a = new stdClass;
425 $a->url = "$CFG->wwwroot/$CFG->admin/settings.php?section=httpsecurity";
426 notify(get_string('adminconfighttps', 'enrol_authorize', $a));
427 return; // notice breaks the form and xhtml later
429 elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 443) { // MDL-9836
430 $wwwsroot = qualified_me();
431 $wwwsroot = str_replace('http:', 'https:', $wwwsroot);
432 $a = new stdClass;
433 $a->url = $wwwsroot;
434 notify(get_string('adminconfighttpsgo', 'enrol_authorize', $a));
435 return; // notice breaks the form and xhtml later
438 if (!empty($frm->an_review)) {
439 $captureday = intval($frm->an_capture_day);
440 $emailexpired = intval($frm->an_emailexpired);
441 if ($captureday > 0 || $emailexpired > 0) {
442 if ((time() - intval($mconfig->an_lastcron) > 3600 * 24)) {
443 notify(get_string('admincronsetup', 'enrol_authorize'));
448 if (($count = count_records('enrol_authorize', 'status', AN_STATUS_AUTH))) {
449 $a = new stdClass;
450 $a->count = $count;
451 $a->url = $CFG->wwwroot."/enrol/authorize/index.php?status=".AN_STATUS_AUTH;
452 notify(get_string('adminpendingorders', 'enrol_authorize', $a));
455 if (data_submitted()) {
456 if (empty($mconfig->an_login)) {
457 notify("an_login required");
459 if (empty($mconfig->an_tran_key) && empty($mconfig->an_password)) {
460 notify("an_tran_key or an_password required");
464 include($CFG->dirroot.'/enrol/authorize/config_form.php');
469 * process_config
471 * @param object $config
472 * @return bool true if it will be saved.
473 * @access public
475 function process_config($config)
477 global $CFG;
478 $mconfig = get_config('enrol/authorize');
480 // site settings
481 if (($cost = optional_param('enrol_cost', 5, PARAM_INT)) > 0) {
482 set_config('enrol_cost', $cost);
484 set_config('enrol_currency', optional_param('enrol_currency', 'USD', PARAM_ALPHA));
485 set_config('enrol_mailstudents', optional_param('enrol_mailstudents', 0, PARAM_BOOL));
486 set_config('enrol_mailteachers', optional_param('enrol_mailteachers', 0, PARAM_BOOL));
487 set_config('enrol_mailadmins', optional_param('enrol_mailadmins', 0, PARAM_BOOL));
489 // optional authorize.net settings
490 set_config('an_avs', optional_param('an_avs', 0, PARAM_BOOL));
491 set_config('an_authcode', optional_param('an_authcode', 0, PARAM_BOOL));
492 set_config('an_test', optional_param('an_test', 0, PARAM_BOOL));
493 set_config('an_referer', optional_param('an_referer', 'http://', PARAM_URL));
495 $acceptmethods = optional_param('acceptmethods', get_list_of_payment_methods(), PARAM_ALPHA);
496 set_config('an_acceptmethods', implode(',', $acceptmethods));
497 $acceptccs = optional_param('acceptccs', array_keys(get_list_of_creditcards()), PARAM_ALPHA);
498 set_config('an_acceptccs', implode(',', $acceptccs));
499 $acceptechecktypes = optional_param('acceptechecktypes', get_list_of_bank_account_types(), PARAM_ALPHA);
500 set_config('an_acceptechecktypes', implode(',', $acceptechecktypes));
502 $cutoff_hour = optional_param('an_cutoff_hour', 0, PARAM_INT);
503 $cutoff_min = optional_param('an_cutoff_min', 5, PARAM_INT);
504 set_config('an_cutoff', $cutoff_hour * 60 + $cutoff_min);
506 // cron depencies
507 $reviewval = optional_param('an_review', 0, PARAM_BOOL);
508 $captureday = optional_param('an_capture_day', 5, PARAM_INT);
509 $emailexpired = optional_param('an_emailexpired', 2, PARAM_INT);
510 $emailexpiredteacher = optional_param('an_emailexpiredteacher', 0, PARAM_BOOL);
511 $sorttype = optional_param('an_sorttype', 'ttl', PARAM_ALPHA);
513 $captureday = ($captureday > 29) ? 29 : (($captureday < 0) ? 0 : $captureday);
514 $emailexpired = ($emailexpired > 5) ? 5 : (($emailexpired < 0) ? 0 : $emailexpired);
516 if (!empty($reviewval) && ($captureday > 0 || $emailexpired > 0)) {
517 if (time() - intval($mconfig->an_lastcron) > 3600 * 24) {
518 return false;
522 set_config('an_review', $reviewval);
523 set_config('an_capture_day', $captureday);
524 set_config('an_emailexpired', $emailexpired);
525 set_config('an_emailexpiredteacher', $emailexpiredteacher);
526 set_config('an_sorttype', $sorttype);
528 // https and openssl library is required
529 if ((substr($CFG->wwwroot, 0, 5) !== 'https' and empty($CFG->loginhttps)) or !check_openssl_loaded()) {
530 return false;
533 // REQUIRED fields;
534 // an_login
535 $loginval = optional_param('an_login', '');
536 if (empty($loginval) && empty($mconfig->an_login)) {
537 return false;
539 $loginval = !empty($loginval) ? rc4encrypt($loginval) : strval($mconfig->an_login);
540 set_config('an_login', $loginval, 'enrol/authorize');
542 // an_tran_key, an_password
543 $tranval = optional_param('an_tran_key', '');
544 $tranval = !empty($tranval) ? rc4encrypt($tranval) : (isset($mconfig->an_tran_key)?$mconfig->an_tran_key:'');
545 $passwordval = optional_param('an_password', '');
546 $passwordval = !empty($passwordval) ? rc4encrypt($passwordval) :(isset($mconfig->an_password)?$mconfig->an_password:'');
547 $deletecurrent = optional_param('delete_current', '0', PARAM_BOOL);
548 if (!empty($deletecurrent) and !empty($tranval)) {
549 unset_config('an_password', 'enrol/authorize');
550 $passwordval = '';
552 elseif (!empty($passwordval)) {
553 set_config('an_password', $passwordval, 'enrol/authorize');
555 if (empty($tranval) and empty($passwordval)) {
556 return false;
558 if (!empty($tranval)) {
559 set_config('an_tran_key', $tranval, 'enrol/authorize');
562 return true;
566 * This function is run by admin/cron.php every time if admin has enabled this plugin.
568 * Everyday at settlement time (default is 00:05), it cleans up some tables
569 * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
571 * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
573 * @access public
575 function cron()
577 global $CFG;
578 require_once($CFG->dirroot.'/enrol/authorize/authorizenetlib.php');
580 $oneday = 86400;
581 $timenow = time();
582 $settlementtime = authorize_getsettletime($timenow);
583 $timediff30 = $settlementtime - (30 * $oneday);
584 $mconfig = get_config('enrol/authorize');
585 set_config('an_lastcron', $timenow, 'enrol/authorize');
587 mtrace("Processing authorize cron...");
589 if (intval($mconfig->an_dailysettlement) < $settlementtime) {
590 set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
591 mtrace(" daily cron; some cleanups and sending email to admins the count of pending orders expiring", ": ");
592 $this->cron_daily();
593 mtrace("done");
596 mtrace(" scheduled capture", ": ");
597 if (empty($CFG->an_review) or (!empty($CFG->an_test)) or (intval($CFG->an_capture_day) < 1) or (!check_openssl_loaded())) {
598 mtrace("disabled");
599 return; // order review disabled or test mode or manual capture or openssl wasn't loaded.
602 $timediffcnf = $settlementtime - (intval($CFG->an_capture_day) * $oneday);
603 $sql = "SELECT * FROM {$CFG->prefix}enrol_authorize
604 WHERE (status = '" .AN_STATUS_AUTH. "')
605 AND (timecreated < '$timediffcnf')
606 AND (timecreated > '$timediff30')
607 ORDER BY courseid";
609 if (!$orders = get_records_sql($sql)) {
610 mtrace("no pending orders");
611 return;
614 $eachconn = intval($mconfig->an_eachconnsecs);
615 if (empty($eachconn)) $eachconn = 3;
616 elseif ($eachconn > 60) $eachconn = 60;
618 $ordercount = count((array)$orders);
619 if (($ordercount * $eachconn) + intval($mconfig->an_lastcron) > $timenow) {
620 mtrace("blocked");
621 return;
624 mtrace(" $ordercount orders are being processed now", ": ");
626 $faults = '';
627 $sendem = array();
628 $elapsed = time();
629 @set_time_limit(0);
630 $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
632 $lastcourseid = 0;
633 foreach ($orders as $order) {
634 $message = '';
635 $extra = NULL;
636 if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
637 if ($lastcourseid != $order->courseid) {
638 $lastcourseid = $order->courseid;
639 $course = get_record('course', 'id', $lastcourseid);
640 $role = get_default_course_role($course);
641 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
643 $timestart = $timeend = 0;
644 if ($course->enrolperiod) {
645 $timestart = $timenow;
646 $timeend = $order->settletime + $course->enrolperiod;
648 $user = get_record('user', 'id', $order->userid);
649 if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
650 $this->log .= "User($user->id) has been enrolled to course($course->id).\n";
651 if (!empty($CFG->enrol_mailstudents)) {
652 $sendem[] = $order->id;
655 else {
656 $faults .= "Error while trying to enrol ".fullname($user)." in '$course->fullname' \n";
657 foreach ($order as $okey => $ovalue) {
658 $faults .= " $okey = $ovalue\n";
662 else {
663 $this->log .= "Error, Order# $order->id: " . $message . "\n";
667 mtrace("processed");
669 $timenow = time();
670 $elapsed = $timenow - $elapsed;
671 $eachconn = ceil($elapsed / $ordercount);
672 set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
674 $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
676 $adminuser = get_admin();
677 if (!empty($faults)) {
678 email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON FAULTS", $faults);
680 if (!empty($CFG->enrol_mailadmins)) {
681 email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON LOG", $this->log);
684 // Send emails to students about which courses have enrolled.
685 if (!empty($sendem)) {
686 mtrace(" sending welcome messages to students", ": ");
687 send_welcome_messages($sendem);
688 mtrace("sent");
693 * Daily cron. It executes at settlement time (default is 00:05).
695 * @access private
697 function cron_daily()
699 global $CFG, $SITE;
700 require_once($CFG->dirroot.'/enrol/authorize/authorizenetlib.php');
702 $oneday = 86400;
703 $timenow = time();
704 $onepass = $timenow - $oneday;
705 $settlementtime = authorize_getsettletime($timenow);
706 $timediff30 = $settlementtime - (30 * $oneday);
708 // Delete orders that no transaction was made.
709 $select = "(status='".AN_STATUS_NONE."') AND (timecreated<'$timediff30')";
710 delete_records_select('enrol_authorize', $select);
712 // Pending orders are expired with in 30 days.
713 $select = "(status='".AN_STATUS_AUTH."') AND (timecreated<'$timediff30')";
714 execute_sql("UPDATE {$CFG->prefix}enrol_authorize SET status='".AN_STATUS_EXPIRE."' WHERE $select", false);
716 // Delete expired orders 60 days later.
717 $timediff60 = $settlementtime - (60 * $oneday);
718 $select = "(status='".AN_STATUS_EXPIRE."') AND (timecreated<'$timediff60')";
719 delete_records_select('enrol_authorize', $select);
721 // XXX TODO SEND EMAIL to 'enrol/authorize:uploadcsv'
722 // get_users_by_capability() does not handling user level resolving
723 // After user resolving, get_admin() to get_users_by_capability()
724 $adminuser = get_admin();
725 $select = "status IN(".AN_STATUS_UNDERREVIEW.",".AN_STATUS_APPROVEDREVIEW.") AND (timecreated<'$onepass') AND (timecreated>'$timediff60')";
726 $count = count_records_select('enrol_authorize', $select);
727 if ($count) {
728 $a = new stdClass;
729 $a->count = $count;
730 $a->course = $SITE->shortname;
731 $subject = get_string('pendingechecksubject', 'enrol_authorize', $a);
732 $a = new stdClass;
733 $a->count = $count;
734 $a->url = $CFG->wwwroot.'/enrol/authorize/uploadcsv.php';
735 $message = get_string('pendingecheckemail', 'enrol_authorize', $a);
736 @email_to_user($adminuser, $adminuser, $subject, $message);
739 // Daily warning email for pending orders expiring.
740 if (empty($CFG->an_emailexpired)) {
741 return; // not enabled
744 // Pending orders count will be expired.
745 $timediffem = $settlementtime - ((30 - intval($CFG->an_emailexpired)) * $oneday);
746 $select = "(status='". AN_STATUS_AUTH ."') AND (timecreated<'$timediffem') AND (timecreated>'$timediff30')";
747 $count = count_records_select('enrol_authorize', $select);
748 if (!$count) {
749 return;
752 // Email to admin
753 $a = new stdClass;
754 $a->pending = $count;
755 $a->days = $CFG->an_emailexpired;
756 $a->course = $SITE->shortname;
757 $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
758 $a = new stdClass;
759 $a->pending = $count;
760 $a->days = $CFG->an_emailexpired;
761 $a->course = $SITE->fullname;
762 $a->enrolurl = "$CFG->wwwroot/$CFG->admin/enrol_config.php?enrol=authorize";
763 $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?status='.AN_STATUS_AUTH;
764 $message = get_string('pendingordersemail', 'enrol_authorize', $a);
765 email_to_user($adminuser, $adminuser, $subject, $message);
767 // Email to teachers
768 if (empty($CFG->an_emailexpiredteacher)) {
769 return; // email feature disabled for teachers.
772 $sorttype = empty($CFG->an_sorttype) ? 'ttl' : $CFG->an_sorttype;
773 $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,
774 COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl
775 FROM {$CFG->prefix}enrol_authorize e
776 INNER JOIN {$CFG->prefix}course c ON c.id = e.courseid
777 WHERE (e.status = ". AN_STATUS_AUTH .")
778 AND (e.timecreated < $timediffem)
779 AND (e.timecreated > $timediff30)
780 GROUP BY e.courseid
781 ORDER BY $sorttype DESC";
783 $courseinfos = get_records_sql($sql);
784 foreach($courseinfos as $courseinfo) {
785 $lastcourse = $courseinfo->courseid;
786 $context = get_context_instance(CONTEXT_COURSE, $lastcourse);
787 if (($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments'))) {
788 $a = new stdClass;
789 $a->course = $courseinfo->shortname;
790 $a->pending = $courseinfo->cnt;
791 $a->days = $CFG->an_emailexpired;
792 $subject = get_string('pendingorderssubject', 'enrol_authorize', $a);
793 $a = new stdClass;
794 $a->course = $courseinfo->fullname;
795 $a->pending = $courseinfo->cnt;
796 $a->currency = $courseinfo->currency;
797 $a->sumcost = $courseinfo->ttl;
798 $a->days = $CFG->an_emailexpired;
799 $a->url = $CFG->wwwroot.'/enrol/authorize/index.php?course='.$lastcourse.'&amp;status='.AN_STATUS_AUTH;
800 $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a);
801 foreach ($paymentmanagers as $paymentmanager) {
802 email_to_user($paymentmanager, $adminuser, $subject, $message);