예제 #1
0
 /**
  * Test get_users_courses
  */
 public function test_get_users_courses()
 {
     global $USER;
     $this->resetAfterTest(true);
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     $courses = array($course1, $course2);
     // Enrol $USER in the courses.
     // We use the manual plugin.
     $enrol = enrol_get_plugin('manual');
     $roleid = null;
     foreach ($courses as $course) {
         $context = context_course::instance($course->id);
         $roleid = $this->assignUserCapability('moodle/course:viewparticipants', $context->id, $roleid);
         $enrolinstances = enrol_get_instances($course->id, true);
         foreach ($enrolinstances as $courseenrolinstance) {
             if ($courseenrolinstance->enrol == "manual") {
                 $instance = $courseenrolinstance;
                 break;
             }
         }
         $enrol->enrol_user($instance, $USER->id, $roleid);
     }
     // Call the external function.
     $enrolledincourses = core_enrol_external::get_users_courses($USER->id);
     // Check we retrieve the good total number of enrolled users.
     $this->assertEquals(2, count($enrolledincourses));
 }
 /**
  * Enrolment of users
  * Function throw an exception at the first error encountered.
  * @param array $enrolments  An array of user enrolment
  * @return null
  */
 public static function manual_enrol_users($enrolments)
 {
     global $DB, $CFG;
     require_once $CFG->libdir . '/enrollib.php';
     $params = self::validate_parameters(self::manual_enrol_users_parameters(), array('enrolments' => $enrolments));
     $transaction = $DB->start_delegated_transaction();
     //rollback all enrolment if an error occurs
     //(except if the DB doesn't support it)
     //retrieve the manual enrolment plugin
     $enrol = enrol_get_plugin('manual');
     if (empty($enrol)) {
         throw new moodle_exception('manualpluginnotinstalled', 'enrol_manual');
     }
     foreach ($params['enrolments'] as $enrolment) {
         // Ensure the current user is allowed to run this function in the enrolment context
         $context = get_context_instance(CONTEXT_COURSE, $enrolment['courseid']);
         self::validate_context($context);
         //check that the user has the permission to manual enrol
         require_capability('enrol/manual:enrol', $context);
         //throw an exception if user is not able to assign the role
         $roles = get_assignable_roles($context);
         if (!key_exists($enrolment['roleid'], $roles)) {
             $errorparams = new stdClass();
             $errorparams->roleid = $enrolment['roleid'];
             $errorparams->courseid = $enrolment['courseid'];
             $errorparams->userid = $enrolment['userid'];
             throw new moodle_exception('wsusercannotassign', 'enrol_manual', '', $errorparams);
         }
         //check manual enrolment plugin instance is enabled/exist
         $enrolinstances = enrol_get_instances($enrolment['courseid'], true);
         foreach ($enrolinstances as $courseenrolinstance) {
             if ($courseenrolinstance->enrol == "manual") {
                 $instance = $courseenrolinstance;
                 break;
             }
         }
         if (empty($instance)) {
             $errorparams = new stdClass();
             $errorparams->courseid = $enrolment['courseid'];
             throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams);
         }
         //check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin)
         if (!$enrol->allow_enrol($instance)) {
             $errorparams = new stdClass();
             $errorparams->roleid = $enrolment['roleid'];
             $errorparams->courseid = $enrolment['courseid'];
             $errorparams->userid = $enrolment['userid'];
             throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams);
         }
         //finally proceed the enrolment
         $enrolment['timestart'] = isset($enrolment['timestart']) ? $enrolment['timestart'] : 0;
         $enrolment['timeend'] = isset($enrolment['timeend']) ? $enrolment['timeend'] : 0;
         $enrolment['status'] = isset($enrolment['suspend']) && !empty($enrolment['suspend']) ? ENROL_USER_SUSPENDED : ENROL_USER_ACTIVE;
         $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['status']);
     }
     $transaction->allow_commit();
 }
예제 #3
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     foreach ($this->arguments as $argument) {
         $this->expandOptionsManually(array($argument));
         $options = $this->expandedOptions;
         // get the details for the course
         $course = $DB->get_record('course', array('id' => $argument), '*', MUST_EXIST);
         // get the details of the self enrolment plugin
         $plugin = enrol_get_plugin('self');
         if (!$plugin) {
             throw new \Exception('could not find self enrolment plugin');
         }
         // get the enrolment plugin instances for the course
         $instances = enrol_get_instances($course->id, false);
         // loop through the instances to find the instance ID for the self-enrolment plugin
         $selfEnrolInstance = 0;
         foreach ($instances as $instance) {
             if ($instance->enrol === 'self') {
                 $selfEnrolInstance = $instance;
             }
         }
         // if we didn't find an instance for the self enrolment plugin then we need to add
         // one to the course
         if (!$selfEnrolInstance) {
             // first try add an instance
             $plugin->add_default_instance($course);
             // then try retreive it
             $instances = enrol_get_instances($course->id, false);
             $selfEnrolInstance = 0;
             foreach ($instances as $instance) {
                 if ($instance->enrol === 'self') {
                     $selfEnrolInstance = $instance;
                 }
             }
             // if we still didn't get an instance - give up
             if (!$selfEnrolInstance) {
                 throw new \Exception('failed to create instance of self enrolment plugin');
             }
         }
         // activate self enrolment
         if ($selfEnrolInstance->status != ENROL_INSTANCE_ENABLED) {
             $plugin->update_status($selfEnrolInstance, ENROL_INSTANCE_ENABLED);
         }
         // set the enrolment key (always do this so running without the -k option will blank a pre-existing key)
         $instance_fromDB = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'self', 'id' => $selfEnrolInstance->id), '*', MUST_EXIST);
         $instance_fromDB->password = $options['key'];
         $DB->update_record('enrol', $instance_fromDB);
     }
 }
예제 #4
0
function block_csv_enrol_enrol_users($courseid, $csvcontent)
{
    global $DB, $CFG;
    require_once $CFG->libdir . '/enrollib.php';
    //get enrolment instance (manual and student)
    $instances = enrol_get_instances($courseid, false);
    $enrolment = "";
    foreach ($instances as $instance) {
        if ($instance->enrol === 'manual') {
            $enrolment = $instance;
            break;
        }
    }
    //get enrolment plugin
    $manual = enrol_get_plugin('manual');
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    $stats = new StdClass();
    $stats->success = $stats->failed = 0;
    //init counters
    $log = get_string('enrolling', 'block_csv_enrol') . "\r\n";
    $lines = explode("\n", $csvcontent);
    foreach ($lines as $line) {
        if ($line == "") {
            continue;
        }
        $user = $DB->get_record('user', array('email' => trim($line)));
        if ($user && !$user->deleted) {
            if (is_enrolled($context, $user)) {
                $log .= get_string('enrollinguser', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n";
            } else {
                $log .= get_string('alreadyenrolled', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n";
                $manual->enrol_user($enrolment, $user->id, $enrolment->roleid, time());
            }
            $stats->success++;
        } else {
            $log .= get_string('emailnotfound', 'block_csv_enrol', trim($line)) . "\r\n";
            $stats->failed++;
        }
    }
    $log .= get_string('done', 'block_csv_enrol') . "\r\n";
    $log = get_string('status', 'block_csv_enrol', $stats) . ' ' . get_string('enrolmentlog', 'block_csv_enrol') . "\r\n\r\n" . $log;
    return $log;
}
예제 #5
0
 /**
  * Make a role assignment in the specified course using the specified role
  * id for the user whose id information is passed in the line data.
  *
  * @access public
  * @static
  * @param stdClass      $course           Course in which to make the role assignment
  * @param stdClass      $enrol_instance   Enrol instance to use for adding users to course
  * @param string        $ident_field      The field (column) name in Moodle user rec against which to query using the imported data
  * @param int           $role_id          Id of the role to use in the role assignment
  * @param boolean       $group_assign     Whether or not to assign users to groups
  * @param int           $group_id         Id of group to assign to, 0 indicates use group name from import file
  * @param boolean       $group_create     Whether or not to create new groups if needed
  * @param stored_file   $import_file      File in local repository from which to get enrollment and group data
  * @return string                         String message with results
  *
  * @uses $DB
  */
 public static function import_file(stdClass $course, stdClass $enrol_instance, $ident_field, $role_id, $group_assign, $group_id, $group_create, stored_file $import_file)
 {
     global $DB;
     // Default return value
     $result = '';
     // Need one of these in the loop
     $course_context = context_course::instance($course->id);
     // Choose the regex pattern based on the $ident_field
     switch ($ident_field) {
         case 'email':
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w.%-]*@[a-z0-9][a-z0-9.-]{0,61}[a-z0-9]\\.[a-z]{2,6})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         case 'idnumber':
             $regex_pattern = '/^"?\\s*(\\d{1,32})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         default:
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w@.-]*)\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
     }
     // If doing group assignments, want to know the valid
     // groups for the course
     $selected_group = null;
     if ($group_assign) {
         if (false === ($existing_groups = groups_get_all_groups($course->id))) {
             $existing_groups = array();
         }
         if ($group_id > 0) {
             if (array_key_exists($group_id, $existing_groups)) {
                 $selected_group = $existing_groups[$group_id];
             } else {
                 // Error condition
                 return sprintf(get_string('ERR_INVALID_GROUP_ID', self::PLUGIN_NAME), $group_id);
             }
         }
     }
     // Iterate the list of active enrol plugins looking for
     // the meta course plugin
     $metacourse = false;
     $enrols_enabled = enrol_get_instances($course->id, true);
     foreach ($enrols_enabled as $enrol) {
         if ($enrol->enrol == 'meta') {
             $metacourse = true;
             break;
         }
     }
     // Get an instance of the enrol_manual_plugin (not to be confused
     // with the enrol_instance arg)
     $manual_enrol_plugin = enrol_get_plugin('manual');
     $user_rec = $new_group = $new_grouping = null;
     // Open and fetch the file contents
     $fh = $import_file->get_content_file_handle();
     $line_num = 0;
     while (false !== ($line = fgets($fh))) {
         $line_num++;
         // Clean these up for each iteration
         unset($user_rec, $new_group, $new_grouping);
         if (!($line = trim($line))) {
             continue;
         }
         // Parse the line, from which we may get one or two
         // matches since the group name is an optional item
         // on a line by line basis
         if (!preg_match($regex_pattern, $line, $matches)) {
             $result .= sprintf(get_string('ERR_PATTERN_MATCH', self::PLUGIN_NAME), $line_num, $line);
             continue;
         }
         $ident_value = $matches[1];
         $group_name = isset($matches[2]) ? $matches[2] : '';
         // User must already exist, we import enrollments
         // into courses, not users into the system. Exclude
         // records marked as deleted. Because idnumber is
         // not enforced unique, possible multiple records
         // returned when using that identifying field, so
         // use ->get_records method to make that detection
         // and inform user
         $user_rec_array = $DB->get_records('user', array($ident_field => addslashes($ident_value), 'deleted' => 0));
         // Should have one and only one record, otherwise
         // report it and move on to the next
         $user_rec_count = count($user_rec_array);
         if ($user_rec_count == 0) {
             // No record found
             $result .= sprintf(get_string('ERR_USERID_INVALID', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         } elseif ($user_rec_count > 1) {
             // Too many records
             $result .= sprintf(get_string('ERR_USER_MULTIPLE_RECS', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         }
         $user_rec = array_shift($user_rec_array);
         // Fetch all the role assignments this user might have for this course's context
         $roles = get_user_roles($course_context, $user_rec->id, false);
         // If a user has a role in this course, then we leave it alone and move on
         // to the group assignment if there is one. If they have no role, then we
         // should go ahead and add one, as long as it is not a metacourse.
         if (!$roles && $role_id > 0) {
             if ($metacourse) {
                 $result .= sprintf(get_string('ERR_ENROLL_META', self::PLUGIN_NAME), $line_num, $ident_value);
             } else {
                 try {
                     $manual_enrol_plugin->enrol_user($enrol_instance, $user_rec->id, $role_id);
                 } catch (Exception $exc) {
                     $result .= sprintf(get_string('ERR_ENROLL_FAILED', self::PLUGIN_NAME), $line_num, $ident_value);
                     $result .= $exc->getMessage();
                     continue;
                 }
             }
         }
         // If no group assignments, or group is from file, but no
         // group found, next line
         if (!$group_assign || $group_id == 0 && empty($group_name)) {
             continue;
         }
         // If no group pre-selected, see if group from import already
         // created for that course
         $assign_group_id = 0;
         $assign_group_name = '';
         if ($selected_group != null) {
             $assign_group_id = $selected_group->id;
             $assign_group_name = $selected_group->name;
         } else {
             foreach ($existing_groups as $existing_group) {
                 if ($existing_group->name != $group_name) {
                     continue;
                 }
                 $assign_group_id = $existing_group->id;
                 $assign_group_name = $existing_group->name;
                 break;
             }
             // No group by that name
             if ($assign_group_id == 0) {
                 // Can not create one, next line
                 if (!$group_create) {
                     continue;
                 }
                 // Make a new group for this course
                 $new_group = new stdClass();
                 $new_group->name = addslashes($group_name);
                 $new_group->courseid = $course->id;
                 if (false === ($assign_group_id = groups_create_group($new_group))) {
                     $result .= sprintf(get_string('ERR_CREATE_GROUP', self::PLUGIN_NAME), $line_num, $group_name);
                     continue;
                 } else {
                     // Add the new group to our list for the benefit of
                     // the next contestant. Strip the slashes off the
                     // name since we do a name comparison earlier when
                     // trying to find the group in our local cache and
                     // an escaped semi-colon will cause the test to fail.
                     $new_group->name = $assign_group_name = stripslashes($new_group->name);
                     $new_group->id = $assign_group_id;
                     $existing_groups[] = $new_group;
                 }
             }
             // if ($assign_group_id == 0)
         }
         // Put the user in the group if not aleady in it
         if (!groups_is_member($assign_group_id, $user_rec->id) && !groups_add_member($assign_group_id, $user_rec->id)) {
             $result .= sprintf(get_string('ERR_GROUP_MEMBER', self::PLUGIN_NAME), $line_num, $ident_value, $assign_group_name);
             continue;
         }
         // Any other work...
     }
     // while fgets
     fclose($fh);
     return empty($result) ? get_string('INF_IMPORT_SUCCESS', self::PLUGIN_NAME) : $result;
 }
 /**
  * Create a course in Moodle (Migration)
  *
  * @global type $DB
  * @global type $CFG
  * @global type $USER
  * @param int $tiicourseid The course id on Turnitin
  * @param string $tiicoursetitle The course title on Turnitin
  * @param string $coursename The new course name on Moodle
  * @param int $coursecategory The category that the course is to be created in
  * @return mixed course object if created or 0 if failed
  */
 public static function create_moodle_course($tiicourseid, $tiicoursetitle, $coursename, $coursecategory)
 {
     global $DB, $CFG, $USER;
     require_once $CFG->dirroot . "/course/lib.php";
     $data = new stdClass();
     $data->category = $coursecategory;
     $data->fullname = $coursename;
     $data->shortname = "Turnitin (" . $tiicourseid . ")";
     $data->maxbytes = 2097152;
     if ($course = create_course($data)) {
         $turnitincourse = new stdClass();
         $turnitincourse->courseid = $course->id;
         $turnitincourse->turnitin_cid = $tiicourseid;
         $turnitincourse->turnitin_ctl = $tiicoursetitle;
         $turnitincourse->ownerid = $USER->id;
         $turnitincourse->course_type = 'TT';
         // Enrol user as instructor on course in moodle if they are not a site admin.
         if (!is_siteadmin()) {
             // Get the role id for a teacher.
             $roles1 = get_roles_with_capability('mod/turnitintooltwo:grade');
             $roles2 = get_roles_with_capability('mod/turnitintooltwo:addinstance');
             $roles = array_intersect_key($roles1, $roles2);
             $role = current($roles);
             // Enrol $USER in the courses using the manual plugin.
             $enrol = enrol_get_plugin('manual');
             $enrolinstances = enrol_get_instances($course->id, true);
             foreach ($enrolinstances as $courseenrolinstance) {
                 if ($courseenrolinstance->enrol == "manual") {
                     $instance = $courseenrolinstance;
                     break;
                 }
             }
             $enrol->enrol_user($instance, $USER->id, $role->id);
         } else {
             // Enrol admin as an instructor incase they are not on the account.
             $turnitintooltwouser = new turnitintooltwo_user($USER->id, "Instructor");
             $turnitintooltwouser->join_user_to_class($tiicourseid);
         }
         if (!($insertid = $DB->insert_record('turnitintooltwo_courses', $turnitincourse))) {
             turnitintooltwo_activitylog(get_string('migrationcoursecreatederror', 'turnitintooltwo', $tiicourseid) . ' - ' . $course->id, "REQUEST");
             return 0;
         } else {
             turnitintooltwo_activitylog(get_string('migrationcoursecreated', 'turnitintooltwo') . ' - ' . $course->id . ' (' . $tiicourseid . ')', "REQUEST");
             return $course;
         }
     } else {
         turnitintooltwo_activitylog(get_string('migrationcoursecreateerror', 'turnitintooltwo', $tiicourseid), "REQUEST");
         return 0;
     }
 }
예제 #7
0
 public function test_enrolment_data()
 {
     $this->resetAfterTest(true);
     $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
     $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
     $data = array('shortname' => 'c1', 'summary' => 'S', 'fullname' => 'FN', 'category' => '1');
     $data['enrolment_1'] = 'manual';
     $data['enrolment_1_role'] = 'teacher';
     $data['enrolment_1_startdate'] = '2nd July 2013';
     $data['enrolment_1_enddate'] = '2nd August 2013';
     $data['enrolment_1_enrolperiod'] = '10 days';
     $co = new tool_uploadcourse_course($mode, $updatemode, $data);
     $this->assertTrue($co->prepare());
     $co->proceed();
     // Enrolment methods.
     $enroldata = array();
     $instances = enrol_get_instances($co->get_id(), false);
     foreach ($instances as $instance) {
         $enroldata[$instance->enrol] = $instance;
     }
     $this->assertNotEmpty($enroldata['manual']);
     $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['manual']->status);
     $this->assertEquals(strtotime($data['enrolment_1_startdate']), $enroldata['manual']->enrolstartdate);
     $this->assertEquals(strtotime('1970-01-01 GMT + ' . $data['enrolment_1_enrolperiod']), $enroldata['manual']->enrolperiod);
     $this->assertEquals(strtotime('12th July 2013'), $enroldata['manual']->enrolenddate);
 }
예제 #8
0
/**
 * This function will empty a course of user data.
 * It will retain the activities and the structure of the course.
 *
 * @param object $data an object containing all the settings including courseid (without magic quotes)
 * @return array status array of array component, item, error
 */
function reset_course_userdata($data)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->libdir . '/completionlib.php';
    require_once $CFG->dirroot . '/group/lib.php';
    $data->courseid = $data->id;
    $context = context_course::instance($data->courseid);
    $eventparams = array('context' => $context, 'courseid' => $data->id, 'other' => array('reset_options' => (array) $data));
    $event = \core\event\course_reset_started::create($eventparams);
    $event->trigger();
    // Calculate the time shift of dates.
    if (!empty($data->reset_start_date)) {
        // Time part of course startdate should be zero.
        $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
    } else {
        $data->timeshift = 0;
    }
    // Result array: component, item, error.
    $status = array();
    // Start the resetting.
    $componentstr = get_string('general');
    // Move the course start time.
    if (!empty($data->reset_start_date) and $data->timeshift) {
        // Change course start data.
        $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
        // Update all course and group events - do not move activity events.
        $updatesql = "UPDATE {event}\n                         SET timestart = timestart + ?\n                       WHERE courseid=? AND instance=0";
        $DB->execute($updatesql, array($data->timeshift, $data->courseid));
        // Update any date activity restrictions.
        if ($CFG->enableavailability) {
            \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
        }
        $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
    }
    if (!empty($data->reset_end_date)) {
        // If the user set a end date value respect it.
        $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
    } else {
        if ($data->timeshift > 0 && $data->reset_end_date_old) {
            // If there is a time shift apply it to the end date as well.
            $enddate = $data->reset_end_date_old + $data->timeshift;
            $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
        }
    }
    if (!empty($data->reset_events)) {
        $DB->delete_records('event', array('courseid' => $data->courseid));
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
    }
    if (!empty($data->reset_notes)) {
        require_once $CFG->dirroot . '/notes/lib.php';
        note_delete_all($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
    }
    if (!empty($data->delete_blog_associations)) {
        require_once $CFG->dirroot . '/blog/lib.php';
        blog_remove_associations_for_course($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
    }
    if (!empty($data->reset_completion)) {
        // Delete course and activity completion information.
        $course = $DB->get_record('course', array('id' => $data->courseid));
        $cc = new completion_info($course);
        $cc->delete_all_completion_data();
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
    }
    if (!empty($data->reset_competency_ratings)) {
        \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
    }
    $componentstr = get_string('roles');
    if (!empty($data->reset_roles_overrides)) {
        $children = $context->get_child_contexts();
        foreach ($children as $child) {
            $DB->delete_records('role_capabilities', array('contextid' => $child->id));
        }
        $DB->delete_records('role_capabilities', array('contextid' => $context->id));
        // Force refresh for logged in users.
        $context->mark_dirty();
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
    }
    if (!empty($data->reset_roles_local)) {
        $children = $context->get_child_contexts();
        foreach ($children as $child) {
            role_unassign_all(array('contextid' => $child->id));
        }
        // Force refresh for logged in users.
        $context->mark_dirty();
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
    }
    // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
    $data->unenrolled = array();
    if (!empty($data->unenrol_users)) {
        $plugins = enrol_get_plugins(true);
        $instances = enrol_get_instances($data->courseid, true);
        foreach ($instances as $key => $instance) {
            if (!isset($plugins[$instance->enrol])) {
                unset($instances[$key]);
                continue;
            }
        }
        foreach ($data->unenrol_users as $withroleid) {
            if ($withroleid) {
                $sql = "SELECT ue.*\n                          FROM {user_enrolments} ue\n                          JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)\n                          JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)\n                          JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
                $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
            } else {
                // Without any role assigned at course context.
                $sql = "SELECT ue.*\n                          FROM {user_enrolments} ue\n                          JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)\n                          JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)\n                     LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)\n                         WHERE ra.id IS null";
                $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
            }
            $rs = $DB->get_recordset_sql($sql, $params);
            foreach ($rs as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    continue;
                }
                $instance = $instances[$ue->enrolid];
                $plugin = $plugins[$instance->enrol];
                if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
                    continue;
                }
                $plugin->unenrol_user($instance, $ue->userid);
                $data->unenrolled[$ue->userid] = $ue->userid;
            }
            $rs->close();
        }
    }
    if (!empty($data->unenrolled)) {
        $status[] = array('component' => $componentstr, 'item' => get_string('unenrol', 'enrol') . ' (' . count($data->unenrolled) . ')', 'error' => false);
    }
    $componentstr = get_string('groups');
    // Remove all group members.
    if (!empty($data->reset_groups_members)) {
        groups_delete_group_members($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
    }
    // Remove all groups.
    if (!empty($data->reset_groups_remove)) {
        groups_delete_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
    }
    // Remove all grouping members.
    if (!empty($data->reset_groupings_members)) {
        groups_delete_groupings_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
    }
    // Remove all groupings.
    if (!empty($data->reset_groupings_remove)) {
        groups_delete_groupings($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
    }
    // Look in every instance of every module for data to delete.
    $unsupportedmods = array();
    if ($allmods = $DB->get_records('modules')) {
        foreach ($allmods as $mod) {
            $modname = $mod->name;
            $modfile = $CFG->dirroot . '/mod/' . $modname . '/lib.php';
            $moddeleteuserdata = $modname . '_reset_userdata';
            // Function to delete user data.
            if (file_exists($modfile)) {
                if (!$DB->count_records($modname, array('course' => $data->courseid))) {
                    continue;
                    // Skip mods with no instances.
                }
                include_once $modfile;
                if (function_exists($moddeleteuserdata)) {
                    $modstatus = $moddeleteuserdata($data);
                    if (is_array($modstatus)) {
                        $status = array_merge($status, $modstatus);
                    } else {
                        debugging('Module ' . $modname . ' returned incorrect staus - must be an array!');
                    }
                } else {
                    $unsupportedmods[] = $mod;
                }
            } else {
                debugging('Missing lib.php in ' . $modname . ' module!');
            }
        }
    }
    // Mention unsupported mods.
    if (!empty($unsupportedmods)) {
        foreach ($unsupportedmods as $mod) {
            $status[] = array('component' => get_string('modulenameplural', $mod->name), 'item' => '', 'error' => get_string('resetnotimplemented'));
        }
    }
    $componentstr = get_string('gradebook', 'grades');
    // Reset gradebook,.
    if (!empty($data->reset_gradebook_items)) {
        remove_course_grades($data->courseid, false);
        grade_grab_course_grades($data->courseid);
        grade_regrade_final_grades($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
    } else {
        if (!empty($data->reset_gradebook_grades)) {
            grade_course_reset($data->courseid);
            $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
        }
    }
    // Reset comments.
    if (!empty($data->reset_comments)) {
        require_once $CFG->dirroot . '/comment/lib.php';
        comment::reset_course_page_comments($context);
    }
    $event = \core\event\course_reset_ended::create($eventparams);
    $event->trigger();
    return $status;
}
예제 #9
0
 public function test_message_get_providers_for_user_more()
 {
     global $DB;
     $this->resetAfterTest();
     // Create a course.
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     // It would probably be better to use a quiz instance as it has capability controlled messages
     // however mod_quiz doesn't have a data generator.
     // Instead we're going to use backup notifications and give and take away the capability at various levels.
     $assign = $this->getDataGenerator()->create_module('assign', array('course' => $course->id));
     $modulecontext = context_module::instance($assign->cmid);
     // Create and enrol a teacher.
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST);
     $teacher = $this->getDataGenerator()->create_user();
     role_assign($teacherrole->id, $teacher->id, $coursecontext);
     $enrolplugin = enrol_get_plugin('manual');
     $enrolplugin->add_instance($course);
     $enrolinstances = enrol_get_instances($course->id, false);
     foreach ($enrolinstances as $enrolinstance) {
         if ($enrolinstance->enrol === 'manual') {
             break;
         }
     }
     $enrolplugin->enrol_user($enrolinstance, $teacher->id);
     // Make the teacher the current user.
     $this->setUser($teacher);
     // Teacher shouldn't have the required capability so they shouldn't be able to see the backup message.
     $this->assertFalse(has_capability('moodle/site:config', $modulecontext));
     $providers = message_get_providers_for_user($teacher->id);
     $this->assertFalse($this->message_type_present('moodle', 'backup', $providers));
     // Give the user the required capability in an activity module.
     // They should now be able to see the backup message.
     assign_capability('moodle/site:config', CAP_ALLOW, $teacherrole->id, $modulecontext->id, true);
     accesslib_clear_all_caches_for_unit_testing();
     $modulecontext = context_module::instance($assign->cmid);
     $this->assertTrue(has_capability('moodle/site:config', $modulecontext));
     $providers = message_get_providers_for_user($teacher->id);
     $this->assertTrue($this->message_type_present('moodle', 'backup', $providers));
     // Prohibit the capability for the user at the course level.
     // This overrules the CAP_ALLOW at the module level.
     // They should not be able to see the backup message.
     assign_capability('moodle/site:config', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id, true);
     accesslib_clear_all_caches_for_unit_testing();
     $modulecontext = context_module::instance($assign->cmid);
     $this->assertFalse(has_capability('moodle/site:config', $modulecontext));
     $providers = message_get_providers_for_user($teacher->id);
     // Actually, handling PROHIBITs would be too expensive. We do not
     // care if users with PROHIBITs see a few more preferences than they should.
     // $this->assertFalse($this->message_type_present('moodle', 'backup', $providers));
 }
예제 #10
0
 /**
  * Return the course information that is public (visible by every one)
  *
  * @param  course_in_list $course        course in list object
  * @param  stdClass       $coursecontext course context object
  * @return array the course information
  * @since  Moodle 3.2
  */
 protected static function get_course_public_information(course_in_list $course, $coursecontext)
 {
     static $categoriescache = array();
     // Category information.
     if (!array_key_exists($course->category, $categoriescache)) {
         $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
     }
     $category = $categoriescache[$course->category];
     // Retrieve course overview used files.
     $files = array();
     foreach ($course->get_course_overviewfiles() as $file) {
         $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), null, $file->get_filepath(), $file->get_filename())->out(false);
         $files[] = array('filename' => $file->get_filename(), 'fileurl' => $fileurl, 'filesize' => $file->get_filesize(), 'filepath' => $file->get_filepath(), 'mimetype' => $file->get_mimetype(), 'timemodified' => $file->get_timemodified());
     }
     // Retrieve the course contacts,
     // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
     $coursecontacts = array();
     foreach ($course->get_course_contacts() as $contact) {
         $coursecontacts[] = array('id' => $contact['user']->id, 'fullname' => $contact['username']);
     }
     // Allowed enrolment methods (maybe we can self-enrol).
     $enroltypes = array();
     $instances = enrol_get_instances($course->id, true);
     foreach ($instances as $instance) {
         $enroltypes[] = $instance->enrol;
     }
     // Format summary.
     list($summary, $summaryformat) = external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
     $displayname = get_course_display_name_for_list($course);
     $coursereturns = array();
     $coursereturns['id'] = $course->id;
     $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
     $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
     $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
     $coursereturns['categoryid'] = $course->category;
     $coursereturns['categoryname'] = $category == null ? '' : $category->name;
     $coursereturns['summary'] = $summary;
     $coursereturns['summaryformat'] = $summaryformat;
     $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
     $coursereturns['overviewfiles'] = $files;
     $coursereturns['contacts'] = $coursecontacts;
     $coursereturns['enrollmentmethods'] = $enroltypes;
     return $coursereturns;
 }
예제 #11
0
 /**
  * Creates a number of user accounts and enrols them on the course.
  * Note: Existing user accounts that were created by this system are
  * reused if available.
  */
 private function create_users()
 {
     global $DB;
     // Work out total number of users.
     $count = self::$paramusers[$this->size];
     // Get existing users in order. We will 'fill up holes' in this up to
     // the required number.
     $this->log('checkaccounts', $count);
     $nextnumber = 1;
     $rs = $DB->get_recordset_select('user', $DB->sql_like('username', '?'), array('tool_generator_%'), 'username', 'id, username');
     foreach ($rs as $rec) {
         // Extract number from username.
         $matches = array();
         if (!preg_match('~^tool_generator_([0-9]{6})$~', $rec->username, $matches)) {
             continue;
         }
         $number = (int) $matches[1];
         // Create missing users in range up to this.
         if ($number != $nextnumber) {
             $this->create_user_accounts($nextnumber, min($number - 1, $count));
         } else {
             $this->userids[$number] = (int) $rec->id;
         }
         // Stop if we've got enough users.
         $nextnumber = $number + 1;
         if ($number >= $count) {
             break;
         }
     }
     $rs->close();
     // Create users from end of existing range.
     if ($nextnumber <= $count) {
         $this->create_user_accounts($nextnumber, $count);
     }
     // Assign all users to course.
     $this->log('enrol', $count, true);
     $enrolplugin = enrol_get_plugin('manual');
     $instances = enrol_get_instances($this->course->id, true);
     foreach ($instances as $instance) {
         if ($instance->enrol === 'manual') {
             break;
         }
     }
     if ($instance->enrol !== 'manual') {
         throw new coding_exception('No manual enrol plugin in course');
     }
     $role = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST);
     for ($number = 1; $number <= $count; $number++) {
         // Enrol user.
         $enrolplugin->enrol_user($instance, $this->userids[$number], $role->id);
         $this->dot($number, $count);
     }
     // Sets the pointer at the beginning to be aware of the users we use.
     reset($this->userids);
     $this->end_log();
 }
예제 #12
0
 /**
  * Search courses following the specified criteria.
  *
  * @param string $criterianame  Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
  * @param string $criteriavalue Criteria value
  * @param int $page             Page number (for pagination)
  * @param int $perpage          Items per page
  * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
  * @param int $limittoenrolled  Limit to only enrolled courses
  * @return array of course objects and warnings
  * @since Moodle 3.0
  * @throws moodle_exception
  */
 public static function search_courses($criterianame, $criteriavalue, $page = 0, $perpage = 0, $requiredcapabilities = array(), $limittoenrolled = 0)
 {
     global $CFG;
     require_once $CFG->libdir . '/coursecatlib.php';
     $warnings = array();
     $parameters = array('criterianame' => $criterianame, 'criteriavalue' => $criteriavalue, 'page' => $page, 'perpage' => $perpage, 'requiredcapabilities' => $requiredcapabilities);
     $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
     self::validate_context(context_system::instance());
     $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
     if (!in_array($params['criterianame'], $allowedcriterianames)) {
         throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: ' . $params['criterianame'] . '),' . 'allowed values are: ' . implode(',', $allowedcriterianames));
     }
     if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
         require_capability('moodle/site:config', context_system::instance());
     }
     $paramtype = array('search' => PARAM_RAW, 'modulelist' => PARAM_PLUGIN, 'blocklist' => PARAM_INT, 'tagid' => PARAM_INT);
     $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
     // Prepare the search API options.
     $searchcriteria = array();
     $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
     $options = array();
     if ($params['perpage'] != 0) {
         $offset = $params['page'] * $params['perpage'];
         $options = array('offset' => $offset, 'limit' => $params['perpage']);
     }
     // Search the courses.
     $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
     $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
     if (!empty($limittoenrolled)) {
         // Get the courses where the current user has access.
         $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
     }
     $finalcourses = array();
     $categoriescache = array();
     foreach ($courses as $course) {
         if (!empty($limittoenrolled)) {
             // Filter out not enrolled courses.
             if (!isset($enrolled[$course->id])) {
                 $totalcount--;
                 continue;
             }
         }
         $coursecontext = context_course::instance($course->id);
         // Category information.
         if (!isset($categoriescache[$course->category])) {
             $categoriescache[$course->category] = coursecat::get($course->category);
         }
         $category = $categoriescache[$course->category];
         // Retrieve course overfiew used files.
         $files = array();
         foreach ($course->get_course_overviewfiles() as $file) {
             $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), null, $file->get_filepath(), $file->get_filename())->out(false);
             $files[] = array('filename' => $file->get_filename(), 'fileurl' => $fileurl, 'filesize' => $file->get_filesize());
         }
         // Retrieve the course contacts,
         // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
         $coursecontacts = array();
         foreach ($course->get_course_contacts() as $contact) {
             $coursecontacts[] = array('id' => $contact['user']->id, 'fullname' => $contact['username']);
         }
         // Allowed enrolment methods (maybe we can self-enrol).
         $enroltypes = array();
         $instances = enrol_get_instances($course->id, true);
         foreach ($instances as $instance) {
             $enroltypes[] = $instance->enrol;
         }
         // Format summary.
         list($summary, $summaryformat) = external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
         $displayname = get_course_display_name_for_list($course);
         $coursereturns = array();
         $coursereturns['id'] = $course->id;
         $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
         $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
         $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
         $coursereturns['categoryid'] = $course->category;
         $coursereturns['categoryname'] = $category->name;
         $coursereturns['summary'] = $summary;
         $coursereturns['summaryformat'] = $summaryformat;
         $coursereturns['overviewfiles'] = $files;
         $coursereturns['contacts'] = $coursecontacts;
         $coursereturns['enrollmentmethods'] = $enroltypes;
         $finalcourses[] = $coursereturns;
     }
     return array('total' => $totalcount, 'courses' => $finalcourses, 'warnings' => $warnings);
 }
예제 #13
0
 /**
  * Returns course details in an array ready to be printed.
  *
  * @global \moodle_database $DB
  * @param \course_in_list $course
  * @return array
  */
 public static function get_course_detail_array(\course_in_list $course)
 {
     global $DB;
     $canaccess = $course->can_access();
     $format = \course_get_format($course->id);
     $modinfo = \get_fast_modinfo($course->id);
     $modules = $modinfo->get_used_module_names();
     $sections = array();
     if ($format->uses_sections()) {
         foreach ($modinfo->get_section_info_all() as $section) {
             if ($section->uservisible) {
                 $sections[] = $format->get_section_name($section);
             }
         }
     }
     $category = \coursecat::get($course->category);
     $categoryurl = new \moodle_url('/course/management.php', array('categoryid' => $course->category));
     $categoryname = $category->get_formatted_name();
     $details = array('fullname' => array('key' => \get_string('fullname'), 'value' => $course->get_formatted_fullname()), 'shortname' => array('key' => \get_string('shortname'), 'value' => $course->get_formatted_shortname()), 'idnumber' => array('key' => \get_string('idnumber'), 'value' => s($course->idnumber)), 'category' => array('key' => \get_string('category'), 'value' => \html_writer::link($categoryurl, $categoryname)));
     if (has_capability('moodle/site:accessallgroups', $course->get_context())) {
         $groups = \groups_get_course_data($course->id);
         $details += array('groupings' => array('key' => \get_string('groupings', 'group'), 'value' => count($groups->groupings)), 'groups' => array('key' => \get_string('groups'), 'value' => count($groups->groups)));
     }
     if ($canaccess) {
         $names = \role_get_names($course->get_context());
         $sql = 'SELECT ra.roleid, COUNT(ra.id) AS rolecount
                   FROM {role_assignments} ra
                  WHERE ra.contextid = :contextid
               GROUP BY ra.roleid';
         $rolecounts = $DB->get_records_sql($sql, array('contextid' => $course->get_context()->id));
         $roledetails = array();
         foreach ($rolecounts as $result) {
             $a = new \stdClass();
             $a->role = $names[$result->roleid]->localname;
             $a->count = $result->rolecount;
             $roledetails[] = \get_string('assignedrolecount', 'moodle', $a);
         }
         $details['roleassignments'] = array('key' => \get_string('roleassignments'), 'value' => join('<br />', $roledetails));
     }
     if ($course->can_review_enrolments()) {
         $enrolmentlines = array();
         $instances = \enrol_get_instances($course->id, true);
         $plugins = \enrol_get_plugins(true);
         foreach ($instances as $instance) {
             if (!isset($plugins[$instance->enrol])) {
                 // Weird.
                 continue;
             }
             $plugin = $plugins[$instance->enrol];
             $enrolmentlines[] = $plugin->get_instance_name($instance);
         }
         $details['enrolmentmethods'] = array('key' => \get_string('enrolmentmethods'), 'value' => join('<br />', $enrolmentlines));
     }
     if ($canaccess) {
         $details['format'] = array('key' => \get_string('format'), 'value' => \course_get_format($course)->get_format_name());
         $details['sections'] = array('key' => \get_string('sections'), 'value' => join('<br />', $sections));
         $details['modulesused'] = array('key' => \get_string('modulesused'), 'value' => join('<br />', $modules));
     }
     return $details;
 }
예제 #14
0
 function course_enrol_methods($course_id)
 {
     $instances = enrol_get_instances($course_id, true);
     $i = 0;
     foreach ($instances as $method) {
         $m[$i]['id'] = $method->id;
         $m[$i]['enrol'] = $method->enrol;
         $m[$i]['enrolstartdate'] = $method->enrolstartdate;
         $m[$i]['enrolenddate'] = $method->enrolenddate;
         $i++;
     }
     return $m;
 }
예제 #15
0
파일: course.php 프로젝트: evltuma/moodle
 /**
  * Add the enrolment data for the course.
  *
  * @param object $course course record.
  * @return void
  */
 protected function process_enrolment_data($course)
 {
     global $DB;
     $enrolmentdata = $this->enrolmentdata;
     if (empty($enrolmentdata)) {
         return;
     }
     $enrolmentplugins = tool_uploadcourse_helper::get_enrolment_plugins();
     $instances = enrol_get_instances($course->id, false);
     foreach ($enrolmentdata as $enrolmethod => $method) {
         $instance = null;
         foreach ($instances as $i) {
             if ($i->enrol == $enrolmethod) {
                 $instance = $i;
                 break;
             }
         }
         $todelete = isset($method['delete']) && $method['delete'];
         $todisable = isset($method['disable']) && $method['disable'];
         unset($method['delete']);
         unset($method['disable']);
         if (!empty($instance) && $todelete) {
             // Remove the enrolment method.
             foreach ($instances as $instance) {
                 if ($instance->enrol == $enrolmethod) {
                     $plugin = $enrolmentplugins[$instance->enrol];
                     $plugin->delete_instance($instance);
                     break;
                 }
             }
         } else {
             if (!empty($instance) && $todisable) {
                 // Disable the enrolment.
                 foreach ($instances as $instance) {
                     if ($instance->enrol == $enrolmethod) {
                         $plugin = $enrolmentplugins[$instance->enrol];
                         $plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
                         $enrol_updated = true;
                         break;
                     }
                 }
             } else {
                 $plugin = null;
                 if (empty($instance)) {
                     $plugin = $enrolmentplugins[$enrolmethod];
                     $instance = new stdClass();
                     $instance->id = $plugin->add_default_instance($course);
                     $instance->roleid = $plugin->get_config('roleid');
                     $instance->status = ENROL_INSTANCE_ENABLED;
                 } else {
                     $plugin = $enrolmentplugins[$instance->enrol];
                     $plugin->update_status($instance, ENROL_INSTANCE_ENABLED);
                 }
                 // Now update values.
                 foreach ($method as $k => $v) {
                     $instance->{$k} = $v;
                 }
                 // Sort out the start, end and date.
                 $instance->enrolstartdate = isset($method['startdate']) ? strtotime($method['startdate']) : 0;
                 $instance->enrolenddate = isset($method['enddate']) ? strtotime($method['enddate']) : 0;
                 // Is the enrolment period set?
                 if (isset($method['enrolperiod']) && !empty($method['enrolperiod'])) {
                     if (preg_match('/^\\d+$/', $method['enrolperiod'])) {
                         $method['enrolperiod'] = (int) $method['enrolperiod'];
                     } else {
                         // Try and convert period to seconds.
                         $method['enrolperiod'] = strtotime('1970-01-01 GMT + ' . $method['enrolperiod']);
                     }
                     $instance->enrolperiod = $method['enrolperiod'];
                 }
                 if ($instance->enrolstartdate > 0 && isset($method['enrolperiod'])) {
                     $instance->enrolenddate = $instance->enrolstartdate + $method['enrolperiod'];
                 }
                 if ($instance->enrolenddate > 0) {
                     $instance->enrolperiod = $instance->enrolenddate - $instance->enrolstartdate;
                 }
                 if ($instance->enrolenddate < $instance->enrolstartdate) {
                     $instance->enrolenddate = $instance->enrolstartdate;
                 }
                 // Sort out the given role. This does not filter the roles allowed in the course.
                 if (isset($method['role'])) {
                     $roleids = tool_uploadcourse_helper::get_role_ids();
                     if (isset($roleids[$method['role']])) {
                         $instance->roleid = $roleids[$method['role']];
                     }
                 }
                 $instance->timemodified = time();
                 $DB->update_record('enrol', $instance);
             }
         }
     }
 }
예제 #16
0
 /**
  * Test delete course_module.
  */
 public function test_delete_modules()
 {
     global $DB;
     // Ensure we reset the data after this test.
     $this->resetAfterTest(true);
     // Create a user.
     $user = self::getDataGenerator()->create_user();
     // Set the tests to run as the user.
     self::setUser($user);
     // Create a course to add the modules.
     $course = self::getDataGenerator()->create_course();
     // Create two test modules.
     $record = new stdClass();
     $record->course = $course->id;
     $module1 = self::getDataGenerator()->create_module('forum', $record);
     $module2 = self::getDataGenerator()->create_module('assign', $record);
     // Check the forum was correctly created.
     $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
     // Check the assignment was correctly created.
     $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
     // Check data exists in the course modules table.
     $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2', array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
     // Enrol the user in the course.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance, $user->id);
     // Assign capabilities to delete module 1.
     $modcontext = context_module::instance($module1->cmid);
     $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
     // Assign capabilities to delete module 2.
     $modcontext = context_module::instance($module2->cmid);
     $newrole = create_role('Role 2', 'role2', 'Role 2 description');
     $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
     // Deleting these module instances.
     core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
     // Check the forum was deleted.
     $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
     // Check the assignment was deleted.
     $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
     // Check we retrieve no data in the course modules table.
     $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2', array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
     // Call with non-existent course module id and ensure exception thrown.
     try {
         core_course_external::delete_modules(array('1337'));
         $this->fail('Exception expected due to missing course module.');
     } catch (dml_missing_record_exception $e) {
         $this->assertEquals('invalidcoursemodule', $e->errorcode);
     }
     // Create two modules.
     $module1 = self::getDataGenerator()->create_module('forum', $record);
     $module2 = self::getDataGenerator()->create_module('assign', $record);
     // Since these modules were recreated the user will not have capabilities
     // to delete them, ensure exception is thrown if they try.
     try {
         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
         $this->fail('Exception expected due to missing capability.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Unenrol user from the course.
     $enrol->unenrol_user($instance, $user->id);
     // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
     try {
         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
         $this->fail('Exception expected due to being unenrolled from the course.');
     } catch (moodle_exception $e) {
         $this->assertEquals('requireloginerror', $e->errorcode);
     }
 }
예제 #17
0
 public function test_mod_quiz_get_quizzes_by_courses()
 {
     global $DB;
     // Create additional course.
     $course2 = self::getDataGenerator()->create_course();
     // Second quiz.
     $record = new stdClass();
     $record->course = $course2->id;
     $quiz2 = self::getDataGenerator()->create_module('quiz', $record);
     // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
     self::setUser($this->student);
     $returndescription = mod_quiz_external::get_quizzes_by_courses_returns();
     // Create what we expect to be returned when querying the two courses.
     // First for the student user.
     $allusersfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'timeopen', 'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid');
     $userswithaccessfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks', 'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer', 'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade', 'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks', 'completionattemptsexhausted', 'completionpass', 'autosaveperiod', 'hasquestions', 'hasfeedback', 'overduehandling', 'graceperiod', 'preferredbehaviour', 'canredoquestions');
     $managerfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
     // Add expected coursemodule and other data.
     $quiz1 = $this->quiz;
     $quiz1->coursemodule = $quiz1->cmid;
     $quiz1->introformat = 1;
     $quiz1->section = 0;
     $quiz1->visible = true;
     $quiz1->groupmode = 0;
     $quiz1->groupingid = 0;
     $quiz1->hasquestions = 0;
     $quiz1->hasfeedback = 0;
     $quiz1->autosaveperiod = get_config('quiz', 'autosaveperiod');
     $quiz2->coursemodule = $quiz2->cmid;
     $quiz2->introformat = 1;
     $quiz2->section = 0;
     $quiz2->visible = true;
     $quiz2->groupmode = 0;
     $quiz2->groupingid = 0;
     $quiz2->hasquestions = 0;
     $quiz2->hasfeedback = 0;
     $quiz2->autosaveperiod = get_config('quiz', 'autosaveperiod');
     foreach (array_merge($allusersfields, $userswithaccessfields) as $field) {
         $expected1[$field] = $quiz1->{$field};
         $expected2[$field] = $quiz2->{$field};
     }
     $expectedquizzes = array($expected2, $expected1);
     // Call the external function passing course ids.
     $result = mod_quiz_external::get_quizzes_by_courses(array($course2->id, $this->course->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedquizzes, $result['quizzes']);
     $this->assertCount(0, $result['warnings']);
     // Call the external function without passing course id.
     $result = mod_quiz_external::get_quizzes_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedquizzes, $result['quizzes']);
     $this->assertCount(0, $result['warnings']);
     // Unenrol user from second course and alter expected quizzes.
     $enrol->unenrol_user($instance2, $this->student->id);
     array_shift($expectedquizzes);
     // Call the external function without passing course id.
     $result = mod_quiz_external::get_quizzes_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedquizzes, $result['quizzes']);
     // Call for the second course we unenrolled the user from, expected warning.
     $result = mod_quiz_external::get_quizzes_by_courses(array($course2->id));
     $this->assertCount(1, $result['warnings']);
     $this->assertEquals('1', $result['warnings'][0]['warningcode']);
     $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
     // Now, try as a teacher for getting all the additional fields.
     self::setUser($this->teacher);
     foreach ($managerfields as $field) {
         $expectedquizzes[0][$field] = $quiz1->{$field};
     }
     $result = mod_quiz_external::get_quizzes_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedquizzes, $result['quizzes']);
     // Admin also should get all the information.
     self::setAdminUser();
     $result = mod_quiz_external::get_quizzes_by_courses(array($this->course->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedquizzes, $result['quizzes']);
     // Now, prevent access.
     $enrol->enrol_user($instance2, $this->student->id);
     self::setUser($this->student);
     $quiz2->timeclose = time() - DAYSECS;
     $DB->update_record('quiz', $quiz2);
     $result = mod_quiz_external::get_quizzes_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertCount(2, $result['quizzes']);
     // We only see a limited set of fields.
     $this->assertCount(4, $result['quizzes'][0]);
     $this->assertEquals($quiz2->id, $result['quizzes'][0]['id']);
     $this->assertEquals($quiz2->coursemodule, $result['quizzes'][0]['coursemodule']);
     $this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
     $this->assertEquals($quiz2->name, $result['quizzes'][0]['name']);
     $this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
     $this->assertFalse(isset($result['quizzes'][0]['timelimit']));
 }
예제 #18
0
파일: instances.php 프로젝트: JP-Git/moodle
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$instanceid = optional_param('instance', 0, PARAM_INT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
$context = context_course::instance($course->id, MUST_EXIST);
if ($course->id == SITEID) {
    redirect("{$CFG->wwwroot}/");
}
require_login($course);
require_capability('moodle/course:enrolreview', $context);
$canconfig = has_capability('moodle/course:enrolconfig', $context);
$PAGE->set_url('/enrol/instances.php', array('id' => $course->id));
$PAGE->set_pagelayout('admin');
$PAGE->set_title(get_string('enrolmentinstances', 'enrol'));
$PAGE->set_heading($course->fullname);
$instances = enrol_get_instances($course->id, false);
$plugins = enrol_get_plugins(false);
if ($canconfig and $action and confirm_sesskey()) {
    if (isset($instances[$instanceid]) and isset($plugins[$instances[$instanceid]->enrol])) {
        if ($action === 'up') {
            $order = array_keys($instances);
            $order = array_flip($order);
            $pos = $order[$instanceid];
            if ($pos > 0) {
                $switch = $pos - 1;
                $resorted = array_values($instances);
                $temp = $resorted[$pos];
                $resorted[$pos] = $resorted[$switch];
                $resorted[$switch] = $temp;
                // now update db sortorder
                foreach ($resorted as $sortorder => $instance) {
예제 #19
0
 public function test_mod_wiki_get_wikis_by_courses()
 {
     // Create additional course.
     $course2 = self::getDataGenerator()->create_course();
     // Second wiki.
     $record = new stdClass();
     $record->course = $course2->id;
     $wiki2 = self::getDataGenerator()->create_module('wiki', $record);
     // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
     self::setUser($this->student);
     $returndescription = mod_wiki_external::get_wikis_by_courses_returns();
     // Create what we expect to be returned when querying the two courses.
     // First for the student user.
     $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'firstpagetitle', 'wikimode', 'defaultformat', 'forceformat', 'editbegin', 'editend', 'section', 'visible', 'groupmode', 'groupingid');
     // Add expected coursemodule and data.
     $wiki1 = $this->wiki;
     $wiki1->coursemodule = $wiki1->cmid;
     $wiki1->introformat = 1;
     $wiki1->section = 0;
     $wiki1->visible = true;
     $wiki1->groupmode = 0;
     $wiki1->groupingid = 0;
     $wiki1->introfiles = [];
     $wiki2->coursemodule = $wiki2->cmid;
     $wiki2->introformat = 1;
     $wiki2->section = 0;
     $wiki2->visible = true;
     $wiki2->groupmode = 0;
     $wiki2->groupingid = 0;
     $wiki2->introfiles = [];
     foreach ($expectedfields as $field) {
         $expected1[$field] = $wiki1->{$field};
         $expected2[$field] = $wiki2->{$field};
     }
     // Users can create pages by default.
     $expected1['cancreatepages'] = true;
     $expected2['cancreatepages'] = true;
     $expectedwikis = array($expected2, $expected1);
     // Call the external function passing course ids.
     $result = mod_wiki_external::get_wikis_by_courses(array($course2->id, $this->course->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedwikis, $result['wikis']);
     $this->assertCount(0, $result['warnings']);
     // Call the external function without passing course id.
     $result = mod_wiki_external::get_wikis_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedwikis, $result['wikis']);
     $this->assertCount(0, $result['warnings']);
     // Unenrol user from second course and alter expected wikis.
     $enrol->unenrol_user($instance2, $this->student->id);
     array_shift($expectedwikis);
     // Call the external function without passing course id.
     $result = mod_wiki_external::get_wikis_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedwikis, $result['wikis']);
     // Call for the second course we unenrolled the user from, expected warning.
     $result = mod_wiki_external::get_wikis_by_courses(array($course2->id));
     $this->assertCount(1, $result['warnings']);
     $this->assertEquals('1', $result['warnings'][0]['warningcode']);
     $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
     // Now, try as a teacher for getting all the additional fields.
     self::setUser($this->teacher);
     $additionalfields = array('timecreated', 'timemodified');
     foreach ($additionalfields as $field) {
         $expectedwikis[0][$field] = $wiki1->{$field};
     }
     $result = mod_wiki_external::get_wikis_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedwikis, $result['wikis']);
     // Admin also should get all the information.
     self::setAdminUser();
     $result = mod_wiki_external::get_wikis_by_courses(array($this->course->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedwikis, $result['wikis']);
     // Now, prohibit capabilities.
     $this->setUser($this->student);
     $contextcourse1 = context_course::instance($this->course->id);
     // Prohibit capability = mod:wiki:viewpage on Course1 for students.
     assign_capability('mod/wiki:viewpage', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
     accesslib_clear_all_caches_for_unit_testing();
     $wikis = mod_wiki_external::get_wikis_by_courses(array($this->course->id));
     $wikis = external_api::clean_returnvalue(mod_wiki_external::get_wikis_by_courses_returns(), $wikis);
     $this->assertFalse(isset($wikis['wikis'][0]['intro']));
     // Prohibit capability = mod:wiki:createpage on Course1 for students.
     assign_capability('mod/wiki:createpage', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
     accesslib_clear_all_caches_for_unit_testing();
     $wikis = mod_wiki_external::get_wikis_by_courses(array($this->course->id));
     $wikis = external_api::clean_returnvalue(mod_wiki_external::get_wikis_by_courses_returns(), $wikis);
     $this->assertFalse($wikis['wikis'][0]['cancreatepages']);
 }
예제 #20
0
 /**
  * Test get databases by courses
  */
 public function test_mod_data_get_databases_by_courses()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create users.
     $student = self::getDataGenerator()->create_user();
     $teacher = self::getDataGenerator()->create_user();
     // Set to the student user.
     self::setUser($student);
     // Create courses to add the modules.
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     // First database.
     $record = new stdClass();
     $record->introformat = FORMAT_HTML;
     $record->course = $course1->id;
     $database1 = self::getDataGenerator()->create_module('data', $record);
     // Second database.
     $record = new stdClass();
     $record->introformat = FORMAT_HTML;
     $record->course = $course2->id;
     $database2 = self::getDataGenerator()->create_module('data', $record);
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
     // Users enrolments.
     $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentrole->id, 'manual');
     $this->getDataGenerator()->enrol_user($teacher->id, $course1->id, $teacherrole->id, 'manual');
     // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $student->id, $studentrole->id);
     // Create what we expect to be returned when querying the two courses.
     // First for the student user.
     $expectedfields = array('id', 'coursemodule', 'course', 'name', 'comments', 'timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto', 'requiredentries', 'requiredentriestoview', 'intro', 'introformat');
     // Add expected coursemodule.
     $database1->coursemodule = $database1->cmid;
     $database2->coursemodule = $database2->cmid;
     $expected1 = array();
     $expected2 = array();
     foreach ($expectedfields as $field) {
         $expected1[$field] = $database1->{$field};
         $expected2[$field] = $database2->{$field};
     }
     $expecteddatabases = array();
     $expecteddatabases[] = $expected2;
     $expecteddatabases[] = $expected1;
     // Call the external function passing course ids.
     $result = mod_data_external::get_databases_by_courses(array($course2->id, $course1->id));
     external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
     $this->assertEquals($expecteddatabases, $result['databases']);
     // Call the external function without passing course id.
     $result = mod_data_external::get_databases_by_courses();
     external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
     $this->assertEquals($expecteddatabases, $result['databases']);
     // Unenrol user from second course and alter expected databases.
     $enrol->unenrol_user($instance2, $student->id);
     array_shift($expecteddatabases);
     // Call the external function without passing course id.
     $result = mod_data_external::get_databases_by_courses();
     external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
     $this->assertEquals($expecteddatabases, $result['databases']);
     // Call for the second course we unenrolled the user from, expected warning.
     $result = mod_data_external::get_databases_by_courses(array($course2->id));
     $this->assertCount(1, $result['warnings']);
     $this->assertEquals('2', $result['warnings'][0]['warningcode']);
     $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
     // Now, try as a teacher for getting all the additional fields.
     self::setUser($teacher);
     $additionalfields = array('maxentries', 'rssarticles', 'singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'approval', 'scale', 'assessed', 'assesstimestart', 'assesstimefinish', 'defaultsort', 'defaultsortdir', 'editany', 'notification');
     foreach ($additionalfields as $field) {
         $expecteddatabases[0][$field] = $database1->{$field};
     }
     $result = mod_data_external::get_databases_by_courses();
     external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
     $this->assertEquals($expecteddatabases, $result['databases']);
 }
예제 #21
0
 /**
  * Returns all of the enrolment instances for this course.
  *
  * NOTE: since 2.4 it includes instances of disabled plugins too.
  *
  * @return array
  */
 public function get_enrolment_instances()
 {
     if ($this->_instances === null) {
         $this->_instances = enrol_get_instances($this->course->id, false);
     }
     return $this->_instances;
 }
예제 #22
0
/**
 * Is there a chance users might self enrol
 * @param int $courseid
 * @return bool
 */
function enrol_selfenrol_available($courseid)
{
    $result = false;
    $plugins = enrol_get_plugins(true);
    $enrolinstances = enrol_get_instances($courseid, true);
    foreach ($enrolinstances as $instance) {
        if (!isset($plugins[$instance->enrol])) {
            continue;
        }
        if ($instance->enrol === 'guest') {
            // blacklist known temporary guest plugins
            continue;
        }
        if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
            $result = true;
            break;
        }
    }
    return $result;
}
예제 #23
0
 /**
  * Self enrol the current user in the given course.
  *
  * @param int $courseid id of course
  * @param string $password enrolment key
  * @param int $instanceid instance id of self enrolment plugin
  * @return array of warnings and status result
  * @since Moodle 3.0
  * @throws moodle_exception
  */
 public static function enrol_user($courseid, $password = '', $instanceid = 0)
 {
     global $CFG;
     require_once $CFG->libdir . '/enrollib.php';
     $params = self::validate_parameters(self::enrol_user_parameters(), array('courseid' => $courseid, 'password' => $password, 'instanceid' => $instanceid));
     $warnings = array();
     $course = get_course($params['courseid']);
     $context = context_course::instance($course->id);
     self::validate_context(context_system::instance());
     if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
         throw new moodle_exception('coursehidden');
     }
     // Retrieve the self enrolment plugin.
     $enrol = enrol_get_plugin('self');
     if (empty($enrol)) {
         throw new moodle_exception('canntenrol', 'enrol_self');
     }
     // We can expect multiple self-enrolment instances.
     $instances = array();
     $enrolinstances = enrol_get_instances($course->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "self") {
             // Instance specified.
             if (!empty($params['instanceid'])) {
                 if ($courseenrolinstance->id == $params['instanceid']) {
                     $instances[] = $courseenrolinstance;
                     break;
                 }
             } else {
                 $instances[] = $courseenrolinstance;
             }
         }
     }
     if (empty($instances)) {
         throw new moodle_exception('canntenrol', 'enrol_self');
     }
     // Try to enrol the user in the instance/s.
     $enrolled = false;
     foreach ($instances as $instance) {
         $enrolstatus = $enrol->can_self_enrol($instance);
         if ($enrolstatus === true) {
             if ($instance->password and $params['password'] !== $instance->password) {
                 // Check if we are using group enrolment keys.
                 if ($instance->customint1) {
                     require_once $CFG->dirroot . "/enrol/self/locallib.php";
                     if (!enrol_self_check_group_enrolment_key($course->id, $params['password'])) {
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '2', 'message' => get_string('passwordinvalid', 'enrol_self'));
                         continue;
                     }
                 } else {
                     if ($enrol->get_config('showhint')) {
                         $hint = core_text::substr($instance->password, 0, 1);
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '3', 'message' => s(get_string('passwordinvalidhint', 'enrol_self', $hint)));
                         continue;
                     } else {
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '4', 'message' => get_string('passwordinvalid', 'enrol_self'));
                         continue;
                     }
                 }
             }
             // Do the enrolment.
             $data = array('enrolpassword' => $params['password']);
             $enrol->enrol_self($instance, (object) $data);
             $enrolled = true;
             break;
         } else {
             $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '1', 'message' => $enrolstatus);
         }
     }
     $result = array();
     $result['status'] = $enrolled;
     $result['warnings'] = $warnings;
     return $result;
 }
예제 #24
0
파일: moodlelib.php 프로젝트: hitphp/moodle
/**
 * This function will empty a course of user data.
 * It will retain the activities and the structure of the course.
 *
 * @param object $data an object containing all the settings including courseid (without magic quotes)
 * @return array status array of array component, item, error
 */
function reset_course_userdata($data)
{
    global $CFG, $USER, $DB;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->libdir . '/completionlib.php';
    require_once $CFG->dirroot . '/group/lib.php';
    $data->courseid = $data->id;
    $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
    // calculate the time shift of dates
    if (!empty($data->reset_start_date)) {
        // time part of course startdate should be zero
        $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
    } else {
        $data->timeshift = 0;
    }
    // result array: component, item, error
    $status = array();
    // start the resetting
    $componentstr = get_string('general');
    // move the course start time
    if (!empty($data->reset_start_date) and $data->timeshift) {
        // change course start data
        $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
        // update all course and group events - do not move activity events
        $updatesql = "UPDATE {event}\n                         SET timestart = timestart + ?\n                       WHERE courseid=? AND instance=0";
        $DB->execute($updatesql, array($data->timeshift, $data->courseid));
        $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
    }
    if (!empty($data->reset_logs)) {
        $DB->delete_records('log', array('course' => $data->courseid));
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
    }
    if (!empty($data->reset_events)) {
        $DB->delete_records('event', array('courseid' => $data->courseid));
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
    }
    if (!empty($data->reset_notes)) {
        require_once $CFG->dirroot . '/notes/lib.php';
        note_delete_all($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
    }
    if (!empty($data->delete_blog_associations)) {
        require_once $CFG->dirroot . '/blog/lib.php';
        blog_remove_associations_for_course($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
    }
    if (!empty($data->reset_course_completion)) {
        // Delete course completion information
        $course = $DB->get_record('course', array('id' => $data->courseid));
        $cc = new completion_info($course);
        $cc->delete_course_completion_data();
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecoursecompletiondata', 'completion'), 'error' => false);
    }
    $componentstr = get_string('roles');
    if (!empty($data->reset_roles_overrides)) {
        $children = get_child_contexts($context);
        foreach ($children as $child) {
            $DB->delete_records('role_capabilities', array('contextid' => $child->id));
        }
        $DB->delete_records('role_capabilities', array('contextid' => $context->id));
        //force refresh for logged in users
        mark_context_dirty($context->path);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
    }
    if (!empty($data->reset_roles_local)) {
        $children = get_child_contexts($context);
        foreach ($children as $child) {
            role_unassign_all(array('contextid' => $child->id));
        }
        //force refresh for logged in users
        mark_context_dirty($context->path);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
    }
    // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
    $data->unenrolled = array();
    if (!empty($data->unenrol_users)) {
        $plugins = enrol_get_plugins(true);
        $instances = enrol_get_instances($data->courseid, true);
        foreach ($instances as $key => $instance) {
            if (!isset($plugins[$instance->enrol])) {
                unset($instances[$key]);
                continue;
            }
            if (!$plugins[$instance->enrol]->allow_unenrol($instance)) {
                unset($instances[$key]);
            }
        }
        $sqlempty = $DB->sql_empty();
        foreach ($data->unenrol_users as $withroleid) {
            $sql = "SELECT DISTINCT ue.userid, ue.enrolid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)\n                      JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)\n                      JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
            $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
            $rs = $DB->get_recordset_sql($sql, $params);
            foreach ($rs as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    continue;
                }
                $plugins[$instances[$ue->enrolid]->enrol]->unenrol_user($instances[$ue->enrolid], $ue->userid);
                $data->unenrolled[$ue->userid] = $ue->userid;
            }
        }
    }
    if (!empty($data->unenrolled)) {
        $status[] = array('component' => $componentstr, 'item' => get_string('unenrol', 'enrol') . ' (' . count($data->unenrolled) . ')', 'error' => false);
    }
    $componentstr = get_string('groups');
    // remove all group members
    if (!empty($data->reset_groups_members)) {
        groups_delete_group_members($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
    }
    // remove all groups
    if (!empty($data->reset_groups_remove)) {
        groups_delete_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
    }
    // remove all grouping members
    if (!empty($data->reset_groupings_members)) {
        groups_delete_groupings_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
    }
    // remove all groupings
    if (!empty($data->reset_groupings_remove)) {
        groups_delete_groupings($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
    }
    // Look in every instance of every module for data to delete
    $unsupported_mods = array();
    if ($allmods = $DB->get_records('modules')) {
        foreach ($allmods as $mod) {
            $modname = $mod->name;
            if (!$DB->count_records($modname, array('course' => $data->courseid))) {
                continue;
                // skip mods with no instances
            }
            $modfile = $CFG->dirroot . '/mod/' . $modname . '/lib.php';
            $moddeleteuserdata = $modname . '_reset_userdata';
            // Function to delete user data
            if (file_exists($modfile)) {
                include_once $modfile;
                if (function_exists($moddeleteuserdata)) {
                    $modstatus = $moddeleteuserdata($data);
                    if (is_array($modstatus)) {
                        $status = array_merge($status, $modstatus);
                    } else {
                        debugging('Module ' . $modname . ' returned incorrect staus - must be an array!');
                    }
                } else {
                    $unsupported_mods[] = $mod;
                }
            } else {
                debugging('Missing lib.php in ' . $modname . ' module!');
            }
        }
    }
    // mention unsupported mods
    if (!empty($unsupported_mods)) {
        foreach ($unsupported_mods as $mod) {
            $status[] = array('component' => get_string('modulenameplural', $mod->name), 'item' => '', 'error' => get_string('resetnotimplemented'));
        }
    }
    $componentstr = get_string('gradebook', 'grades');
    // reset gradebook
    if (!empty($data->reset_gradebook_items)) {
        remove_course_grades($data->courseid, false);
        grade_grab_course_grades($data->courseid);
        grade_regrade_final_grades($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
    } else {
        if (!empty($data->reset_gradebook_grades)) {
            grade_course_reset($data->courseid);
            $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
        }
    }
    // reset comments
    if (!empty($data->reset_comments)) {
        require_once $CFG->dirroot . '/comment/lib.php';
        comment::reset_course_page_comments($context);
    }
    return $status;
}
 /**
  * Test get forum discussions
  */
 public function test_mod_anonforum_get_anonforum_discussions()
 {
     global $USER, $CFG, $DB;
     $this->resetAfterTest(true);
     // Set the CFG variable to allow track forums.
     $CFG->anonforum_trackreadposts = true;
     // Create a user who can track forums.
     $record = new stdClass();
     $record->trackforums = true;
     $user1 = self::getDataGenerator()->create_user($record);
     // Create a bunch of other users to post.
     $user2 = self::getDataGenerator()->create_user();
     $user3 = self::getDataGenerator()->create_user();
     $user4 = self::getDataGenerator()->create_user();
     // Set the first created user to the test user.
     self::setUser($user1);
     // Create courses to add the modules.
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     // First forum with tracking off.
     $record = new stdClass();
     $record->course = $course1->id;
     $record->trackingtype = FORUM_TRACKING_OFF;
     $anonforum1 = self::getDataGenerator()->create_module('anonforum', $record);
     // Second forum of type 'qanda' with tracking enabled.
     $record = new stdClass();
     $record->course = $course2->id;
     $record->type = 'qanda';
     $record->trackingtype = FORUM_TRACKING_FORCED;
     $anonforum2 = self::getDataGenerator()->create_module('anonforum', $record);
     // Third forum where we will only have one discussion with no replies.
     $record = new stdClass();
     $record->course = $course2->id;
     $anonforum3 = self::getDataGenerator()->create_module('anonforum', $record);
     // Add discussions to the forums.
     $record = new stdClass();
     $record->course = $course1->id;
     $record->userid = $user1->id;
     $record->anonforum = $anonforum1->id;
     $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     $record = new stdClass();
     $record->course = $course2->id;
     $record->userid = $user2->id;
     $record->anonforum = $anonforum2->id;
     $discussion2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     $record = new stdClass();
     $record->course = $course2->id;
     $record->userid = $user2->id;
     $record->anonforum = $anonforum3->id;
     $discussion3 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     // Add three replies to the discussion 1 from different users.
     $record = new stdClass();
     $record->discussion = $discussion1->id;
     $record->parent = $discussion1->firstpost;
     $record->userid = $user2->id;
     $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->parent = $discussion1reply1->id;
     $record->userid = $user3->id;
     $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->userid = $user4->id;
     $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     // Add two replies to discussion 2 from different users.
     $record = new stdClass();
     $record->discussion = $discussion2->id;
     $record->parent = $discussion2->firstpost;
     $record->userid = $user1->id;
     $discussion2reply1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->parent = $discussion2reply1->id;
     $record->userid = $user3->id;
     $discussion2reply2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     // Check the forums were correctly created.
     $this->assertEquals(3, $DB->count_records_select('anonforum', 'id = :anonforum1 OR id = :anonforum2 OR id = :anonforum3', array('anonforum1' => $anonforum1->id, 'anonforum2' => $anonforum2->id, 'anonforum3' => $anonforum3->id)));
     // Check the discussions were correctly created.
     $this->assertEquals(3, $DB->count_records_select('anonforum_discussions', 'anonforum = :anonforum1 OR anonforum = :anonforum2 OR anonforum = :anonforum3', array('anonforum1' => $anonforum1->id, 'anonforum2' => $anonforum2->id, 'anonforum3' => $anonforum3->id)));
     // Check the posts were correctly created, don't forget each discussion created also creates a post.
     $this->assertEquals(7, $DB->count_records_select('anonforum_posts', 'discussion = :discussion1 OR discussion = :discussion2', array('discussion1' => $discussion1->id, 'discussion2' => $discussion2->id)));
     // Enrol the user in the first course.
     $enrol = enrol_get_plugin('manual');
     // Following line enrol and assign default role id to the user.
     // So the user automatically gets mod/anonforum:viewdiscussion on all forums of the course.
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
     // Now enrol into the second course.
     // We don't use the dataGenerator as we need to get the $instance2 to unenrol later.
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $user1->id);
     // Assign capabilities to view discussions for forum 2.
     $cm = get_coursemodule_from_id('anonforum', $anonforum2->cmid, 0, false, MUST_EXIST);
     $context = context_module::instance($cm->id);
     $newrole = create_role('Role 2', 'role2', 'Role 2 description');
     $this->assignUserCapability('mod/anonforum:viewdiscussion', $context->id, $newrole);
     // Assign capabilities to view discussions for forum 3.
     $cm = get_coursemodule_from_id('anonforum', $anonforum3->cmid, 0, false, MUST_EXIST);
     $context = context_module::instance($cm->id);
     $this->assignUserCapability('mod/anonforum:viewdiscussion', $context->id, $newrole);
     // Create what we expect to be returned when querying the forums.
     $expecteddiscussions = array();
     $expecteddiscussions[$discussion1->id] = array('id' => $discussion1->id, 'course' => $discussion1->course, 'anonforum' => $discussion1->anonforum, 'name' => $discussion1->name, 'firstpost' => $discussion1->firstpost, 'userid' => $discussion1->userid, 'groupid' => $discussion1->groupid, 'assessed' => $discussion1->assessed, 'timemodified' => $discussion1reply3->created, 'usermodified' => $discussion1reply3->userid, 'timestart' => $discussion1->timestart, 'timeend' => $discussion1->timeend, 'firstuserfullname' => fullname($user1), 'firstuserimagealt' => $user1->imagealt, 'firstuserpicture' => $user1->picture, 'firstuseremail' => $user1->email, 'subject' => $discussion1->name, 'numreplies' => 3, 'numunread' => '', 'lastpost' => $discussion1reply3->id, 'lastuserid' => $user4->id, 'lastuserfullname' => fullname($user4), 'lastuserimagealt' => $user4->imagealt, 'lastuserpicture' => $user4->picture, 'lastuseremail' => $user4->email);
     $expecteddiscussions[$discussion2->id] = array('id' => $discussion2->id, 'course' => $discussion2->course, 'anonforum' => $discussion2->anonforum, 'name' => $discussion2->name, 'firstpost' => $discussion2->firstpost, 'userid' => $discussion2->userid, 'groupid' => $discussion2->groupid, 'assessed' => $discussion2->assessed, 'timemodified' => $discussion2reply2->created, 'usermodified' => $discussion2reply2->userid, 'timestart' => $discussion2->timestart, 'timeend' => $discussion2->timeend, 'firstuserfullname' => fullname($user2), 'firstuserimagealt' => $user2->imagealt, 'firstuserpicture' => $user2->picture, 'firstuseremail' => $user2->email, 'subject' => $discussion2->name, 'numreplies' => 2, 'numunread' => 3, 'lastpost' => $discussion2reply2->id, 'lastuserid' => $user3->id, 'lastuserfullname' => fullname($user3), 'lastuserimagealt' => $user3->imagealt, 'lastuserpicture' => $user3->picture, 'lastuseremail' => $user3->email);
     $expecteddiscussions[$discussion3->id] = array('id' => $discussion3->id, 'course' => $discussion3->course, 'anonforum' => $discussion3->anonforum, 'name' => $discussion3->name, 'firstpost' => $discussion3->firstpost, 'userid' => $discussion3->userid, 'groupid' => $discussion3->groupid, 'assessed' => $discussion3->assessed, 'timemodified' => $discussion3->timemodified, 'usermodified' => $discussion3->usermodified, 'timestart' => $discussion3->timestart, 'timeend' => $discussion3->timeend, 'firstuserfullname' => fullname($user2), 'firstuserimagealt' => $user2->imagealt, 'firstuserpicture' => $user2->picture, 'firstuseremail' => $user2->email, 'subject' => $discussion3->name, 'numreplies' => 0, 'numunread' => 1, 'lastpost' => $discussion3->firstpost, 'lastuserid' => $user2->id, 'lastuserfullname' => fullname($user2), 'lastuserimagealt' => $user2->imagealt, 'lastuserpicture' => $user2->picture, 'lastuseremail' => $user2->email);
     // Call the external function passing forum ids.
     $discussions = mod_anonforum_external::get_anonforum_discussions(array($anonforum1->id, $anonforum2->id, $anonforum3->id));
     external_api::clean_returnvalue(mod_anonforum_external::get_anonforum_discussions_returns(), $discussions);
     $this->assertEquals($expecteddiscussions, $discussions);
     // Remove the users post from the qanda forum and ensure they can not return the discussion.
     $DB->delete_records('anonforum_posts', array('id' => $discussion2reply1->id));
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum2->id));
         $this->fail('Exception expected due to attempting to access qanda forum without posting.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Call without required view discussion capability.
     $this->unassignUserCapability('mod/anonforum:viewdiscussion', null, null, $course1->id);
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum1->id));
         $this->fail('Exception expected due to missing capability.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Unenrol user from second course.
     $enrol->unenrol_user($instance2, $user1->id);
     // Call for the second course we unenrolled the user from, make sure exception thrown.
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum2->id));
         $this->fail('Exception expected due to being unenrolled from the course.');
     } catch (moodle_exception $e) {
         $this->assertEquals('requireloginerror', $e->errorcode);
     }
 }
예제 #26
0
 /**
  * Get list of active course enrolment methods for current user.
  *
  * @param int $courseid
  * @return array of course enrolment methods
  * @throws moodle_exception
  */
 public static function get_course_enrolment_methods($courseid)
 {
     global $DB;
     $params = self::validate_parameters(self::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
     self::validate_context(context_system::instance());
     $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
     $context = context_course::instance($course->id);
     if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
         throw new moodle_exception('coursehidden');
     }
     $result = array();
     $enrolinstances = enrol_get_instances($params['courseid'], true);
     foreach ($enrolinstances as $enrolinstance) {
         if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol)) {
             if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
                 $result[] = (array) $instanceinfo;
             }
         }
     }
     return $result;
 }
예제 #27
0
 public function test_mod_scorm_get_scorms_by_courses()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create users.
     $student = self::getDataGenerator()->create_user();
     $teacher = self::getDataGenerator()->create_user();
     // Set to the student user.
     self::setUser($student);
     // Create courses to add the modules.
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     // First scorm.
     $record = new stdClass();
     $record->introformat = FORMAT_HTML;
     $record->course = $course1->id;
     $record->hidetoc = 2;
     $record->displayattemptstatus = 2;
     $record->skipview = 2;
     $scorm1 = self::getDataGenerator()->create_module('scorm', $record);
     // Second scorm.
     $record = new stdClass();
     $record->introformat = FORMAT_HTML;
     $record->course = $course2->id;
     $scorm2 = self::getDataGenerator()->create_module('scorm', $record);
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
     // Users enrolments.
     $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentrole->id, 'manual');
     $this->getDataGenerator()->enrol_user($teacher->id, $course1->id, $teacherrole->id, 'manual');
     // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $student->id, $studentrole->id);
     $returndescription = mod_scorm_external::get_scorms_by_courses_returns();
     // Test open/close dates.
     $timenow = time();
     $scorm1->timeopen = $timenow - DAYSECS;
     $scorm1->timeclose = $timenow - HOURSECS;
     $DB->update_record('scorm', $scorm1);
     $result = mod_scorm_external::get_scorms_by_courses(array($course1->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertCount(1, $result['warnings']);
     // Only 'id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles'.
     $this->assertCount(7, $result['scorms'][0]);
     $this->assertEquals('expired', $result['warnings'][0]['warningcode']);
     $scorm1->timeopen = $timenow + DAYSECS;
     $scorm1->timeclose = $scorm1->timeopen + DAYSECS;
     $DB->update_record('scorm', $scorm1);
     $result = mod_scorm_external::get_scorms_by_courses(array($course1->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertCount(1, $result['warnings']);
     // Only 'id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles'.
     $this->assertCount(7, $result['scorms'][0]);
     $this->assertEquals('notopenyet', $result['warnings'][0]['warningcode']);
     // Reset times.
     $scorm1->timeopen = 0;
     $scorm1->timeclose = 0;
     $DB->update_record('scorm', $scorm1);
     // Create what we expect to be returned when querying the two courses.
     // First for the student user.
     $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'version', 'maxgrade', 'grademethod', 'whatgrade', 'maxattempt', 'forcecompleted', 'forcenewattempt', 'lastattemptlock', 'displayattemptstatus', 'displaycoursestructure', 'sha1hash', 'md5hash', 'revision', 'launch', 'skipview', 'hidebrowse', 'hidetoc', 'nav', 'navpositionleft', 'navpositiontop', 'auto', 'popup', 'width', 'height', 'timeopen', 'timeclose', 'displayactivityname', 'packagesize', 'packageurl', 'scormtype', 'reference');
     // Add expected coursemodule and data.
     $scorm1->coursemodule = $scorm1->cmid;
     $scorm1->section = 0;
     $scorm1->visible = true;
     $scorm1->groupmode = 0;
     $scorm1->groupingid = 0;
     $scorm2->coursemodule = $scorm2->cmid;
     $scorm2->section = 0;
     $scorm2->visible = true;
     $scorm2->groupmode = 0;
     $scorm2->groupingid = 0;
     // SCORM size. The same package is used in both SCORMs.
     $scormcontext1 = context_module::instance($scorm1->cmid);
     $scormcontext2 = context_module::instance($scorm2->cmid);
     $fs = get_file_storage();
     $packagefile = $fs->get_file($scormcontext1->id, 'mod_scorm', 'package', 0, '/', $scorm1->reference);
     $packagesize = $packagefile->get_filesize();
     $packageurl1 = moodle_url::make_webservice_pluginfile_url($scormcontext1->id, 'mod_scorm', 'package', 0, '/', $scorm1->reference)->out(false);
     $packageurl2 = moodle_url::make_webservice_pluginfile_url($scormcontext2->id, 'mod_scorm', 'package', 0, '/', $scorm2->reference)->out(false);
     $scorm1->packagesize = $packagesize;
     $scorm1->packageurl = $packageurl1;
     $scorm2->packagesize = $packagesize;
     $scorm2->packageurl = $packageurl2;
     // Forced to boolean as it is returned as PARAM_BOOL.
     $protectpackages = (bool) get_config('scorm', 'protectpackagedownloads');
     $expected1 = array('protectpackagedownloads' => $protectpackages);
     $expected2 = array('protectpackagedownloads' => $protectpackages);
     foreach ($expectedfields as $field) {
         // Since we return the fields used as boolean as PARAM_BOOL instead PARAM_INT we need to force casting here.
         // From the returned fields definition we obtain the type expected for the field.
         if (empty($returndescription->keys['scorms']->content->keys[$field]->type)) {
             continue;
         }
         $fieldtype = $returndescription->keys['scorms']->content->keys[$field]->type;
         if ($fieldtype == PARAM_BOOL) {
             $expected1[$field] = (bool) $scorm1->{$field};
             $expected2[$field] = (bool) $scorm2->{$field};
         } else {
             $expected1[$field] = $scorm1->{$field};
             $expected2[$field] = $scorm2->{$field};
         }
     }
     $expected1['introfiles'] = [];
     $expected2['introfiles'] = [];
     $expectedscorms = array();
     $expectedscorms[] = $expected2;
     $expectedscorms[] = $expected1;
     // Call the external function passing course ids.
     $result = mod_scorm_external::get_scorms_by_courses(array($course2->id, $course1->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
     // Call the external function without passing course id.
     $result = mod_scorm_external::get_scorms_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
     // Unenrol user from second course and alter expected scorms.
     $enrol->unenrol_user($instance2, $student->id);
     array_shift($expectedscorms);
     // Call the external function without passing course id.
     $result = mod_scorm_external::get_scorms_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
     // Call for the second course we unenrolled the user from, expected warning.
     $result = mod_scorm_external::get_scorms_by_courses(array($course2->id));
     $this->assertCount(1, $result['warnings']);
     $this->assertEquals('1', $result['warnings'][0]['warningcode']);
     $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
     // Now, try as a teacher for getting all the additional fields.
     self::setUser($teacher);
     $additionalfields = array('updatefreq', 'timemodified', 'options', 'completionstatusrequired', 'completionscorerequired', 'completionstatusallscos', 'autocommit', 'section', 'visible', 'groupmode', 'groupingid');
     foreach ($additionalfields as $field) {
         $fieldtype = $returndescription->keys['scorms']->content->keys[$field]->type;
         if ($fieldtype == PARAM_BOOL) {
             $expectedscorms[0][$field] = (bool) $scorm1->{$field};
         } else {
             $expectedscorms[0][$field] = $scorm1->{$field};
         }
     }
     $result = mod_scorm_external::get_scorms_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
     // Even with the SCORM closed in time teacher should retrieve the info.
     $scorm1->timeopen = $timenow - DAYSECS;
     $scorm1->timeclose = $timenow - HOURSECS;
     $DB->update_record('scorm', $scorm1);
     $expectedscorms[0]['timeopen'] = $scorm1->timeopen;
     $expectedscorms[0]['timeclose'] = $scorm1->timeclose;
     $result = mod_scorm_external::get_scorms_by_courses();
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
     // Admin also should get all the information.
     self::setAdminUser();
     $result = mod_scorm_external::get_scorms_by_courses(array($course1->id));
     $result = external_api::clean_returnvalue($returndescription, $result);
     $this->assertEquals($expectedscorms, $result['scorms']);
 }
예제 #28
0
if ($course->id == SITEID) {
    redirect("{$CFG->wwwroot}/");
}
if (!$course->visible && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
    print_error('coursehidden');
}
$PAGE->set_course($course);
$PAGE->set_pagelayout('course');
$PAGE->set_url('/enrol/index.php', array('id' => $course->id));
// do not allow enrols when in login-as session
if (\core\session\manager::is_loggedinas() and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
    print_error('loginasnoenrol', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
}
// get all enrol forms available in this course
$enrols = enrol_get_plugins(true);
$enrolinstances = enrol_get_instances($course->id, true);
$forms = array();
foreach ($enrolinstances as $instance) {
    if (!isset($enrols[$instance->enrol])) {
        continue;
    }
    $form = $enrols[$instance->enrol]->enrol_page_hook($instance);
    if ($form) {
        $forms[$instance->id] = $form;
    }
}
// Check if user already enrolled
if (is_enrolled($context, $USER, '', true)) {
    if (!empty($SESSION->wantsurl)) {
        $destination = $SESSION->wantsurl;
        unset($SESSION->wantsurl);
예제 #29
0
 }
 $shortname = $user->{'course' . $i};
 if (!array_key_exists($shortname, $ccache)) {
     if (!($course = $DB->get_record('course', array('shortname' => $shortname), 'id, shortname'))) {
         $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
         continue;
     }
     $ccache[$shortname] = $course;
     $ccache[$shortname]->groups = null;
 }
 $courseid = $ccache[$shortname]->id;
 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
 if (!isset($manualcache[$courseid])) {
     $manualcache[$courseid] = false;
     if ($manual) {
         if ($instances = enrol_get_instances($courseid, false)) {
             foreach ($instances as $instance) {
                 if ($instance->enrol === 'manual') {
                     $manualcache[$courseid] = $instance;
                     break;
                 }
             }
         }
     }
 }
 if ($manual and $manualcache[$courseid]) {
     // find role
     $rid = false;
     if (!empty($user->{'role' . $i})) {
         $addrole = $user->{'role' . $i};
         if (array_key_exists($addrole, $rolecache)) {
예제 #30
0
 public function get_instance($course)
 {
     $enrolinstances = enrol_get_instances($course->id, true);
     $instance = null;
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "saml") {
             $instance = $courseenrolinstance;
             break;
         }
     }
     return $instance;
 }