Programatically add access restriction to a course section

Re: Programatically add access restriction to a course section

by Jose R. Aguilar -
Number of replies: 0

I found a way to restrict access to a section of a course for a group, I don't know if this is the best way to do that, but it works for my purpose.

This is the code:

/**
 * giving permits to a group for a particular section of a course
 *
 * @param $course course that contains the section to restrict access
 * @param $sectionid id of the section to restrict access
 * @param $groupid id of the group will have access
 *
 */
function grantPermission($course, $sectionid, $groupid ){

    global $DB;

    $restriction = '{"op":"&","c":[{"type":"group","id":'. $groupid .'}],"showc":[true]}';

    $module = $DB->get_record('course_modules', array('course' => $course , 'section' => $sectionid ), '*', MUST_EXIST);

    $course_module = new stdClass();
    $course_module->id = $module->id;
    $course_module->course = $course;
    $course_module->section = $sectionid;
    $course_module->availability = $restriction;

    $res = $DB->update_record('course_modules', $course_module);

    if($res)
        rebuild_course_cache($course, true);    

    return $res;
}