/**
 * Called from cron and update_instance. Not called from add_instance as the contexts are not set up yet.
 */
function qcreate_student_q_access_sync($qcreate, $cmcontext = null, $course = null, $forcesync = false)
{
    //check if a check is needed
    $timenow = time();
    $activityopen = ($qcreate->timeopen == 0 || $qcreate->timeopen < $timenow) && ($qcreate->timeclose == 0 || $qcreate->timeclose > $timenow);
    $activitywasopen = ($qcreate->timeopen == 0 || $qcreate->timeopen < $qcreate->timesync) && ($qcreate->timeclose == 0 || $qcreate->timeclose > $qcreate->timesync);
    $needsync = empty($qcreate->timesync) || $activitywasopen != $activityopen;
    if ($forcesync || $needsync) {
        if ($cmcontext == null) {
            $cm = get_coursemodule_from_instance('qcreate', $qcreate->id);
            $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
        }
        if ($course == null) {
            $course = get_record('course', 'id', $qcreate->course);
        }
        $studentrole = get_default_course_role($course);
        if ($activityopen) {
            $capabilitiestoassign = array(0 => array('moodle/question:add' => 1, 'moodle/question:usemine' => -1, 'moodle/question:viewmine' => -1, 'moodle/question:editmine' => -1), 1 => array('moodle/question:add' => 1, 'moodle/question:usemine' => 1, 'moodle/question:viewmine' => -1, 'moodle/question:editmine' => -1), 2 => array('moodle/question:add' => 1, 'moodle/question:usemine' => 1, 'moodle/question:viewmine' => 1, 'moodle/question:editmine' => -1), 3 => array('moodle/question:add' => 1, 'moodle/question:usemine' => 1, 'moodle/question:viewmine' => 1, 'moodle/question:editmine' => 1));
            foreach ($capabilitiestoassign[$qcreate->studentqaccess] as $capability => $permission) {
                assign_capability($capability, $permission, $studentrole->id, $cmcontext->id, true);
            }
        } else {
            $capabilitiestounassign = array('moodle/question:add', 'moodle/question:usemine', 'moodle/question:viewmine', 'moodle/question:editmine');
            foreach ($capabilitiestounassign as $capability) {
                unassign_capability($capability, $studentrole->id, $cmcontext->id);
            }
        }
        set_field('qcreate', 'timesync', $timenow, 'id', $qcreate->id);
    }
}
Exemplo n.º 2
0
 /**
  * This function is run by admin/cron.php every time if admin has enabled this plugin.
  *
  * Everyday at settlement time (default is 00:05), it cleans up some tables
  * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
  *
  * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
  *
  * @access public
  */
 function cron()
 {
     global $CFG;
     require_once $CFG->dirroot . '/enrol/authorize/authorizenetlib.php';
     $oneday = 86400;
     $timenow = time();
     $settlementtime = authorize_getsettletime($timenow);
     $timediff30 = $settlementtime - 30 * $oneday;
     $mconfig = get_config('enrol/authorize');
     mtrace("Processing authorize cron...");
     if (intval($mconfig->an_dailysettlement) < $settlementtime) {
         set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
         mtrace("    daily cron; some cleanups and sending email to admins the count of pending orders expiring", ": ");
         $this->cron_daily();
         mtrace("done");
     }
     mtrace("    scheduled capture", ": ");
     if (empty($CFG->an_review) or !empty($CFG->an_test) or intval($CFG->an_capture_day) < 1 or !check_openssl_loaded()) {
         mtrace("disabled");
         return;
         // order review disabled or test mode or manual capture or openssl wasn't loaded.
     }
     $timediffcnf = $settlementtime - intval($CFG->an_capture_day) * $oneday;
     $select = "(status = '" . AN_STATUS_AUTH . "') AND (timecreated < '{$timediffcnf}') AND (timecreated > '{$timediff30}')";
     if (!($ordercount = count_records_select('enrol_authorize', $select))) {
         mtrace("no pending orders");
         return;
     }
     $eachconn = intval($mconfig->an_eachconnsecs);
     $eachconn = $eachconn > 60 ? 60 : ($eachconn <= 0 ? 3 : $eachconn);
     if ($ordercount * $eachconn + intval($mconfig->an_lastcron) > $timenow) {
         mtrace("blocked");
         return;
     }
     set_config('an_lastcron', $timenow, 'enrol/authorize');
     mtrace("    {$ordercount} orders are being processed now", ": ");
     $faults = '';
     $sendem = array();
     $elapsed = time();
     @set_time_limit(0);
     $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
     $lastcourseid = 0;
     for ($rs = get_recordset_select('enrol_authorize', $select, 'courseid'); $order = rs_fetch_next_record($rs);) {
         $message = '';
         $extra = NULL;
         if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
             if ($lastcourseid != $order->courseid) {
                 $lastcourseid = $order->courseid;
                 $course = get_record('course', 'id', $lastcourseid);
                 $role = get_default_course_role($course);
                 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
             }
             $timestart = $timeend = 0;
             if ($course->enrolperiod) {
                 $timestart = $timenow;
                 $timeend = $order->settletime + $course->enrolperiod;
             }
             $user = get_record('user', 'id', $order->userid);
             if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
                 $this->log .= "User({$user->id}) has been enrolled to course({$course->id}).\n";
                 if (!empty($CFG->enrol_mailstudents)) {
                     $sendem[] = $order->id;
                 }
             } else {
                 $faults .= "Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                 foreach ($order as $okey => $ovalue) {
                     $faults .= "   {$okey} = {$ovalue}\n";
                 }
             }
         } else {
             $this->log .= "Error, Order# {$order->id}: " . $message . "\n";
         }
     }
     rs_close($rs);
     mtrace("processed");
     $timenow = time();
     $elapsed = $timenow - $elapsed;
     $eachconn = ceil($elapsed / $ordercount);
     set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
     $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
     $adminuser = get_admin();
     if (!empty($faults)) {
         email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON FAULTS", $faults);
     }
     if (!empty($CFG->enrol_mailadmins)) {
         email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON LOG", $this->log);
     }
     // Send emails to students about which courses have enrolled.
     if (!empty($sendem)) {
         mtrace("    sending welcome messages to students", ": ");
         send_welcome_messages($sendem);
         mtrace("sent");
     }
 }
Exemplo n.º 3
0
function authorize_process_csv($filename)
{
    global $CFG, $SITE, $DB;
    $plugin = enrol_get_plugin('authorize');
    /// We need these fields
    $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID');
    /// Open the file and get first line
    $handle = fopen($filename, "r");
    if (!$handle) {
        print_error('cannotopencsv');
    }
    $firstline = fgetcsv($handle, 8192, ",");
    $numfields = count($firstline);
    if ($numfields != 49 && $numfields != 70) {
        @fclose($handle);
        print_error('csvinvalidcolsnum');
    }
    /// Re-sort fields
    $csvfields = array();
    foreach ($myfields as $myfield) {
        $csvindex = array_search($myfield, $firstline);
        if ($csvindex === false) {
            $csvfields = array();
            break;
        }
        $csvfields[$myfield] = $csvindex;
    }
    if (empty($csvfields)) {
        @fclose($handle);
        print_error('csvinvalidcols');
    }
    /// Read lines
    $sendem = array();
    $ignoredlines = '';
    $imported = 0;
    $updated = 0;
    $ignored = 0;
    while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
        if (count($data) != $numfields) {
            $ignored++;
            // ignore empty lines
            continue;
        }
        $transid = $data[$csvfields['Transaction ID']];
        $transtype = $data[$csvfields['Transaction Type']];
        $transstatus = $data[$csvfields['Transaction Status']];
        $reftransid = $data[$csvfields['Reference Transaction ID']];
        $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
        if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
            if ($order = $DB->get_record('enrol_authorize', array('transid' => $transid))) {
                $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
                $DB->update_record('enrol_authorize', $order);
                $updated++;
                // Updated order status
            }
            continue;
        }
        if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
            if ($order = $DB->get_record('enrol_authorize', array('transid' => $reftransid))) {
                if (AN_METHOD_ECHECK == $order->paymentmethod) {
                    $refund = $DB->get_record('enrol_authorize_refunds', array('transid' => $transid));
                    if ($refund) {
                        $refund->status = AN_STATUS_CREDIT;
                        $refund->settletime = $settlementdate;
                        $DB->update_record('enrol_authorize_refunds', $refund);
                        $updated++;
                    } else {
                        $ignored++;
                        $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
                    }
                }
            } else {
                $ignored++;
                $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
            }
            continue;
        }
        if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
            $ignored++;
            $ignoredlines .= $transid . ": Not settled\n";
            continue;
        }
        // TransactionId must match
        $order = $DB->get_record('enrol_authorize', array('transid' => $transid));
        if (!$order) {
            $ignored++;
            $ignoredlines .= $transid . ": Not our business\n";
            continue;
        }
        // Authorized/Captured and Settled
        $order->status = AN_STATUS_AUTHCAPTURE;
        $order->settletime = $settlementdate;
        $DB->update_record('enrol_authorize', $order);
        $updated++;
        // Updated order status and settlement date
        if ($order->paymentmethod != AN_METHOD_ECHECK) {
            $ignored++;
            $ignoredlines .= $transid . ": The method must be echeck\n";
            continue;
        }
        // Get course and context
        $course = $DB->get_record('course', array('id' => $order->courseid));
        if (!$course) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
            continue;
        }
        $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
        if (!$coursecontext) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
            continue;
        }
        // Get user
        $user = $DB->get_record('user', array('id' => $order->userid));
        if (!$user) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this user: "******"\n";
            continue;
        }
        // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
        if ($role = get_default_course_role($course)) {
            if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
                $timestart = $timeend = 0;
                if ($course->enrolperiod) {
                    $timestart = time();
                    $timeend = $timestart + $course->enrolperiod;
                }
                // Enrol user
                $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid));
                $plugin->enrol_user($pinstance, $user->id, $pinstance->roleid, $timestart, $timeend);
                $imported++;
                if ($plugin->get_config('enrol_mailstudents')) {
                    $sendem[] = $order->id;
                }
            }
        }
    }
    fclose($handle);
    /// Send email to admin
    if (!empty($ignoredlines)) {
        $admin = get_admin();
        $eventdata = new stdClass();
        $eventdata->modulename = 'moodle';
        $eventdata->component = 'enrol_authorize';
        $eventdata->name = 'authorize_enrolment';
        $eventdata->userfrom = $admin;
        $eventdata->userto = $admin;
        $eventdata->subject = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))) . ': Authorize.net CSV ERROR LOG';
        $eventdata->fullmessage = $ignoredlines;
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml = '';
        $eventdata->smallmessage = '';
        message_send($eventdata);
    }
    /// Send welcome messages to users
    if (!empty($sendem)) {
        send_welcome_messages($sendem);
    }
    /// Show result
    notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}");
}
Exemplo n.º 4
0
/**
 * A convenience function to take care of the common case where you
 * just want to enrol someone using the default role into a course
 *
 * @param object $course
 * @param object $user
 * @param string $enrol - the plugin used to do this enrolment
 */
function enrol_into_course($course, $user, $enrol)
{
    $timestart = time();
    // remove time part from the timestamp and keep only the date part
    $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
    if ($course->enrolperiod) {
        $timeend = $timestart + $course->enrolperiod;
    } else {
        $timeend = 0;
    }
    if ($role = get_default_course_role($course)) {
        $context = get_context_instance(CONTEXT_COURSE, $course->id);
        if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
            return false;
        }
        // force accessdata refresh for users visiting this context...
        mark_context_dirty($context->path);
        email_welcome_message_to_user($course, $user);
        add_to_log($course->id, 'course', 'enrol', 'view.php?id=' . $course->id, $course->id);
        return true;
    }
    return false;
}
Exemplo n.º 5
0
 /**
  * sync enrolments with database, create courses if required.
  *
  * @param object The role to sync for. If no role is specified, defaults are
  * used.
  */
 function sync_enrolments($role = null)
 {
     global $CFG;
     global $db;
     error_reporting(E_ALL);
     // Connect to the external database
     $enroldb = $this->enrol_connect();
     if (!$enroldb) {
         notify("enrol/database cannot connect to server");
         return false;
     }
     if (isset($role)) {
         echo '=== Syncing enrolments for role: ' . $role->shortname . " ===\n";
     } else {
         echo "=== Syncing enrolments for default role ===\n";
     }
     // first, pack the sortorder...
     fix_course_sortorder();
     list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
     if (!$have_role) {
         if (!empty($CFG->enrol_db_defaultcourseroleid) and $role = get_record('role', 'id', $CFG->enrol_db_defaultcourseroleid)) {
             echo "=== Using enrol_db_defaultcourseroleid: {$role->id} ({$role->shortname}) ===\n";
         } elseif (isset($role)) {
             echo "!!! WARNING: Role specified by caller, but no (or invalid) role configuration !!!\n";
         }
     }
     // get enrolments per-course
     $sql = "SELECT DISTINCT {$CFG->enrol_remotecoursefield} " . " FROM {$CFG->enrol_dbtable} " . " WHERE {$CFG->enrol_remoteuserfield} IS NOT NULL" . (isset($remote_role_name, $remote_role_value) ? ' AND ' . $remote_role_name . ' = ' . $remote_role_value : '');
     $rs = $enroldb->Execute($sql);
     if (!$rs) {
         trigger_error($enroldb->ErrorMsg() . ' STATEMENT: ' . $sql);
         return false;
     }
     if ($rs->EOF) {
         // no courses! outta here...
         return true;
     }
     begin_sql();
     $extcourses = array();
     while ($extcourse_obj = rs_fetch_next_record($rs)) {
         // there are more course records
         $extcourse_obj = (object) array_change_key_case((array) $extcourse_obj, CASE_LOWER);
         $extcourse = $extcourse_obj->{strtolower($CFG->enrol_remotecoursefield)};
         array_push($extcourses, $extcourse);
         // does the course exist in moodle already?
         $course = false;
         $course = get_record('course', $CFG->enrol_localcoursefield, $extcourse);
         if (!is_object($course)) {
             if (empty($CFG->enrol_db_autocreate)) {
                 // autocreation not allowed
                 if (debugging('', DEBUG_ALL)) {
                     error_log("Course {$extcourse} does not exist, skipping");
                 }
                 continue;
                 // next foreach course
             }
             // ok, now then let's create it!
             // prepare any course properties we actually have
             $course = new StdClass();
             $course->{$CFG->enrol_localcoursefield} = $extcourse;
             $course->fullname = $extcourse;
             $course->shortname = $extcourse;
             if (!($newcourseid = $this->create_course($course, true) and $course = get_record('course', 'id', $newcourseid))) {
                 error_log("Creating course {$extcourse} failed");
                 continue;
                 // nothing left to do...
             }
         }
         $context = get_context_instance(CONTEXT_COURSE, $course->id);
         // If we don't have a proper role setup, then we default to the default
         // role for the current course.
         if (!$have_role) {
             $role = get_default_course_role($course);
         }
         // get a list of the student ids the are enrolled
         // in the external db -- hopefully it'll fit in memory...
         $extenrolments = array();
         $sql = "SELECT {$CFG->enrol_remoteuserfield} " . " FROM {$CFG->enrol_dbtable} " . " WHERE {$CFG->enrol_remotecoursefield} = " . $enroldb->quote($extcourse) . ($have_role ? ' AND ' . $remote_role_name . ' = ' . $remote_role_value : '');
         $crs = $enroldb->Execute($sql);
         if (!$crs) {
             trigger_error($enroldb->ErrorMsg() . ' STATEMENT: ' . $sql);
             return false;
         }
         if ($crs->EOF) {
             // shouldn't happen, but cover all bases
             continue;
         }
         // slurp results into an array
         while ($crs_obj = rs_fetch_next_record($crs)) {
             $crs_obj = (object) array_change_key_case((array) $crs_obj, CASE_LOWER);
             array_push($extenrolments, $crs_obj->{strtolower($CFG->enrol_remoteuserfield)});
         }
         rs_close($crs);
         // release the handle
         //
         // prune enrolments to users that are no longer in ext auth
         // hopefully they'll fit in the max buffer size for the RDBMS
         //
         // TODO: This doesn't work perfectly.  If we are operating without
         // roles in the external DB, then this doesn't handle changes of role
         // within a course (because the user is still enrolled in the course,
         // so NOT IN misses the course).
         //
         // When the user logs in though, their role list will be updated
         // correctly.
         //
         if (!$CFG->enrol_db_disableunenrol) {
             $to_prune = get_records_sql("\n             SELECT ra.*\n             FROM {$CFG->prefix}role_assignments ra\n              JOIN {$CFG->prefix}user u ON ra.userid = u.id\n             WHERE ra.enrol = 'database'\n              AND ra.contextid = {$context->id}\n              AND ra.roleid = " . $role->id . ($extenrolments ? " AND u.{$CFG->enrol_localuserfield} NOT IN (" . join(", ", array_map(array(&$db, 'quote'), $extenrolments)) . ")" : ''));
             if ($to_prune) {
                 foreach ($to_prune as $role_assignment) {
                     if (role_unassign($role->id, $role_assignment->userid, 0, $role_assignment->contextid)) {
                         error_log("Unassigned {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
                     } else {
                         error_log("Failed to unassign {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
                     }
                 }
             }
         }
         //
         // insert current enrolments
         // bad we can't do INSERT IGNORE with postgres...
         //
         foreach ($extenrolments as $member) {
             // Get the user id and whether is enrolled in one fell swoop
             $sql = "\n                SELECT u.id AS userid, ra.id AS enrolmentid\n                FROM {$CFG->prefix}user u\n                 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid\n                  AND ra.roleid = {$role->id}\n                  AND ra.contextid = {$context->id}\n                 WHERE u.{$CFG->enrol_localuserfield} = " . $db->quote($member) . " AND (u.deleted IS NULL OR u.deleted=0) ";
             $ers = $db->Execute($sql);
             if (!$ers) {
                 trigger_error($db->ErrorMsg() . ' STATEMENT: ' . $sql);
                 return false;
             }
             if ($ers->EOF) {
                 // if this returns empty, it means we don't have the student record.
                 // should not happen -- but skip it anyway
                 trigger_error('weird! no user record entry?');
                 continue;
             }
             $user_obj = rs_fetch_record($ers);
             $userid = $user_obj->userid;
             $enrolmentid = $user_obj->enrolmentid;
             rs_close($ers);
             // release the handle
             if ($enrolmentid) {
                 // already enrolled - skip
                 continue;
             }
             if (role_assign($role->id, $userid, 0, $context->id, 0, 0, 0, 'database')) {
                 error_log("Assigned role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
             } else {
                 error_log("Failed to assign role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
             }
         }
         // end foreach member
     }
     // end while course records
     rs_close($rs);
     //Close the main course recordset
     //
     // prune enrolments to courses that are no longer in ext auth
     //
     // TODO: This doesn't work perfectly.  If we are operating without
     // roles in the external DB, then this doesn't handle changes of role
     // within a course (because the user is still enrolled in the course,
     // so NOT IN misses the course).
     //
     // When the user logs in though, their role list will be updated
     // correctly.
     //
     if (!$CFG->enrol_db_disableunenrol) {
         $sql = "\n            SELECT ra.roleid, ra.userid, ra.contextid\n            FROM {$CFG->prefix}role_assignments ra\n                JOIN {$CFG->prefix}context cn ON cn.id = ra.contextid\n                JOIN {$CFG->prefix}course c ON c.id = cn.instanceid\n            WHERE ra.enrol = 'database'\n              AND cn.contextlevel = " . CONTEXT_COURSE . " " . ($have_role ? ' AND ra.roleid = ' . $role->id : '') . ($extcourses ? " AND c.{$CFG->enrol_localcoursefield} NOT IN (" . join(",", array_map(array(&$db, 'quote'), $extcourses)) . ")" : '');
         $ers = $db->Execute($sql);
         if (!$ers) {
             trigger_error($db->ErrorMsg() . ' STATEMENT: ' . $sql);
             return false;
         }
         if (!$ers->EOF) {
             while ($user_obj = rs_fetch_next_record($ers)) {
                 $user_obj = (object) array_change_key_case((array) $user_obj, CASE_LOWER);
                 $roleid = $user_obj->roleid;
                 $user = $user_obj->userid;
                 $contextid = $user_obj->contextid;
                 if (role_unassign($roleid, $user, 0, $contextid)) {
                     error_log("Unassigned role {$roleid} from user {$user} in context {$contextid}");
                 } else {
                     error_log("Failed unassign role {$roleid} from user {$user} in context {$contextid}");
                 }
             }
             rs_close($ers);
             // release the handle
         }
     }
     commit_sql();
     // we are done now, a bit of housekeeping
     fix_course_sortorder();
     $this->enrol_disconnect($enroldb);
     return true;
 }
Exemplo n.º 6
0
 /**
  * This function is run by admin/cron.php every time if admin has enabled this plugin.
  *
  * Everyday at settlement time (default is 00:05), it cleans up some tables
  * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled.
  *
  * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students.
  *
  * @access public
  */
 public function cron()
 {
     global $CFG, $DB;
     $oneday = 86400;
     $timenow = time();
     $settlementtime = AuthorizeNet::getsettletime($timenow);
     $timediff30 = $settlementtime - 30 * $oneday;
     $mconfig = get_config('enrol/authorize');
     mtrace("Processing authorize cron...");
     if (intval($mconfig->an_dailysettlement) < $settlementtime) {
         set_config('an_dailysettlement', $settlementtime, 'enrol/authorize');
         mtrace("    Daily cron:");
         $this->cron_daily();
         mtrace("    Done");
     }
     mtrace("    Scheduled capture", ": ");
     if (empty($CFG->an_review) or !empty($CFG->an_test) or intval($CFG->an_capture_day) < 1 or !check_curl_available()) {
         mtrace("disabled");
         return;
         // order review disabled or test mode or manual capture or openssl wasn't loaded.
     }
     $timediffcnf = $settlementtime - intval($CFG->an_capture_day) * $oneday;
     $select = "(status = ?) AND (timecreated < ?) AND (timecreated > ?)";
     $params = array(AN_STATUS_AUTH, $timediffcnf, $timediff30);
     if (!($ordercount = $DB->count_records_select('enrol_authorize', $select, $params))) {
         mtrace("no pending orders");
         return;
     }
     $eachconn = intval($mconfig->an_eachconnsecs);
     $eachconn = $eachconn > 60 ? 60 : ($eachconn <= 0 ? 3 : $eachconn);
     if ($ordercount * $eachconn + intval($mconfig->an_lastcron) > $timenow) {
         mtrace("blocked");
         return;
     }
     set_config('an_lastcron', $timenow, 'enrol/authorize');
     mtrace("    {$ordercount} orders are being processed now", ": ");
     $faults = '';
     $sendem = array();
     $elapsed = time();
     @set_time_limit(0);
     $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n";
     $lastcourseid = 0;
     $rs = $DB->get_recordset_select('enrol_authorize', $select, $params, 'courseid');
     foreach ($rs as $order) {
         $message = '';
         $extra = NULL;
         if (AN_APPROVED == AuthorizeNet::process($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) {
             if ($lastcourseid != $order->courseid) {
                 $lastcourseid = $order->courseid;
                 $course = $DB->get_record('course', array('id' => $lastcourseid));
                 $role = get_default_course_role($course);
                 $context = get_context_instance(CONTEXT_COURSE, $lastcourseid);
             }
             $timestart = $timeend = 0;
             if ($course->enrolperiod) {
                 $timestart = $timenow;
                 $timeend = $order->settletime + $course->enrolperiod;
             }
             $user = $DB->get_record('user', array('id' => $order->userid));
             if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
                 $this->log .= "User({$user->id}) has been enrolled to course({$course->id}).\n";
                 if (!empty($CFG->enrol_mailstudents)) {
                     $sendem[] = $order->id;
                 }
             } else {
                 $faults .= "Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                 foreach ($order as $okey => $ovalue) {
                     $faults .= "   {$okey} = {$ovalue}\n";
                 }
             }
         } else {
             $this->log .= "Error, Order# {$order->id}: " . $message . "\n";
         }
     }
     $rs->close();
     mtrace("processed");
     $timenow = time();
     $elapsed = $timenow - $elapsed;
     $eachconn = ceil($elapsed / $ordercount);
     set_config('an_eachconnsecs', $eachconn, 'enrol/authorize');
     $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow);
     $adminuser = get_admin();
     if (!empty($faults)) {
         $eventdata = new object();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $adminuser;
         $eventdata->userto = $adminuser;
         $eventdata->subject = "AUTHORIZE.NET CRON FAULTS";
         $eventdata->fullmessage = $faults;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         events_trigger('message_send', $eventdata);
     }
     if (!empty($CFG->enrol_mailadmins)) {
         $eventdata = new object();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $adminuser;
         $eventdata->userto = $adminuser;
         $eventdata->subject = "AUTHORIZE.NET CRON LOG";
         $eventdata->fullmessage = $this->log;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         events_trigger('message_send', $eventdata);
     }
     // Send emails to students about which courses have enrolled.
     if (!empty($sendem)) {
         mtrace("    sending welcome messages to students", ": ");
         send_welcome_messages($sendem);
         mtrace("sent");
     }
 }
Exemplo n.º 7
0
function authorize_process_csv($filename)
{
    global $CFG, $SITE;
    /// We need these fields
    $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID');
    /// Open the file and get first line
    $handle = fopen($filename, "r");
    if (!$handle) {
        error('CANNOT OPEN CSV FILE');
    }
    $firstline = fgetcsv($handle, 8192, ",");
    $numfields = count($firstline);
    if ($numfields != 49 && $numfields != 70) {
        @fclose($handle);
        error('INVALID CSV FILE; Each line must include 49 or 70 fields');
    }
    /// Re-sort fields
    $csvfields = array();
    foreach ($myfields as $myfield) {
        $csvindex = array_search($myfield, $firstline);
        if ($csvindex === false) {
            $csvfields = array();
            break;
        }
        $csvfields[$myfield] = $csvindex;
    }
    if (empty($csvfields)) {
        @fclose($handle);
        error("<b>INVALID CSV FILE:</b> First line must include 'Header Fields' and\n               the file must be type of <br />'Expanded Fields/Comma Separated'<br />or<br />\n              'Expanded Fields with CAVV Result Code/Comma Separated'");
    }
    /// Read lines
    $sendem = array();
    $ignoredlines = '';
    $imported = 0;
    $updated = 0;
    $ignored = 0;
    while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
        if (count($data) != $numfields) {
            $ignored++;
            // ignore empty lines
            continue;
        }
        $transid = $data[$csvfields['Transaction ID']];
        $transtype = $data[$csvfields['Transaction Type']];
        $transstatus = $data[$csvfields['Transaction Status']];
        $reftransid = $data[$csvfields['Reference Transaction ID']];
        $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]);
        if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') {
            if ($order = get_record('enrol_authorize', 'transid', $transid)) {
                $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED;
                update_record('enrol_authorize', $order);
                $updated++;
                // Updated order status
            }
            continue;
        }
        if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) {
            if ($order = get_record('enrol_authorize', 'transid', $reftransid)) {
                if (AN_METHOD_ECHECK == $order->paymentmethod) {
                    $refund = get_record('enrol_authorize_refunds', 'transid', $transid);
                    if ($refund) {
                        $refund->status = AN_STATUS_CREDIT;
                        $refund->settletime = $settlementdate;
                        update_record('enrol_authorize_refunds', $refund);
                        $updated++;
                    } else {
                        $ignored++;
                        $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n";
                    }
                }
            } else {
                $ignored++;
                $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n";
            }
            continue;
        }
        if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) {
            $ignored++;
            $ignoredlines .= $transid . ": Not settled\n";
            continue;
        }
        // TransactionId must match
        $order = get_record('enrol_authorize', 'transid', $transid);
        if (!$order) {
            $ignored++;
            $ignoredlines .= $transid . ": Not our business\n";
            continue;
        }
        // Authorized/Captured and Settled
        $order->status = AN_STATUS_AUTHCAPTURE;
        $order->settletime = $settlementdate;
        update_record('enrol_authorize', $order);
        $updated++;
        // Updated order status and settlement date
        if ($order->paymentmethod != AN_METHOD_ECHECK) {
            $ignored++;
            $ignoredlines .= $transid . ": The method must be echeck\n";
            continue;
        }
        // Get course and context
        $course = get_record('course', 'id', $order->courseid);
        if (!$course) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n";
            continue;
        }
        $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
        if (!$coursecontext) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n";
            continue;
        }
        // Get user
        $user = get_record('user', 'id', $order->userid);
        if (!$user) {
            $ignored++;
            $ignoredlines .= $transid . ": Could not find this user: "******"\n";
            continue;
        }
        // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again.
        if ($role = get_default_course_role($course)) {
            if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) {
                $timestart = $timeend = 0;
                if ($course->enrolperiod) {
                    $timestart = time();
                    $timeend = $timestart + $course->enrolperiod;
                }
                if (role_assign($role->id, $user->id, 0, $coursecontext->id, $timestart, $timeend, 0, 'authorize')) {
                    $imported++;
                    if (!empty($CFG->enrol_mailstudents)) {
                        $sendem[] = $order->id;
                    }
                } else {
                    $ignoredlines .= $transid . ": Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n";
                }
            }
        }
    }
    fclose($handle);
    /// Send email to admin
    if (!empty($ignoredlines)) {
        $admin = get_admin();
        email_to_user($admin, $admin, "{$SITE->fullname}: Authorize.net CSV ERROR LOG", $ignoredlines);
    }
    /// Send welcome messages to users
    if (!empty($sendem)) {
        send_welcome_messages($sendem);
    }
    /// Show result
    notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}");
}
Exemplo n.º 8
0
 /**
  * Perform all necessary tasks to add a student enrolment to the system.
  *
  * @param array $checks what checks to perform before adding enrolling the
  * user.  e.g. array('prereq' => 1, 'waitlist' => 1) will check that
  * prerequisites are satisfied, and that the class is not full
  * @param boolean $notify whether or not notifications should be sent if a
  * check fails
  */
 function add($checks = array(), $notify = false)
 {
     global $CURMAN, $CFG, $USER;
     $status = true;
     if ($CURMAN->db->record_exists(STUTABLE, 'userid', $this->userid, 'classid', $this->classid)) {
         // already enrolled -- pretend we succeeded
         return true;
     }
     // check that the student can be enrolled first
     if (!empty($checks['prereq'])) {
         // check prerequisites
         $cmclass = new cmclass($this->classid);
         // get all the curricula that the user is in
         $curricula = curriculumstudent::get_curricula($this->userid);
         foreach ($curricula as $curriculum) {
             $curcrs = new curriculumcourse();
             $curcrs->courseid = $cmclass->courseid;
             $curcrs->curriculumid = $curriculum->curid;
             if (!$curcrs->prerequisites_satisfied($this->userid)) {
                 // prerequisites not satisfied
                 if ($notify) {
                     $data = new stdClass();
                     $data->userid = $this->userid;
                     $data->classid = $this->classid;
                     //$data->trackid = $trackid;
                     events_trigger('crlm_prereq_unsatisfied', $data);
                 }
                 $status = new Object();
                 $status->message = get_string('unsatisfiedprereqs', 'block_curr_admin');
                 $status->code = 'unsatisfiedprereqs';
                 return $status;
             }
         }
     }
     if (!empty($checks['waitlist'])) {
         // check class enrolment limit
         $cmclass = new cmclass($this->classid);
         $limit = $cmclass->maxstudents;
         if (!empty($limit) && $limit <= student::count_enroled($this->classid)) {
             // class is full
             // put student on wait list
             $wait_list = new waitlist($this);
             $wait_list->timecreated = time();
             $wait_list->position = 0;
             $wait_list->add();
             if ($notify) {
                 $subject = get_string('user_waitlisted', 'block_curr_admin');
                 $a = new object();
                 $a->user = $this->user->idnumber;
                 $a->cmclass = $cmclass->idnumber;
                 $message = get_string('user_waitlisted_msg', 'block_curr_admin', $a);
                 $from = $user = get_admin();
                 notification::notify($message, $user, $from);
                 email_to_user($user, $from, $subject, $message);
             }
             $status = new Object();
             $status->message = get_string('user_waitlisted', 'block_curr_admin');
             $status->code = 'user_waitlisted';
             return $status;
         }
     }
     //set end time based on class duration
     $studentclass = new cmclass($this->classid);
     if (empty($this->endtime)) {
         if (isset($studentclass->duration) && $studentclass->duration) {
             $this->endtime = $this->enrolmenttime + $studentclass->duration;
         } else {
             // no class duration -> no end time
             $this->endtime = 0;
         }
     }
     $status = $this->data_insert_record();
     // TBD: we should check this!
     /// Get the Moodle user ID or create a new account for this user.
     if (!($muserid = cm_get_moodleuserid($this->userid))) {
         $user = new user($this->userid);
         if (!($muserid = $user->synchronize_moodle_user(true, true))) {
             $status = new Object();
             $status->message = get_string('errorsynchronizeuser', 'block_curr_admin');
             $muserid = false;
         }
     }
     /// Enrol them into the Moodle class.
     if ($moodlecourseid = moodle_get_course($this->classid)) {
         if ($mcourse = get_record('course', 'id', $moodlecourseid)) {
             $enrol = $mcourse->enrol;
             if (!$enrol) {
                 $enrol = $CFG->enrol;
             }
             if ($CURMAN->config->restrict_to_elis_enrolment_plugin && $enrol != 'elis') {
                 $status = new Object();
                 $status->message = get_string('error_not_using_elis_enrolment', 'block_curr_admin');
                 return $status;
             }
             $timestart = $this->enrolmenttime;
             $timeend = $this->endtime;
             if ($role = get_default_course_role($mcourse)) {
                 $context = get_context_instance(CONTEXT_COURSE, $mcourse->id);
                 if (!empty($muserid)) {
                     if (!role_assign($role->id, $muserid, 0, $context->id, $timestart, $timeend, 0, 'manual')) {
                         $status = new Object();
                         $status->message = get_string('errorroleassign', 'block_curr_admin');
                     }
                 }
             }
         }
     } else {
         if (!empty($muserid)) {
             $sturole = $CURMAN->config->enrolment_role_sync_student_role;
             // ELIS-2776: must still trigger events for notifications
             $ra = new stdClass();
             $ra->roleid = !empty($sturole) ? $sturole : get_field('role', 'id', 'shortname', 'student');
             $ra->contextid = context_level_base::get_custom_context_level('class', 'block_curr_admin');
             // TBD
             $ra->userid = $muserid;
             $ra->component = '';
             // TBD: 'enrol_elis'
             $ra->itemid = $this->classid;
             // TBD
             $ra->timemodified = time();
             $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
             events_trigger('role_assigned', $ra);
         }
     }
     return $status;
 }
 /**
  * Enrol the students associated with the class into the attached Moodle
  * course.
  *
  * @param none
  * @return bool True on success, False otherwise.
  */
 function data_enrol_students()
 {
     if (empty($this->classid) || empty($this->moodlecourseid) || !empty($this->siteconfig) && !file_exists($this->siteconfig)) {
         return false;
     }
     $stu = new student();
     if ($students = $stu->get_students($this->classid)) {
         /// At this point we must switch over the other Moodle site's DB config, if needed
         if (!empty($this->siteconfig)) {
             $cfgbak = moodle_load_config($this->siteconfig);
         }
         /// This has to be put here in case we have a site config reload.
         $CFG = $GLOBALS['CFG'];
         $CURMAN = $GLOBALS['CURMAN'];
         $db = $GLOBALS['db'];
         $role = get_default_course_role($this->moodlecourseid);
         if (!($context = get_context_instance(CONTEXT_COURSE, $this->moodlecourseid))) {
             return false;
         }
         foreach ($students as $student) {
             /// Make sure that a Moodle account exists for this user already.
             $user = new user($student->id);
             if (!($muser = $CURMAN->db->get_record('user', 'idnumber', addslashes($user->idnumber)))) {
                 $muser = addslashes_recursive($muser);
                 /// Create a new record.
                 $muser = new stdClass();
                 $muser->idnumber = $user->idnumber;
                 $muser->username = $user->uname;
                 $muser->passwword = $user->passwd;
                 $muser->firstname = $user->firstname;
                 $muser->lastname = $user->lastname;
                 $muser->auth = 'manual';
                 $muser->timemodified = time();
                 $muser->id = $CURMAN->db->insert_record('user', $muser);
             }
             /// If we have a vald Moodle user account, apply the role.
             if (!empty($muser->id)) {
                 role_assign($role->id, $muser->id, 0, $context->id, 0, 0, 0, 'manual');
             }
         }
         /// Reset $CFG object.
         if (!empty($this->siteconfig)) {
             moodle_load_config($cfgbak->dirroot . '/config.php');
         }
     }
     return true;
 }
/**
 * This function is called when a 'user_created' event is triggered, and hopefully every time a new user
 * is created. It will assign the defined user to the configured role at the front page level, so that
 * the user can be added to site groups.
 *
 *  @param object $eventdata The user object created.
 *  @return boolean Always return true so that the event gets cleared.
 *
 */
function fn_user_created_handler($eventdata)
{
    global $CFG;
    /// If we aren't using site groups, do nothing.
    if (empty($CFG->block_fn_site_groups_enabled)) {
        return true;
    }
    /// If no specific role has been configured, use the default role for a course in the user policies.
    if (empty($CFG->block_fn_site_groups_defaultroleid)) {
        $course = get_site();
        $role = get_default_course_role($course);
        $defaultroleid = $role->id;
    } else {
        $defaultroleid = $CFG->block_fn_site_groups_defaultroleid;
    }
    /// If the role is empty, there's nothing else we can do.
    if (!empty($defaultroleid)) {
        $context = get_context_instance(CONTEXT_COURSE, SITEID);
        role_assign($defaultroleid, $eventdata->id, false, $context->id);
    }
    return true;
}
    notice_yesno($confmsg, 'index.php', $return, $optionsyes, NULL, 'post', 'get');
    admin_externalpage_print_footer();
    die;
}
// action confirmed, perform it
if ($confirm) {
    if (empty($SESSION->bulk_courses)) {
        redirect($return);
    }
    // for each course, get the default role if needed and check the selected group
    foreach ($SESSION->bulk_courses as $course) {
        $context = get_context_instance(CONTEXT_COURSE, $course);
        $in = implode(',', $SESSION->bulk_users);
        $groupid = false;
        if ($roleassign == 0) {
            $defrole = get_default_course_role($context);
            $roleassign = $defrole->id;
        }
        if (!empty($groupname)) {
            $groupid = groups_get_group_by_name($course, stripslashes($groupname));
        }
        // for each user, enrol them to the course with the selected role,
        // and add to the selected group if available
        if ($rs = get_recordset_select('user', "id IN ({$in})")) {
            while ($user = rs_fetch_next_record($rs)) {
                role_assign($roleassign, $user->id, 0, $context->id, 0, 0, $hidden);
                if ($groupid !== false) {
                    groups_add_member($groupid, $user->id);
                }
            }
        }
    assign_capability('block/fn_site_groups:managegroups', CAP_ALLOW, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:managegroupmembers', CAP_ALLOW, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:managestudents', CAP_ALLOW, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:markallgroups', CAP_ALLOW, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:assignallusers', CAP_INHERIT, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:assignowngroupusers', CAP_ALLOW, $gmroleid, $context->id);
    assign_capability('block/fn_site_groups:createnewgroups', CAP_ALLOW, $gmroleid, $context->id);
} else {
    $gmroleid = $role->id;
}
$roles = get_records_menu('role', '', '', 'sortorder ASC', 'id,name');
if (empty($roles)) {
    $roles = array();
}
$course = get_site();
$role = get_default_course_role($course);
$defaultroleid = $role->id;
$item = new admin_setting_configcheckbox('block_fn_site_groups_enabled', get_string('fn_site_groups_enabled', 'block_fn_site_groups'), get_string('fn_config_site_groups_enabled', 'block_fn_site_groups'), '0');
$item->set_updatedcallback('fn_sg_set_site_group_mode');
$settings->add($item);
$settings->add(new admin_setting_configselect('block_fn_site_groups_defaultroleid', get_string('fn_site_groups_defaultroleid', 'block_fn_site_groups'), get_string('fn_config_site_groups_defaultroleid', 'block_fn_site_groups'), $defaultroleid, $roles));
$settings->add(new admin_setting_configmulticheckbox('block_fn_site_groups_roles', get_string('fn_site_groups_roles', 'block_fn_site_groups'), get_string('fn_config_site_groups_roles', 'block_fn_site_groups'), '0', $roles));
/// These settings don't actually use the $CFG variable, but are used to manage capabilities.
$caps = role_context_capabilities($gmroleid, $context);
$sgusers = array();
if (!empty($caps['block/fn_site_groups:assignowngroupusers'])) {
    $sgusers[] = 1;
}
if (!empty($caps['block/fn_site_groups:assignallusers'])) {
    $sgusers[] = 2;
}
Exemplo n.º 13
0
/**
 * A convenience function to take care of the common case where you
 * just want to enrol someone using the default role into a course
 *
 * @param object $course
 * @param object $user
 * @param string $enrol - the plugin used to do this enrolment
 */
function enrol_into_course($course, $user, $enrol)
{
    if ($course->enrolperiod) {
        $timestart = time();
        $timeend = time() + $course->enrolperiod;
    } else {
        $timestart = $timeend = 0;
    }
    if ($role = get_default_course_role($course)) {
        $context = get_context_instance(CONTEXT_COURSE, $course->id);
        if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
            return false;
        }
        email_welcome_message_to_user($course, $user);
        add_to_log($course->id, 'course', 'enrol', 'view.php?id=' . $course->id, $user->id);
        return true;
    }
    return false;
}