Check if a Section or Activity is accessible to user in Moodle

| By Webner

In Moodle a course can have multiple sections and each section can have multiple activities in it. Moodle provides access restrictions feature in course in which we can impose some restrictions to section or activity based on date, completion, group ,score etc. If a user does not satisfy the required conditions then he will not be able to access that section or activity. Either the activity will be hidden or it could be grayed out.

Define Restrictions on Moodle Course Activity :
While creating an activity add restrictions in Restrict access column :

In the above image we have added 2 restrictions on activity :

1. Student must belong to group colleen
2. Student must receive a grade in Session One : Part Three activity.

Now on UI the activity will be displayed as :

The restrictions gets saved in availability column in course_modules table in moodle database in complex form as shown below :


But this format is complex and cannot be parsed and used in custom code if needed.
The solution is to use inbuilt methods of Moodle.

For section use the following code to find out whether the logged in user satisfies the restrictions or not :

$course = $DB->get_record('course', array('id' => $courseId)); //get course object
$modinfo = get_fast_modinfo($course); //Returns reference to full info about modules in course
$sections = $modinfo->get_section_info_all(); //get all sections information from modules
$thissection = $sections[0];//get particular section info with index
if ($thissection->available) {
print(‘user can access this section’);
print(‘user can’t access this section’);

For activity use the following code to find out whether it user satisfies the restrictions or not :

$cm = $modinfo->get_cm($activity['moduleid']);
if ($cm->availableinfo) {
echo “user cannot access the activity, but on the course page they will see a link to it, greyed-out”;
else if ($cm->uservisible) {
echo "user can access the activity";
echo "user cannot access the activity";

Leave a Reply

Your email address will not be published. Required fields are marked *