/**
  * Gets a blank course with 2 teachers and 10 students ready for each test.
  */
 protected function setUp()
 {
     global $PAGE, $DB;
     // First test will set up DB submissions, so we keep it hanging around for the others.
     $this->resetAfterTest();
     // Make a course.
     $generator = $this->getDataGenerator();
     $this->course = $generator->create_course();
     $this->setAdminUser();
     $PAGE->set_course($this->course);
     $manager = new course_enrolment_manager($PAGE, $this->course);
     $plugins = $manager->get_enrolment_plugins();
     $instances = $manager->get_enrolment_instances();
     /* @var enrol_manual_plugin $manualenrolplugin */
     $manualenrolplugin = reset($plugins);
     $manualenrolinstance = reset($instances);
     $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
     $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'teacher'));
     // Make some students.
     for ($i = 0; $i < 10; $i++) {
         $student = $generator->create_user();
         $this->students[$student->id] = $student;
         $manualenrolplugin->enrol_user($manualenrolinstance, $student->id, $studentroleid);
     }
     // Make a couple of teachers.
     $teacher1 = $generator->create_user();
     $this->teachers[$teacher1->id] = $teacher1;
     $manualenrolplugin->enrol_user($manualenrolinstance, $teacher1->id, $teacherroleid);
     $teacher2 = $generator->create_user();
     $this->teachers[$teacher2->id] = $teacher2;
     $manualenrolplugin->enrol_user($manualenrolinstance, $teacher2->id, $teacherroleid);
 }
Esempio n. 2
0
 /**
  * Returns a button to manually enrol users through the manual enrolment plugin.
  *
  * By default the first manual enrolment plugin instance available in the course is used.
  * If no manual enrolment instances exist within the course then false is returned.
  *
  * This function also adds a quickenrolment JS ui to the page so that users can be enrolled
  * via AJAX.
  *
  * @param course_enrolment_manager $manager
  * @return enrol_user_button
  */
 public function get_manual_enrol_button(course_enrolment_manager $manager)
 {
     global $CFG;
     $instance = null;
     $instances = array();
     foreach ($manager->get_enrolment_instances() as $tempinstance) {
         if ($tempinstance->enrol == 'manual') {
             if ($instance === null) {
                 $instance = $tempinstance;
             }
             $instances[] = array('id' => $tempinstance->id, 'name' => $this->get_instance_name($tempinstance));
         }
     }
     if (empty($instance)) {
         return false;
     }
     if (!($manuallink = $this->get_manual_enrol_link($instance))) {
         return false;
     }
     $button = new enrol_user_button($manuallink, get_string('enrolusers', 'enrol_manual'), 'get');
     $button->class .= ' enrol_manual_plugin';
     $startdate = $manager->get_course()->startdate;
     $startdateoptions = array();
     $timeformat = get_string('strftimedatefullshort');
     if ($startdate > 0) {
         $startdateoptions[2] = get_string('coursestart') . ' (' . userdate($startdate, $timeformat) . ')';
     }
     $today = time();
     $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
     $startdateoptions[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')';
     $defaultduration = $instance->enrolperiod > 0 ? $instance->enrolperiod / 86400 : '';
     $modules = array('moodle-enrol_manual-quickenrolment', 'moodle-enrol_manual-quickenrolment-skin');
     $arguments = array('instances' => $instances, 'courseid' => $instance->courseid, 'ajaxurl' => '/enrol/manual/ajax.php', 'url' => $manager->get_moodlepage()->url->out(false), 'optionsStartDate' => $startdateoptions, 'defaultRole' => $instance->roleid, 'defaultDuration' => $defaultduration, 'disableGradeHistory' => $CFG->disablegradehistory, 'recoverGradesDefault' => '');
     if ($CFG->recovergradesdefault) {
         $arguments['recoverGradesDefault'] = ' checked="checked"';
     }
     $function = 'M.enrol_manual.quickenrolment.init';
     $button->require_yui_module($modules, $function, array($arguments));
     $button->strings_for_js(array('ajaxoneuserfound', 'ajaxxusersfound', 'ajaxnext25', 'enrol', 'enrolmentoptions', 'enrolusers', 'errajaxfailedenrol', 'errajaxsearch', 'none', 'usersearch', 'unlimitedduration', 'startdatetoday', 'durationdays', 'enrolperiod', 'finishenrollingusers', 'recovergrades'), 'enrol');
     $button->strings_for_js('assignroles', 'role');
     $button->strings_for_js('startingfrom', 'moodle');
     return $button;
 }
Esempio n. 3
0
 /**
  * Returns a button to manually enrol users through the manual enrolment plugin.
  *
  * By default the first manual enrolment plugin instance available in the course is used.
  * If no manual enrolment instances exist within the course then false is returned.
  *
  * This function also adds a quickenrolment JS ui to the page so that users can be enrolled
  * via AJAX.
  *
  * @param course_enrolment_manager $manager
  * @return enrol_user_button
  */
 public function get_manual_enrol_button(course_enrolment_manager $manager)
 {
     global $CFG;
     require_once $CFG->dirroot . '/cohort/lib.php';
     $instance = null;
     $instances = array();
     foreach ($manager->get_enrolment_instances() as $tempinstance) {
         if ($tempinstance->enrol == 'manual') {
             if ($instance === null) {
                 $instance = $tempinstance;
             }
             $instances[] = array('id' => $tempinstance->id, 'name' => $this->get_instance_name($tempinstance));
         }
     }
     if (empty($instance)) {
         return false;
     }
     if (!($manuallink = $this->get_manual_enrol_link($instance))) {
         return false;
     }
     $button = new enrol_user_button($manuallink, get_string('enrolusers', 'enrol_manual'), 'get');
     $button->class .= ' enrol_manual_plugin';
     $startdate = $manager->get_course()->startdate;
     if (!($defaultstart = get_config('enrol_manual', 'enrolstart'))) {
         // Default to now if there is no system setting.
         $defaultstart = 4;
     }
     $startdateoptions = array();
     $dateformat = get_string('strftimedatefullshort');
     if ($startdate > 0) {
         $startdateoptions[2] = get_string('coursestart') . ' (' . userdate($startdate, $dateformat) . ')';
     }
     $now = time();
     $today = make_timestamp(date('Y', $now), date('m', $now), date('d', $now), 0, 0, 0);
     $startdateoptions[3] = get_string('today') . ' (' . userdate($today, $dateformat) . ')';
     $startdateoptions[4] = get_string('now', 'enrol_manual') . ' (' . userdate($now, get_string('strftimedatetimeshort')) . ')';
     $defaultduration = $instance->enrolperiod > 0 ? $instance->enrolperiod / 86400 : '';
     $modules = array('moodle-enrol_manual-quickenrolment', 'moodle-enrol_manual-quickenrolment-skin');
     $arguments = array('instances' => $instances, 'courseid' => $instance->courseid, 'ajaxurl' => '/enrol/manual/ajax.php', 'url' => $manager->get_moodlepage()->url->out(false), 'optionsStartDate' => $startdateoptions, 'defaultRole' => $instance->roleid, 'defaultDuration' => $defaultduration, 'defaultStartDate' => (int) $defaultstart, 'disableGradeHistory' => $CFG->disablegradehistory, 'recoverGradesDefault' => '', 'cohortsAvailable' => cohort_get_available_cohorts($manager->get_context(), COHORT_WITH_NOTENROLLED_MEMBERS_ONLY, 0, 1) ? true : false);
     if ($CFG->recovergradesdefault) {
         $arguments['recoverGradesDefault'] = ' checked="checked"';
     }
     $function = 'M.enrol_manual.quickenrolment.init';
     $button->require_yui_module($modules, $function, array($arguments));
     $button->strings_for_js(array('ajaxoneuserfound', 'ajaxxusersfound', 'ajaxnext25', 'enrol', 'enrolmentoptions', 'enrolusers', 'enrolxusers', 'errajaxfailedenrol', 'errajaxsearch', 'foundxcohorts', 'none', 'usersearch', 'unlimitedduration', 'startdatetoday', 'durationdays', 'enrolperiod', 'finishenrollingusers', 'recovergrades'), 'enrol');
     $button->strings_for_js(array('browseusers', 'browsecohorts'), 'enrol_manual');
     $button->strings_for_js('assignroles', 'role');
     $button->strings_for_js('startingfrom', 'moodle');
     return $button;
 }
Esempio n. 4
0
/**
 * Gets cohorts the user is able to view.
 *
 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
 *
 * @global moodle_database $DB
 * @param course_enrolment_manager $manager
 * @param int $offset limit output from
 * @param int $limit items to output per load
 * @param string $search search string
 * @return array    Array(more => bool, offset => int, cohorts => array)
 */
function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '')
{
    global $CFG;
    debugging('enrol_cohort_search_cohorts() is deprecated. This functionality is moved to enrol_manual.', DEBUG_DEVELOPER);
    require_once $CFG->dirroot . '/cohort/lib.php';
    $context = $manager->get_context();
    $cohorts = array();
    $instances = $manager->get_enrolment_instances();
    $enrolled = array();
    foreach ($instances as $instance) {
        if ($instance->enrol === 'cohort') {
            $enrolled[] = $instance->customint1;
        }
    }
    $rawcohorts = cohort_get_available_cohorts($context, COHORT_COUNT_MEMBERS, $offset, $limit, $search);
    // Produce the output respecting parameters.
    foreach ($rawcohorts as $c) {
        $cohorts[$c->id] = array('cohortid' => $c->id, 'name' => shorten_text(format_string($c->name, true, array('context' => context::instance_by_id($c->contextid))), 35), 'users' => $c->memberscnt, 'enrolled' => in_array($c->id, $enrolled));
    }
    return array('more' => !(bool) $limit, 'offset' => $offset, 'cohorts' => $cohorts);
}
Esempio n. 5
0
         $timestart = $course->startdate;
         break;
     case 3:
     default:
         $today = time();
         $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
         $timestart = $today;
         break;
 }
 if ($duration <= 0) {
     $timeend = 0;
 } else {
     $timeend = $timestart + $duration * 24 * 60 * 60;
 }
 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
 $instances = $manager->get_enrolment_instances();
 $plugins = $manager->get_enrolment_plugins(true);
 // Do not allow actions on disabled plugins.
 if (!array_key_exists($enrolid, $instances)) {
     throw new enrol_ajax_exception('invalidenrolinstance');
 }
 $instance = $instances[$enrolid];
 if (!isset($plugins[$instance->enrol])) {
     throw new enrol_ajax_exception('enrolnotpermitted');
 }
 $plugin = $plugins[$instance->enrol];
 if ($plugin->allow_enrol($instance) && has_capability('enrol/' . $plugin->get_name() . ':enrol', $context)) {
     $plugin->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
     if ($recovergrades) {
         require_once $CFG->libdir . '/gradelib.php';
         grade_recover_history_grades($user->id, $instance->courseid);
Esempio n. 6
0
 /**
  * Return the invitation instance for a specific course.
  *
  * Note: as using $PAGE variable, this function can only be called in a
  * Moodle script page.
  *
  * @param int $courseid
  * @param boolean $mustexist when set, an exception is thrown if no instance is found
  * @return object
  */
 public function get_invitation_instance($courseid, $mustexist = false)
 {
     global $PAGE, $CFG, $DB;
     if ($courseid == $this->courseid and !empty($this->enrolinstance)) {
         return $this->enrolinstance;
     }
     // Find enrolment instance.
     $instance = null;
     require_once "{$CFG->dirroot}/enrol/locallib.php";
     $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
     $manager = new course_enrolment_manager($PAGE, $course);
     foreach ($manager->get_enrolment_instances() as $tempinstance) {
         if ($tempinstance->enrol == 'invitation') {
             if ($instance === null) {
                 $instance = $tempinstance;
             }
         }
     }
     if ($mustexist and empty($instance)) {
         throw new moodle_exception('noinvitationinstanceset', 'enrol_invitation');
     }
     return $instance;
 }
Esempio n. 7
0
 function enrol_user($username, $course_id, $roleid = 5, $timestart = 0, $timeend = 0)
 {
     global $CFG, $DB, $PAGE;
     $username = utf8_decode($username);
     $username = strtolower($username);
     /* Create the user before if it is not created yet */
     $conditions = array('username' => $username);
     $user = $DB->get_record('user', $conditions);
     if (!$user) {
         $this->create_joomdle_user($username);
     }
     $user = $DB->get_record('user', $conditions);
     $conditions = array('id' => $course_id);
     $course = $DB->get_record('course', $conditions);
     if (!$course) {
         return 0;
     }
     // Get enrol start and end dates of manual enrolment plugin
     if ($CFG->version >= 2011061700) {
         $manager = new course_enrolment_manager($PAGE, $course);
     } else {
         $manager = new course_enrolment_manager($course);
     }
     $instances = $manager->get_enrolment_instances();
     $plugins = $manager->get_enrolment_plugins();
     $enrolid = 1;
     //manual
     if (!$timestart) {
         // Set NOW as enrol start if not one defined
         $today = time();
         $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), date('H', $today), date('i', $today), date('s', $today));
         $timestart = $today;
     }
     //  $timeend = 0;
     $found = false;
     foreach ($instances as $instance) {
         if ($instance->enrol == 'manual') {
             $found = true;
             break;
         }
     }
     if (!$found) {
         return 0;
     }
     $plugin = $plugins['manual'];
     if ($instance->enrolperiod != 0) {
         $timeend = $timestart + $instance->enrolperiod;
     }
     // First, check if user is already enroled but suspended, so we just need to enable it
     $conditions = array('courseid' => $course_id, 'enrol' => 'manual');
     $enrol = $DB->get_record('enrol', $conditions);
     if (!$enrol) {
         return 0;
     }
     $conditions = array('username' => $username);
     $user = $DB->get_record('user', $conditions);
     if (!$user) {
         return 0;
     }
     $conditions = array('enrolid' => $enrol->id, 'userid' => $user->id);
     $ue = $DB->get_record('user_enrolments', $conditions);
     if ($ue) {
         // User already enroled
         // Can be suspended, or maybe enrol time passed
         // Just activate enrolment and set new dates
         $ue->status = 0;
         //active
         $ue->timestart = $timestart;
         $ue->timeend = $timeend;
         $ue->timemodified = $timestart;
         $DB->update_record('user_enrolments', $ue);
         return 1;
     }
     $plugin->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
     return 1;
 }
Esempio n. 8
0
/**
 * Gets cohorts the user is able to view.
 *
 * @global moodle_database $DB
 * @param course_enrolment_manager $manager
 * @param int $offset limit output from
 * @param int $limit items to output per load
 * @param string $search search string
 * @return array    Array(more => bool, offset => int, cohorts => array)
 */
function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '')
{
    global $DB;
    $context = $manager->get_context();
    $cohorts = array();
    $instances = $manager->get_enrolment_instances();
    $enrolled = array();
    foreach ($instances as $instance) {
        if ($instance->enrol == 'cohort') {
            $enrolled[] = $instance->customint1;
        }
    }
    list($sqlparents, $params) = $DB->get_in_or_equal($context->get_parent_context_ids());
    // Add some additional sensible conditions.
    $tests = array('contextid ' . $sqlparents);
    // Modify the query to perform the search if required.
    if (!empty($search)) {
        $conditions = array('name', 'idnumber', 'description');
        $searchparam = '%' . $DB->sql_like_escape($search) . '%';
        foreach ($conditions as $key => $condition) {
            $conditions[$key] = $DB->sql_like($condition, "?", false);
            $params[] = $searchparam;
        }
        $tests[] = '(' . implode(' OR ', $conditions) . ')';
    }
    $wherecondition = implode(' AND ', $tests);
    $sql = "SELECT id, name, idnumber, contextid, description\n              FROM {cohort}\n             WHERE {$wherecondition}\n          ORDER BY name ASC, idnumber ASC";
    $rs = $DB->get_recordset_sql($sql, $params, $offset);
    // Produce the output respecting parameters.
    foreach ($rs as $c) {
        // Track offset.
        $offset++;
        // Check capabilities.
        $context = context::instance_by_id($c->contextid);
        if (!has_capability('moodle/cohort:view', $context)) {
            continue;
        }
        if ($limit === 0) {
            // We have reached the required number of items and know that there are more, exit now.
            $offset--;
            break;
        }
        $cohorts[$c->id] = array('cohortid' => $c->id, 'name' => shorten_text(format_string($c->name, true, array('context' => context::instance_by_id($c->contextid))), 35), 'users' => $DB->count_records('cohort_members', array('cohortid' => $c->id)), 'enrolled' => in_array($c->id, $enrolled));
        // Count items.
        $limit--;
    }
    $rs->close();
    return array('more' => !(bool) $limit, 'offset' => $offset, 'cohorts' => $cohorts);
}
 /**
  * This test the most complex decorator. The aim is to hide users who are in groups that are all hidden
  * and include those who are either in no group at all, or who have a group which is set to display.
  */
 public function test_groupid_attach_countrwapper()
 {
     global $PAGE, $DB;
     $this->setAdminUser();
     // Make basic course submissions. Keep track of which students have what.
     // Make courses.
     $generator = $this->getDataGenerator();
     $coursea = $generator->create_course();
     $courseb = $generator->create_course();
     // Make four students and a teacher.
     $student1a = $generator->create_user();
     $student2a = $generator->create_user();
     $student3b = $generator->create_user();
     $student4b = $generator->create_user();
     $teacher = $generator->create_user();
     // Enrol the users into the courses.
     $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
     $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'teacher'));
     $PAGE->set_course($coursea);
     $manager = new course_enrolment_manager($PAGE, $coursea);
     $plugins = $manager->get_enrolment_plugins();
     $instances = $manager->get_enrolment_instances();
     /* @var enrol_manual_plugin $manualenrolplugin */
     $manualenrolplugin = reset($plugins);
     $manualenrolinstance = reset($instances);
     $manualenrolplugin->enrol_user($manualenrolinstance, $student1a->id, $studentroleid);
     $manualenrolplugin->enrol_user($manualenrolinstance, $student2a->id, $studentroleid);
     $manualenrolplugin->enrol_user($manualenrolinstance, $teacher->id, $teacherroleid);
     $PAGE->set_course($courseb);
     $manager = new course_enrolment_manager($PAGE, $courseb);
     $plugins = $manager->get_enrolment_plugins();
     $instances = $manager->get_enrolment_instances();
     $manualenrolplugin = reset($plugins);
     $manualenrolinstance = reset($instances);
     $manualenrolplugin->enrol_user($manualenrolinstance, $student3b->id, $studentroleid);
     $manualenrolplugin->enrol_user($manualenrolinstance, $student4b->id, $studentroleid);
     $manualenrolplugin->enrol_user($manualenrolinstance, $teacher->id, $teacherroleid);
     // Make two groups in each course.
     $group1a = new stdClass();
     $group1a->courseid = $coursea->id;
     $group1a = $generator->create_group($group1a);
     $group2a = new stdClass();
     $group2a->courseid = $coursea->id;
     $group2a = $generator->create_group($group2a);
     $group3b = new stdClass();
     $group3b->courseid = $courseb->id;
     $group3b = $generator->create_group($group3b);
     $group4b = new stdClass();
     $group4b->courseid = $courseb->id;
     $group4b = $generator->create_group($group4b);
     // Make the students into group members.
     // To test all angles:
     // Student 1a is in two groups: 1a and 2a.
     // Student 2a is in 1 group: group 1a.
     // Student 3b is in one group: 3b.
     // Student 4a is in no groups.
     $groupmembership = new stdclass();
     $groupmembership->groupid = $group1a->id;
     $groupmembership->userid = $student1a->id;
     $groupmembership->timeadded = time();
     $DB->insert_record('groups_members', $groupmembership);
     $groupmembership = new stdclass();
     $groupmembership->groupid = $group1a->id;
     $groupmembership->userid = $student2a->id;
     $groupmembership->timeadded = time();
     $DB->insert_record('groups_members', $groupmembership);
     $groupmembership = new stdclass();
     $groupmembership->groupid = $group3b->id;
     $groupmembership->userid = $student3b->id;
     $groupmembership->timeadded = time();
     $DB->insert_record('groups_members', $groupmembership);
     $groupmembership = new stdclass();
     $groupmembership->groupid = $group2a->id;
     $groupmembership->userid = $student1a->id;
     $groupmembership->timeadded = time();
     $DB->insert_record('groups_members', $groupmembership);
     // Make an assignment for each course.
     $assigngenerator = new block_ajax_marking_mod_assign_generator($generator);
     $assignrecord = new stdClass();
     $assignrecord->assessed = 1;
     $assignrecord->scale = 4;
     $assignrecord->course = $coursea->id;
     $assigna = $assigngenerator->create_instance($assignrecord);
     $assignrecord = new stdClass();
     $assignrecord->assessed = 1;
     $assignrecord->scale = 4;
     $assignrecord->course = $courseb->id;
     $assignb = $assigngenerator->create_instance($assignrecord);
     // Make a student submission for each one.
     $submission = new stdClass();
     $submission->userid = $student1a->id;
     $submission->assignment = $assigna->id;
     $assigngenerator->create_assign_submission($submission);
     $submission = new stdClass();
     $submission->userid = $student2a->id;
     $submission->assignment = $assigna->id;
     $assigngenerator->create_assign_submission($submission);
     $submission = new stdClass();
     $submission->userid = $student3b->id;
     $submission->assignment = $assignb->id;
     $assigngenerator->create_assign_submission($submission);
     $submission = new stdClass();
     $submission->userid = $student4b->id;
     $submission->assignment = $assignb->id;
     $assigngenerator->create_assign_submission($submission);
     // A basic query should now return all four submissions.
     $this->setUser($teacher->id);
     // Get coutwrapper without any decorators.
     $nodesbuilder = new ReflectionClass('block_ajax_marking_nodes_builder');
     $moduleunionmethod = $nodesbuilder->getMethod('get_module_queries_array');
     $moduleunionmethod->setAccessible(true);
     $modulequeries = $moduleunionmethod->invoke($nodesbuilder, array());
     $moduleunionmethod = $nodesbuilder->getMethod('get_count_wrapper_query');
     $moduleunionmethod->setAccessible(true);
     /* @var block_ajax_marking_query $countwrapper */
     $countwrapper = $moduleunionmethod->invoke($nodesbuilder, $modulequeries, array());
     $this->assertInstanceOf('block_ajax_marking_query', $countwrapper);
     $totalnumberofsubmissions = 4;
     // Check that the raw countwrapper gets what we need.
     $sql = $countwrapper->debuggable_query();
     $recordset = $DB->get_recordset_sql($countwrapper->get_sql(), $countwrapper->get_params());
     // Count: should be 4. No other 'group by' filters, so just one record with an itemcount for all submissions.
     $pregroupscount = 0;
     $row = $recordset->current();
     $pregroupscount += $row->itemcount;
     $this->assertEquals($totalnumberofsubmissions, $pregroupscount, 'Query not working before we even get to the groups decorator');
     // OK - query works. now get the basic group ids that we expect.
     // Wrap countwrapper in group id decorator.
     $countwrapper = new block_ajax_marking_filter_groupid_attach_countwrapper($countwrapper);
     // Add a select or two so we can see if the groupid is there.
     $countwrapper->add_select(array('table' => 'membergroupquery', 'column' => 'groupid'));
     $countwrapper->add_select(array('table' => 'moduleunion', 'column' => 'userid'), true);
     $countwrapper->add_select(array('table' => 'moduleunion', 'column' => 'coursemoduleid'));
     // For debugging. Stop here and copy this to see what's in the query.
     $wrappedquery = $countwrapper->debuggable_query();
     $results = $countwrapper->execute();
     // Sanity check: we should still get the whole lot before messing with anything.
     $this->assertEquals($totalnumberofsubmissions, count($results), 'Groups decorator has broken the query before any settings changed');
     // Make sure we have the right groups - should be the highest groupid available if they are in more than one
     // group, or the one group id if they are in one group.
     // Student 1a is in two groups. Should be the max id.
     $message = 'Student has the wrong groupid - ' . $results[$student1a->id]->groupid . ' but ought to be the highest out of group1a and group2a ids: ' . $group2a->id;
     $this->assertEquals($group2a->id, $results[$student1a->id]->groupid, $message);
     // Student 2a should be there with the id from group1a. Single group membership.
     $message = 'Student 2a should be in group 1a (id: ' . $group1a->id . ' but is instead in a group with id ' . $results[$student2a->id]->groupid;
     $this->assertEquals($group1a->id, $results[$student2a->id]->groupid, $message);
     // Student 4b has no group, so ought to be without any groupid.
     $message = 'Student 4b should have zero for a groupid due to being in no group, but doesn\'t';
     $this->assertEquals(0, $results[$student4b->id]->groupid, $message);
     // Hide a group2a at coursemoduleid level.
     $newsetting = new stdClass();
     $newsetting->userid = $teacher->id;
     $newsetting->tablename = 'course_modules';
     $newsetting->instanceid = $assigna->cmid;
     $newsetting->display = 1;
     $newsetting->id = $DB->insert_record('block_ajax_marking', $newsetting);
     $newgroupsetting = new stdClass();
     $newgroupsetting->configid = $newsetting->id;
     $newgroupsetting->groupid = $group2a->id;
     $newgroupsetting->display = 0;
     $newgroupsetting->id = $DB->insert_record('block_ajax_marking_groups', $newgroupsetting);
     $results = $countwrapper->execute();
     $message = 'Hiding at coursemodule level has hidden the user instead of used the other available groupid';
     $this->assertArrayHasKey($student1a->id, $results, $message);
     $message = 'Hiding a group at coursemodule level didn\'t work as it ought to have made the student ' . 'in multiple groups who previously had a high id have a low id.';
     $this->assertEquals($group1a->id, $results[$student1a->id]->groupid, $message);
     // Now hide the only group a student is in and verify that we have that student hidden.
     $newgroupsetting = new stdClass();
     $newgroupsetting->configid = $newsetting->id;
     $newgroupsetting->groupid = $group1a->id;
     $newgroupsetting->display = 0;
     $newgroupsetting->id = $DB->insert_record('block_ajax_marking_groups', $newgroupsetting);
     $results = $countwrapper->execute();
     $message = 'Hiding group 1a failed to leave student 2a with a null groupid';
     $this->assertArrayNotHasKey($student2a->id, $results, $message);
     $message = 'Hiding group 1a failed to leave student 1a with a null groupid';
     $this->assertArrayNotHasKey($student1a->id, $results, $message);
     // Hide both groups group at course level.
     // Clean out the settings first.
     $DB->delete_records('block_ajax_marking_groups');
     $DB->delete_records('block_ajax_marking');
     // Test for non-group users coming up as 0.
 }
Esempio n. 10
0
 /**
  * Returns an enrol_user_button that takes the user to a page where they are able to
  * enrol users into the managers course through this plugin.
  *
  * Optional: If the plugin supports manual enrolments it can choose to override this
  * otherwise it shouldn't.
  *
  * @param course_enrolment_manager $manager
  * @return enrol_user_button|false
  */
 public function get_manual_enrol_button(course_enrolment_manager $manager)
 {
     global $CFG;
     $instance = null;
     $instances = array();
     foreach ($manager->get_enrolment_instances() as $tempinstance) {
         if ($tempinstance->enrol == 'invitation') {
             if ($instance === null) {
                 $instance = $tempinstance;
             }
             $instances[] = array('id' => $tempinstance->id, 'name' => $this->get_instance_name($tempinstance));
         }
     }
     if (empty($instance)) {
         return false;
     }
     $context = context_course::instance($instance->courseid);
     if (has_capability('enrol/invitation:enrol', $context)) {
         $invitelink = new moodle_url('/enrol/invitation/invitation.php', array('courseid' => $instance->courseid, 'id' => $instance->id));
         $button = new enrol_user_button($invitelink, get_string('inviteusers', 'enrol_invitation'), 'get');
         return $button;
     } else {
         return false;
     }
 }
Esempio n. 11
0
/**
 * Add a record to the facetoface submissions table and sends out an
 * email confirmation
 *
 * @param class $session record from the facetoface_sessions table
 * @param class $facetoface record from the facetoface table
 * @param class $course record from the course table
 * @param string $discountcode code entered by the user
 * @param integer $notificationtype type of notifications to send to user
 * @see {{MDL_F2F_INVITE}}
 * @param integer $statuscode Status code to set
 * @param integer $userid user to signup
 * @param bool $notifyuser whether or not to send an email confirmation
 * @param bool $displayerrors whether or not to return an error page on errors
 */
function facetoface_user_signup($session, $facetoface, $course, $discountcode, $notificationtype, $statuscode, $userid = false, $notifyuser = true)
{
    global $CFG, $DB, $PAGE;
    // Get user ID.
    if (!$userid) {
        global $USER;
        $userid = $USER->id;
    }
    $return = false;
    $timenow = time();
    // Check to see if user is already enrolled, if not. Enrol user
    $ehelper = new course_enrolment_manager($PAGE, $course);
    $enrolinstances = $ehelper->get_enrolment_instances();
    $enrolments = $ehelper->get_user_enrolments($userid);
    if (empty($enrolments)) {
        foreach ($enrolinstances as $instance) {
            if ($instance->enrol == 'manual') {
                $emp = new enrol_manual_plugin();
                $emp->enrol_user($instance, $userid, 5, $timenow);
                break;
            }
        }
    }
    // Check to see if a signup already exists.
    if ($existingsignup = $DB->get_record('facetoface_signups', array('sessionid' => $session->id, 'userid' => $userid))) {
        $usersignup = $existingsignup;
    } else {
        // Otherwise, prepare a signup object.
        $usersignup = new stdclass();
        $usersignup->sessionid = $session->id;
        $usersignup->userid = $userid;
    }
    $usersignup->mailedreminder = 0;
    $usersignup->notificationtype = $notificationtype;
    $usersignup->discountcode = trim(strtoupper($discountcode));
    if (empty($usersignup->discountcode)) {
        $usersignup->discountcode = null;
    }
    // Update/insert the signup record.
    if (!empty($usersignup->id)) {
        $success = $DB->update_record('facetoface_signups', $usersignup);
    } else {
        $usersignup->id = $DB->insert_record('facetoface_signups', $usersignup);
        $success = (bool) $usersignup->id;
    }
    if (!$success) {
        print_error('error:couldnotupdatef2frecord', 'facetoface');
        return false;
    }
    // Work out which status to use.
    // If approval not required.
    if (!$facetoface->approvalreqd) {
        $newstatus = $statuscode;
    } else {
        // If approval required.
        // Get current status (if any).
        $currentstatus = $DB->get_field('facetoface_signups_status', 'statuscode', array('signupid' => $usersignup->id, 'superceded' => 0));
        // If approved, then no problem.
        if ($currentstatus == MDL_F2F_STATUS_APPROVED) {
            $newstatus = $statuscode;
        } else {
            if ($session->datetimeknown) {
                // Otherwise, send manager request.
                $newstatus = MDL_F2F_STATUS_REQUESTED;
            } else {
                $newstatus = MDL_F2F_STATUS_WAITLISTED;
            }
        }
    }
    // Update status.
    if (!facetoface_update_signup_status($usersignup->id, $newstatus, $userid)) {
        print_error('error:f2ffailedupdatestatus', 'facetoface');
        return false;
    }
    // Add to user calendar -- if facetoface usercalentry is set to true.
    if ($facetoface->usercalentry) {
        if (in_array($newstatus, array(MDL_F2F_STATUS_BOOKED, MDL_F2F_STATUS_WAITLISTED))) {
            facetoface_add_session_to_calendar($session, $facetoface, 'user', $userid, 'booking');
        }
    }
    // Course completion.
    if (in_array($newstatus, array(MDL_F2F_STATUS_BOOKED, MDL_F2F_STATUS_WAITLISTED))) {
        $completion = new completion_info($course);
        if ($completion->is_enabled()) {
            $ccdetails = array('course' => $course->id, 'userid' => $userid);
            $cc = new completion_completion($ccdetails);
            $cc->mark_inprogress($timenow);
        }
    }
    // If session has already started, do not send a notification.
    if (facetoface_has_session_started($session, $timenow)) {
        $notifyuser = false;
    }
    // Send notification.
    if ($notifyuser) {
        // If booked/waitlisted.
        switch ($newstatus) {
            case MDL_F2F_STATUS_BOOKED:
                $error = facetoface_send_confirmation_notice($facetoface, $session, $userid, $notificationtype, false);
                break;
            case MDL_F2F_STATUS_WAITLISTED:
                $error = facetoface_send_confirmation_notice($facetoface, $session, $userid, $notificationtype, true);
                break;
            case MDL_F2F_STATUS_REQUESTED:
                $error = facetoface_send_request_notice($facetoface, $session, $userid);
                break;
        }
        if (!empty($error)) {
            print_error($error, 'facetoface');
            return false;
        }
        if (!$DB->update_record('facetoface_signups', $usersignup)) {
            print_error('error:couldnotupdatef2frecord', 'facetoface');
            return false;
        }
    }
    return true;
}
/**
 * Gets all the cohorts the user is able to view.
 *
 * @global moodle_database $DB
 * @return array
 */
function enrol_cohort_get_cohorts(course_enrolment_manager $manager)
{
    global $DB;
    $context = $manager->get_context();
    $cohorts = array();
    $instances = $manager->get_enrolment_instances();
    $enrolled = array();
    foreach ($instances as $instance) {
        if ($instance->enrol == 'cohort') {
            $enrolled[] = $instance->customint1;
        }
    }
    list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($context));
    $sql = "SELECT id, name, contextid\n              FROM {cohort}\n             WHERE contextid {$sqlparents}\n          ORDER BY name ASC";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $c) {
        $context = get_context_instance_by_id($c->contextid);
        if (!has_capability('moodle/cohort:view', $context)) {
            continue;
        }
        $cohorts[$c->id] = array('cohortid' => $c->id, 'name' => format_string($c->name), 'users' => $DB->count_records('cohort_members', array('cohortid' => $c->id)), 'enrolled' => in_array($c->id, $enrolled));
    }
    $rs->close();
    return $cohorts;
}