/**
  * Group created
  *
  * @param \core\event\group_created $event
  * @return void
  */
 public static function group_created(\core\event\group_created $event)
 {
     global $DB;
     $group = $event->get_record_snapshot('groups', $event->objectid);
     $courseids = local_metagroups_parent_courses($group->courseid);
     foreach ($courseids as $courseid) {
         $course = get_course($courseid);
         // If parent course doesn't use groups, we can skip synchronization.
         if (groups_get_course_groupmode($course) == NOGROUPS) {
             continue;
         }
         if (!$DB->record_exists('groups', array('courseid' => $course->id, 'idnumber' => $group->id))) {
             $metagroup = new \stdClass();
             $metagroup->courseid = $course->id;
             $metagroup->idnumber = $group->id;
             $metagroup->name = $group->name;
             groups_create_group($metagroup, false, false);
         }
     }
 }
 /**
  *
  * @uses $CFG
  * @uses $USER
  */
 function display_filemanager_link()
 {
     global $CFG, $USER;
     if (!($course = get_record('course', 'id', $this->instance->pageid))) {
         error("Course ID is incorrect");
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
     $canmanagegroups = has_capability('block/file_manager:canmanagegroups', $coursecontext);
     $this->content->items[] = "<a title=\"" . get_string('msgfilemanager', 'block_file_manager') . "\" href=\"{$CFG->wwwroot}/blocks/file_manager/view.php?id={$this->instance->pageid}&groupid=0\">" . get_string('myfiles', 'block_file_manager') . "</a>";
     $this->content->icons[] = "<img src=\"{$CFG->pixpath}/i/files.gif\" alt=\"\" />";
     // If the user is member of any group of this course, links for each group in which he belongs must be displayed
     $groupmode = groups_get_course_groupmode($course);
     $groupsarray = array();
     switch ($groupmode) {
         case NOGROUPS:
             // Nothing to display
             break;
         case SEPARATEGROUPS:
             if ($canmanagegroups) {
                 // Displays all groups because of super rights
                 $groupsarray = groups_get_all_groups($this->instance->pageid);
             } else {
                 // Display only links for groups in which the user is member
                 $groupsarray = groups_get_all_groups($this->instance->pageid, $USER->id);
             }
             break;
         case VISIBLEGROUPS:
             // Display a link for all groups
             $groupsarray = groups_get_all_groups($this->instance->pageid);
             break;
     }
     // Displays group links if user in a group.
     if (is_array($groupsarray)) {
         foreach ($groupsarray as $groupid => $value) {
             $this->content->items[] = "<a title=\"" . get_string('msgfilemanagergroup', 'block_file_manager') . "\" href=\"{$CFG->wwwroot}/blocks/file_manager/view.php?id={$this->instance->pageid}&groupid={$groupid}\">" . groups_get_group_name($groupid) . "</a>";
             $this->content->icons[] = "<img src=\"{$CFG->pixpath}/i/files.gif\" alt=\"\" />";
         }
     }
 }
/**
 * Run synchronization process
 *
 * @param progress_trace $trace
 * @param int|null $courseid or null for all courses
 * @return void
 */
function local_metagroups_sync(progress_trace $trace, $courseid = null)
{
    global $DB;
    if ($courseid !== null) {
        $courseids = array($courseid);
    } else {
        $courseids = local_metagroups_parent_courses();
    }
    foreach (array_unique($courseids) as $courseid) {
        $parent = get_course($courseid);
        // If parent course doesn't use groups, we can skip synchronization.
        if (groups_get_course_groupmode($parent) == NOGROUPS) {
            continue;
        }
        $trace->output($parent->fullname, 1);
        $children = local_metagroups_child_courses($parent->id);
        foreach ($children as $childid) {
            $child = get_course($childid);
            $trace->output($child->fullname, 2);
            $groups = groups_get_all_groups($child->id);
            foreach ($groups as $group) {
                if (!($metagroup = $DB->get_record('groups', array('courseid' => $parent->id, 'idnumber' => $group->id)))) {
                    $metagroup = new stdClass();
                    $metagroup->courseid = $parent->id;
                    $metagroup->idnumber = $group->id;
                    $metagroup->name = $group->name;
                    $metagroup->id = groups_create_group($metagroup, false, false);
                }
                $trace->output($metagroup->name, 3);
                $users = groups_get_members($group->id);
                foreach ($users as $user) {
                    groups_add_member($metagroup->id, $user->id, 'local_metagroups', $group->id);
                }
            }
        }
    }
}
Exemple #4
0
 /**
  * Get course participants details
  *
  * @param int $courseid  course id
  * @param array $options options {
  *                                'name' => option name
  *                                'value' => option value
  *                               }
  * @return array An array of users
  */
 public static function get_enrolled_users($courseid, $options = array())
 {
     global $CFG, $USER, $DB;
     require_once $CFG->dirroot . "/user/lib.php";
     $params = self::validate_parameters(self::get_enrolled_users_parameters(), array('courseid' => $courseid, 'options' => $options));
     $withcapability = '';
     $groupid = 0;
     $onlyactive = false;
     $userfields = array();
     $limitfrom = 0;
     $limitnumber = 0;
     $sortby = 'us.id';
     $sortparams = array();
     $sortdirection = 'ASC';
     foreach ($options as $option) {
         switch ($option['name']) {
             case 'withcapability':
                 $withcapability = $option['value'];
                 break;
             case 'groupid':
                 $groupid = (int) $option['value'];
                 break;
             case 'onlyactive':
                 $onlyactive = !empty($option['value']);
                 break;
             case 'userfields':
                 $thefields = explode(',', $option['value']);
                 foreach ($thefields as $f) {
                     $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
                 }
                 break;
             case 'limitfrom':
                 $limitfrom = clean_param($option['value'], PARAM_INT);
                 break;
             case 'limitnumber':
                 $limitnumber = clean_param($option['value'], PARAM_INT);
                 break;
             case 'sortby':
                 $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
                 if (!in_array($option['value'], $sortallowedvalues)) {
                     throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' . 'allowed values are: ' . implode(',', $sortallowedvalues));
                 }
                 if ($option['value'] == 'siteorder') {
                     list($sortby, $sortparams) = users_order_by_sql('us');
                 } else {
                     $sortby = 'us.' . $option['value'];
                 }
                 break;
             case 'sortdirection':
                 $sortdirection = strtoupper($option['value']);
                 $directionallowedvalues = array('ASC', 'DESC');
                 if (!in_array($sortdirection, $directionallowedvalues)) {
                     throw new invalid_parameter_exception('Invalid value for sortdirection parameter
                     (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
                 }
                 break;
         }
     }
     $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
     $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
     if ($courseid == SITEID) {
         $context = context_system::instance();
     } else {
         $context = $coursecontext;
     }
     try {
         self::validate_context($context);
     } catch (Exception $e) {
         $exceptionparam = new stdClass();
         $exceptionparam->message = $e->getMessage();
         $exceptionparam->courseid = $params['courseid'];
         throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
     }
     if ($courseid == SITEID) {
         require_capability('moodle/site:viewparticipants', $context);
     } else {
         require_capability('moodle/course:viewparticipants', $context);
     }
     // to overwrite this parameter, you need role:review capability
     if ($withcapability) {
         require_capability('moodle/role:review', $coursecontext);
     }
     // need accessallgroups capability if you want to overwrite this option
     if (!empty($groupid) && !groups_is_member($groupid)) {
         require_capability('moodle/site:accessallgroups', $coursecontext);
     }
     // to overwrite this option, you need course:enrolereview permission
     if ($onlyactive) {
         require_capability('moodle/course:enrolreview', $coursecontext);
     }
     list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
     $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
     $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
     $enrolledparams['contextlevel'] = CONTEXT_USER;
     $groupjoin = '';
     if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
         // Filter by groups the user can view.
         $usergroups = groups_get_user_groups($course->id);
         if (!empty($usergroups['0'])) {
             list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED);
             $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid {$groupsql})";
             $enrolledparams = array_merge($enrolledparams, $groupparams);
         } else {
             // User doesn't belong to any group, so he can't see any user. Return an empty array.
             return array();
         }
     }
     $sql = "SELECT us.*\n                  FROM {user} us\n                  JOIN (\n                      SELECT DISTINCT u.id {$ctxselect}\n                        FROM {user} u {$ctxjoin} {$groupjoin}\n                       WHERE u.id IN ({$enrolledsql})\n                  ) q ON q.id = us.id\n                ORDER BY {$sortby} {$sortdirection}";
     $enrolledparams = array_merge($enrolledparams, $sortparams);
     $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
     $users = array();
     foreach ($enrolledusers as $user) {
         context_helper::preload_from_record($user);
         if ($userdetails = user_get_user_details($user, $course, $userfields)) {
             $users[] = $userdetails;
         }
     }
     $enrolledusers->close();
     return $users;
 }
Exemple #5
0
 /**
  * Sets up this object's group variables, mainly to restrict the selection of users to display.
  */
 protected function setup_groups()
 {
     /// find out current groups mode
     if ($this->groupmode = groups_get_course_groupmode($this->course)) {
         $this->currentgroup = groups_get_course_group($this->course, true);
         $this->group_selector = groups_print_course_menu($this->course, $this->pbarurl, true);
         if ($this->groupmode == SEPARATEGROUPS and !$this->currentgroup and !has_capability('moodle/site:accessallgroups', $this->context)) {
             $this->currentgroup = -2;
             // means can not access any groups at all
         }
         if ($this->currentgroup) {
             $this->groupsql = " JOIN {groups_members} gm ON gm.userid = u.id ";
             $this->groupwheresql = " AND gm.groupid = :gr_grpid ";
             $this->groupwheresql_params = array('gr_grpid' => $this->currentgroup);
         }
     }
 }
Exemple #6
0
        } else {
            echo $OUTPUT->header();
            $PAGE->navbar->add($struser);
            echo $OUTPUT->heading(get_string('notenrolledprofile'));
        }
        $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
        if (!empty($referer)) {
            echo $OUTPUT->continue_button($referer);
        }
        echo $OUTPUT->footer();
        exit;
    }

    // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
    // Except when we are a parent, in which case we would not be in any group.
    if (groups_get_course_groupmode($course) == SEPARATEGROUPS
            and $course->groupmodeforce
            and !has_capability('moodle/site:accessallgroups', $coursecontext)
            and !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)
            and !$isparent) {
        if (!isloggedin() or isguestuser()) {
            // Do not use require_login() here because we might have already used require_login($course).
            redirect(get_login_url());
        }
        $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
        $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
        if (!array_intersect($mygroups, $usergroups)) {
            print_error("groupnotamember", '', "../course/view.php?id=$course->id");
        }
    }
}
Exemple #7
0
            echo $OUTPUT->header();
            echo $OUTPUT->heading(get_string('notenrolled', '', $fullname));
        } else {
            echo $OUTPUT->header();
            $PAGE->navbar->add($struser);
            echo $OUTPUT->heading(get_string('notenrolledprofile'));
        }
        if (!empty($_SERVER['HTTP_REFERER'])) {
            echo $OUTPUT->continue_button($_SERVER['HTTP_REFERER']);
        }
        echo $OUTPUT->footer();
        exit;
    }

    // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group
    if (groups_get_course_groupmode($course) == SEPARATEGROUPS and $course->groupmodeforce
      and !has_capability('moodle/site:accessallgroups', $coursecontext) and !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
        if (!isloggedin() or isguestuser()) {
            // do not use require_login() here because we might have already used require_login($course)
            redirect(get_login_url());
        }
        $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
        $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
        if (!array_intersect($mygroups, $usergroups)) {
            print_error("groupnotamember", '', "../course/view.php?id=$course->id");
        }
    }
}


/// We've established they can see the user's name at least, so what about the rest?
Exemple #8
0
            $PAGE->navbar->add($fullname);
            echo $OUTPUT->header();
            echo $OUTPUT->heading(get_string('notenrolled', '', $fullname));
        } else {
            echo $OUTPUT->header();
            $PAGE->navbar->add($struser);
            echo $OUTPUT->heading(get_string('notenrolledprofile'));
        }
        if (!empty($_SERVER['HTTP_REFERER'])) {
            echo $OUTPUT->continue_button($_SERVER['HTTP_REFERER']);
        }
        echo $OUTPUT->footer();
        exit;
    }
    // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group
    if (groups_get_course_groupmode($course) == SEPARATEGROUPS and $course->groupmodeforce and !has_capability('moodle/site:accessallgroups', $coursecontext) and !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
        if (!isloggedin() or isguestuser()) {
            // do not use require_login() here because we might have already used require_login($course)
            redirect(get_login_url());
        }
        $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
        $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
        if (!array_intersect($mygroups, $usergroups)) {
            print_error("groupnotamember", '', "../course/view.php?id={$course->id}");
        }
    }
}
/// We've established they can see the user's name at least, so what about the rest?
if (!$currentuser) {
    $PAGE->navigation->extend_for_user($user);
    if ($node = $PAGE->settingsnav->get('userviewingsettings' . $user->id)) {
Exemple #9
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     $prefurl = new moodle_url('/user/preferences.php');
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
         $prefurl->param('userid', $userid);
     }
     // Add a user setting branch.
     if ($gstitle == 'usercurrentsettings') {
         $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
         // This should be set to false as we don't want to show this to the user. It's only for generating the correct
         // breadcrumb.
         $dashboard->display = false;
         if (get_home_page() == HOMEPAGE_MY) {
             $dashboard->mainnavonly = true;
         }
         $iscurrentuser = $user->id == $USER->id;
         $baseargs = array('id' => $user->id);
         if ($course->id != $SITE->id && !$iscurrentuser) {
             $baseargs['course'] = $course->id;
             $issitecourse = false;
         } else {
             // Load all categories and get the context for the system.
             $issitecourse = true;
         }
         // Add the user profile to the dashboard.
         $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
         if (!empty($CFG->navadduserpostslinks)) {
             // Add nodes for forum posts and discussions if the user can view either or both
             // There are no capability checks here as the content of the page is based
             // purely on the forums the current user has access too.
             $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
         }
         // Add blog nodes.
         if (!empty($CFG->enableblogs)) {
             if (!$this->cache->cached('userblogoptions' . $user->id)) {
                 require_once $CFG->dirroot . '/blog/lib.php';
                 // Get all options for the user.
                 $options = blog_get_options_for_user($user);
                 $this->cache->set('userblogoptions' . $user->id, $options);
             } else {
                 $options = $this->cache->{'userblogoptions' . $user->id};
             }
             if (count($options) > 0) {
                 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                 foreach ($options as $type => $option) {
                     if ($type == "rss") {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                     } else {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
                     }
                 }
             }
         }
         // Add the messages link.
         // It is context based so can appear in the user's profile and in course participants information.
         if (!empty($CFG->messaging)) {
             $messageargs = array('user1' => $USER->id);
             if ($USER->id != $user->id) {
                 $messageargs['user2'] = $user->id;
             }
             if ($course->id != $SITE->id) {
                 $messageargs['viewing'] = MESSAGE_VIEW_COURSE . $course->id;
             }
             $url = new moodle_url('/message/index.php', $messageargs);
             $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
         }
         // Add the "My private files" link.
         // This link doesn't have a unique display for course context so only display it under the user's profile.
         if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
             $url = new moodle_url('/user/files.php');
             $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
         }
         // Add a node to view the users notes if permitted.
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php', array('user' => $user->id));
             if ($coursecontext->instanceid != SITEID) {
                 $url->param('course', $coursecontext->instanceid);
             }
             $profilenode->add(get_string('notes', 'notes'), $url);
         }
         // Show the grades node.
         if ($issitecourse && $iscurrentuser || has_capability('moodle/user:viewdetails', $usercontext)) {
             require_once $CFG->dirroot . '/user/lib.php';
             // Set the grades node to link to the "Grades" page.
             if ($course->id == SITEID) {
                 $url = user_mygrades_url($user->id, $course->id);
             } else {
                 // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
                 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
             }
             $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
         }
         // Let plugins hook into user navigation.
         $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
         foreach ($pluginsfunction as $plugintype => $plugins) {
             if ($plugintype != 'report') {
                 foreach ($plugins as $pluginfunction) {
                     $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
                 }
             }
         }
         $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $dashboard->add_node($usersetting);
     } else {
         $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $usersetting->display = false;
     }
     $usersetting->id = 'usersettings';
     // Check if the user has been deleted.
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message.
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile.
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
     // Add the profile edit link.
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link.
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
         }
     }
     $pluginmanager = core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('mod');
     if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
         }
     }
     $editors = editors_get_enabled();
     if (count($editors) > 1) {
         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
             if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
                 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
                 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
             }
         }
     }
     // Add "Course preferences" link.
     if (isloggedin() && !isguestuser($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
         }
     }
     // View the roles settings.
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Repositories.
     if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
         require_once $CFG->dirroot . '/repository/lib.php';
         $editabletypes = repository::get_editable_types($usercontext);
         $haseditabletypes = !empty($editabletypes);
         unset($editabletypes);
         $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
     } else {
         $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
     }
     if ($haseditabletypes) {
         $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
         $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
     }
     // Portfolio.
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys.
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging.
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs.
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         if (has_capability('moodle/blog:view', $systemcontext)) {
             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         }
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
         // Remove the blog node if empty.
         $blog->trim_if_empty();
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
             $url = new moodle_url('/badges/mybadges.php');
             $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
         }
         $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Let plugins hook into user settings navigation.
     $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
     foreach ($pluginsfunction as $plugintype => $plugins) {
         foreach ($plugins as $pluginfunction) {
             $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
         }
     }
     return $usersetting;
 }
/**
 * Print groupmode form element on module setup forms in mod/.../mod.html
 */
function print_groupmode_setting($form, $course = NULL)
{
    if (empty($course)) {
        if (!($course = get_record('course', 'id', $form->course))) {
            error("This course doesn't exist");
        }
    }
    if ($form->coursemodule) {
        if (!($cm = get_record('course_modules', 'id', $form->coursemodule))) {
            error("This course module doesn't exist");
        }
        $groupmode = groups_get_activity_groupmode($cm);
    } else {
        $cm = null;
        $groupmode = groups_get_course_groupmode($course);
    }
    if ($course->groupmode or !$course->groupmodeforce) {
        echo '<tr valign="top">';
        echo '<td align="right"><b>' . get_string('groupmode') . ':</b></td>';
        echo '<td align="left">';
        $choices = array();
        $choices[NOGROUPS] = get_string('groupsnone');
        $choices[SEPARATEGROUPS] = get_string('groupsseparate');
        $choices[VISIBLEGROUPS] = get_string('groupsvisible');
        choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
        helpbutton('groupmode', get_string('groupmode'));
        echo '</td></tr>';
    }
}
Exemple #11
0
/**
 * This function delegates file serving to individual plugins
 *
 * @param string $relativepath
 * @param bool $forcedownload
 * @param null|string $preview the preview mode, defaults to serving the original file
 * @todo MDL-31088 file serving improments
 */
function file_pluginfile($relativepath, $forcedownload, $preview = null)
{
    global $DB, $CFG, $USER;
    // relative path must start with '/'
    if (!$relativepath) {
        print_error('invalidargorconf');
    } else {
        if ($relativepath[0] != '/') {
            print_error('pathdoesnotstartslash');
        }
    }
    // extract relative path components
    $args = explode('/', ltrim($relativepath, '/'));
    if (count($args) < 3) {
        // always at least context, component and filearea
        print_error('invalidarguments');
    }
    $contextid = (int) array_shift($args);
    $component = clean_param(array_shift($args), PARAM_COMPONENT);
    $filearea = clean_param(array_shift($args), PARAM_AREA);
    list($context, $course, $cm) = get_context_info_array($contextid);
    $fs = get_file_storage();
    // ========================================================================================================================
    if ($component === 'blog') {
        // Blog file serving
        if ($context->contextlevel != CONTEXT_SYSTEM) {
            send_file_not_found();
        }
        if ($filearea !== 'attachment' and $filearea !== 'post') {
            send_file_not_found();
        }
        if (empty($CFG->enableblogs)) {
            print_error('siteblogdisable', 'blog');
        }
        $entryid = (int) array_shift($args);
        if (!($entry = $DB->get_record('post', array('module' => 'blog', 'id' => $entryid)))) {
            send_file_not_found();
        }
        if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
            require_login();
            if (isguestuser()) {
                print_error('noguest');
            }
            if ($CFG->bloglevel == BLOG_USER_LEVEL) {
                if ($USER->id != $entry->userid) {
                    send_file_not_found();
                }
            }
        }
        if ($entry->publishstate === 'public') {
            if ($CFG->forcelogin) {
                require_login();
            }
        } else {
            if ($entry->publishstate === 'site') {
                require_login();
                //ok
            } else {
                if ($entry->publishstate === 'draft') {
                    require_login();
                    if ($USER->id != $entry->userid) {
                        send_file_not_found();
                    }
                }
            }
        }
        $filename = array_pop($args);
        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
        if (!($file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename)) or $file->is_directory()) {
            send_file_not_found();
        }
        send_stored_file($file, 10 * 60, 0, true, array('preview' => $preview));
        // download MUST be forced - security!
        // ========================================================================================================================
    } else {
        if ($component === 'grade') {
            if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
                // Global gradebook files
                if ($CFG->forcelogin) {
                    require_login();
                }
                $fullpath = "/{$context->id}/{$component}/{$filearea}/" . implode('/', $args);
                if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                    send_file_not_found();
                }
                \core\session\manager::write_close();
                // Unlock session during file serving.
                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
            } else {
                if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
                    //TODO: nobody implemented this yet in grade edit form!!
                    send_file_not_found();
                    if ($CFG->forcelogin || $course->id != SITEID) {
                        require_login($course);
                    }
                    $fullpath = "/{$context->id}/{$component}/{$filearea}/" . implode('/', $args);
                    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                        send_file_not_found();
                    }
                    \core\session\manager::write_close();
                    // Unlock session during file serving.
                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                } else {
                    send_file_not_found();
                }
            }
            // ========================================================================================================================
        } else {
            if ($component === 'tag') {
                if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
                    // All tag descriptions are going to be public but we still need to respect forcelogin
                    if ($CFG->forcelogin) {
                        require_login();
                    }
                    $fullpath = "/{$context->id}/tag/description/" . implode('/', $args);
                    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                        send_file_not_found();
                    }
                    \core\session\manager::write_close();
                    // Unlock session during file serving.
                    send_stored_file($file, 60 * 60, 0, true, array('preview' => $preview));
                } else {
                    send_file_not_found();
                }
                // ========================================================================================================================
            } else {
                if ($component === 'badges') {
                    require_once $CFG->libdir . '/badgeslib.php';
                    $badgeid = (int) array_shift($args);
                    $badge = new badge($badgeid);
                    $filename = array_pop($args);
                    if ($filearea === 'badgeimage') {
                        if ($filename !== 'f1' && $filename !== 'f2') {
                            send_file_not_found();
                        }
                        if (!($file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename . '.png'))) {
                            send_file_not_found();
                        }
                        \core\session\manager::write_close();
                        send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                    } else {
                        if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
                            if (!($file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename . '.png'))) {
                                send_file_not_found();
                            }
                            \core\session\manager::write_close();
                            send_stored_file($file, 60 * 60, 0, true, array('preview' => $preview));
                        }
                    }
                    // ========================================================================================================================
                } else {
                    if ($component === 'calendar') {
                        if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
                            // All events here are public the one requirement is that we respect forcelogin
                            if ($CFG->forcelogin) {
                                require_login();
                            }
                            // Get the event if from the args array
                            $eventid = array_shift($args);
                            // Load the event from the database
                            if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'eventtype' => 'site')))) {
                                send_file_not_found();
                            }
                            // Get the file and serve if successful
                            $filename = array_pop($args);
                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                            if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                send_file_not_found();
                            }
                            \core\session\manager::write_close();
                            // Unlock session during file serving.
                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                        } else {
                            if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
                                // Must be logged in, if they are not then they obviously can't be this user
                                require_login();
                                // Don't want guests here, potentially saves a DB call
                                if (isguestuser()) {
                                    send_file_not_found();
                                }
                                // Get the event if from the args array
                                $eventid = array_shift($args);
                                // Load the event from the database - user id must match
                                if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'userid' => $USER->id, 'eventtype' => 'user')))) {
                                    send_file_not_found();
                                }
                                // Get the file and serve if successful
                                $filename = array_pop($args);
                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                    send_file_not_found();
                                }
                                \core\session\manager::write_close();
                                // Unlock session during file serving.
                                send_stored_file($file, 0, 0, true, array('preview' => $preview));
                            } else {
                                if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
                                    // Respect forcelogin and require login unless this is the site.... it probably
                                    // should NEVER be the site
                                    if ($CFG->forcelogin || $course->id != SITEID) {
                                        require_login($course);
                                    }
                                    // Must be able to at least view the course. This does not apply to the front page.
                                    if ($course->id != SITEID && !is_enrolled($context) && !is_viewing($context)) {
                                        //TODO: hmm, do we really want to block guests here?
                                        send_file_not_found();
                                    }
                                    // Get the event id
                                    $eventid = array_shift($args);
                                    // Load the event from the database we need to check whether it is
                                    // a) valid course event
                                    // b) a group event
                                    // Group events use the course context (there is no group context)
                                    if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'courseid' => $course->id)))) {
                                        send_file_not_found();
                                    }
                                    // If its a group event require either membership of view all groups capability
                                    if ($event->eventtype === 'group') {
                                        if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
                                            send_file_not_found();
                                        }
                                    } else {
                                        if ($event->eventtype === 'course' || $event->eventtype === 'site') {
                                            // Ok. Please note that the event type 'site' still uses a course context.
                                        } else {
                                            // Some other type.
                                            send_file_not_found();
                                        }
                                    }
                                    // If we get this far we can serve the file
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                } else {
                                    send_file_not_found();
                                }
                            }
                        }
                        // ========================================================================================================================
                    } else {
                        if ($component === 'user') {
                            if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
                                if (count($args) == 1) {
                                    $themename = theme_config::DEFAULT_THEME;
                                    $filename = array_shift($args);
                                } else {
                                    $themename = array_shift($args);
                                    $filename = array_shift($args);
                                }
                                // fix file name automatically
                                if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
                                    $filename = 'f1';
                                }
                                if ((!empty($CFG->forcelogin) and !isloggedin()) || !empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser())) {
                                    // protect images if login required and not logged in;
                                    // also if login is required for profile images and is not logged in or guest
                                    // do not use require_login() because it is expensive and not suitable here anyway
                                    $theme = theme_config::load($themename);
                                    redirect($theme->pix_url('u/' . $filename, 'moodle'));
                                    // intentionally not cached
                                }
                                if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename . '.png'))) {
                                    if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename . '.jpg'))) {
                                        if ($filename === 'f3') {
                                            // f3 512x512px was introduced in 2.3, there might be only the smaller version.
                                            if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png'))) {
                                                $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
                                            }
                                        }
                                    }
                                }
                                if (!$file) {
                                    // bad reference - try to prevent future retries as hard as possible!
                                    if ($user = $DB->get_record('user', array('id' => $context->instanceid), 'id, picture')) {
                                        if ($user->picture > 0) {
                                            $DB->set_field('user', 'picture', 0, array('id' => $user->id));
                                        }
                                    }
                                    // no redirect here because it is not cached
                                    $theme = theme_config::load($themename);
                                    $imagefile = $theme->resolve_image_location('u/' . $filename, 'moodle', null);
                                    send_file($imagefile, basename($imagefile), 60 * 60 * 24 * 14);
                                }
                                $options = array('preview' => $preview);
                                if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
                                    // Profile images should be cache-able by both browsers and proxies according
                                    // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
                                    $options['cacheability'] = 'public';
                                }
                                send_stored_file($file, 60 * 60 * 24 * 365, 0, false, $options);
                                // enable long caching, there are many images on each page
                            } else {
                                if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
                                    require_login();
                                    if (isguestuser()) {
                                        send_file_not_found();
                                    }
                                    if ($USER->id !== $context->instanceid) {
                                        send_file_not_found();
                                    }
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                    // must force download - security!
                                } else {
                                    if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
                                        if ($CFG->forcelogin) {
                                            require_login();
                                        }
                                        $userid = $context->instanceid;
                                        if ($USER->id == $userid) {
                                            // always can access own
                                        } else {
                                            if (!empty($CFG->forceloginforprofiles)) {
                                                require_login();
                                                if (isguestuser()) {
                                                    send_file_not_found();
                                                }
                                                // we allow access to site profile of all course contacts (usually teachers)
                                                if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
                                                    send_file_not_found();
                                                }
                                                $canview = false;
                                                if (has_capability('moodle/user:viewdetails', $context)) {
                                                    $canview = true;
                                                } else {
                                                    $courses = enrol_get_my_courses();
                                                }
                                                while (!$canview && count($courses) > 0) {
                                                    $course = array_shift($courses);
                                                    if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
                                                        $canview = true;
                                                    }
                                                }
                                            }
                                        }
                                        $filename = array_pop($args);
                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                        if (!($file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                            send_file_not_found();
                                        }
                                        \core\session\manager::write_close();
                                        // Unlock session during file serving.
                                        send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                        // must force download - security!
                                    } else {
                                        if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
                                            $userid = (int) array_shift($args);
                                            $usercontext = context_user::instance($userid);
                                            if ($CFG->forcelogin) {
                                                require_login();
                                            }
                                            if (!empty($CFG->forceloginforprofiles)) {
                                                require_login();
                                                if (isguestuser()) {
                                                    print_error('noguest');
                                                }
                                                //TODO: review this logic of user profile access prevention
                                                if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
                                                    print_error('usernotavailable');
                                                }
                                                if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
                                                    print_error('cannotviewprofile');
                                                }
                                                if (!is_enrolled($context, $userid)) {
                                                    print_error('notenrolledprofile');
                                                }
                                                if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                                                    print_error('groupnotamember');
                                                }
                                            }
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (!($file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename)) or $file->is_directory()) {
                                                send_file_not_found();
                                            }
                                            \core\session\manager::write_close();
                                            // Unlock session during file serving.
                                            send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                            // must force download - security!
                                        } else {
                                            if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
                                                require_login();
                                                if (isguestuser()) {
                                                    send_file_not_found();
                                                }
                                                $userid = $context->instanceid;
                                                if ($USER->id != $userid) {
                                                    send_file_not_found();
                                                }
                                                $filename = array_pop($args);
                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                if (!($file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename)) or $file->is_directory()) {
                                                    send_file_not_found();
                                                }
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                                // must force download - security!
                                            } else {
                                                send_file_not_found();
                                            }
                                        }
                                    }
                                }
                            }
                            // ========================================================================================================================
                        } else {
                            if ($component === 'coursecat') {
                                if ($context->contextlevel != CONTEXT_COURSECAT) {
                                    send_file_not_found();
                                }
                                if ($filearea === 'description') {
                                    if ($CFG->forcelogin) {
                                        // no login necessary - unless login forced everywhere
                                        require_login();
                                    }
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                } else {
                                    send_file_not_found();
                                }
                                // ========================================================================================================================
                            } else {
                                if ($component === 'course') {
                                    if ($context->contextlevel != CONTEXT_COURSE) {
                                        send_file_not_found();
                                    }
                                    if ($filearea === 'summary' || $filearea === 'overviewfiles') {
                                        if ($CFG->forcelogin) {
                                            require_login();
                                        }
                                        $filename = array_pop($args);
                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                        if (!($file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                            send_file_not_found();
                                        }
                                        \core\session\manager::write_close();
                                        // Unlock session during file serving.
                                        send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                    } else {
                                        if ($filearea === 'section') {
                                            if ($CFG->forcelogin) {
                                                require_login($course);
                                            } else {
                                                if ($course->id != SITEID) {
                                                    require_login($course);
                                                }
                                            }
                                            $sectionid = (int) array_shift($args);
                                            if (!($section = $DB->get_record('course_sections', array('id' => $sectionid, 'course' => $course->id)))) {
                                                send_file_not_found();
                                            }
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (!($file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename)) or $file->is_directory()) {
                                                send_file_not_found();
                                            }
                                            \core\session\manager::write_close();
                                            // Unlock session during file serving.
                                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                        } else {
                                            send_file_not_found();
                                        }
                                    }
                                } else {
                                    if ($component === 'cohort') {
                                        $cohortid = (int) array_shift($args);
                                        $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
                                        $cohortcontext = context::instance_by_id($cohort->contextid);
                                        // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
                                        if ($context->id != $cohort->contextid && ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
                                            send_file_not_found();
                                        }
                                        // User is able to access cohort if they have view cap on cohort level or
                                        // the cohort is visible and they have view cap on course level.
                                        $canview = has_capability('moodle/cohort:view', $cohortcontext) || $cohort->visible && has_capability('moodle/cohort:view', $context);
                                        if ($filearea === 'description' && $canview) {
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename)) && !$file->is_directory()) {
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                            }
                                        }
                                        send_file_not_found();
                                    } else {
                                        if ($component === 'group') {
                                            if ($context->contextlevel != CONTEXT_COURSE) {
                                                send_file_not_found();
                                            }
                                            require_course_login($course, true, null, false);
                                            $groupid = (int) array_shift($args);
                                            $group = $DB->get_record('groups', array('id' => $groupid, 'courseid' => $course->id), '*', MUST_EXIST);
                                            if ($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
                                                // do not allow access to separate group info if not member or teacher
                                                send_file_not_found();
                                            }
                                            if ($filearea === 'description') {
                                                require_login($course);
                                                $filename = array_pop($args);
                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                if (!($file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename)) or $file->is_directory()) {
                                                    send_file_not_found();
                                                }
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                            } else {
                                                if ($filearea === 'icon') {
                                                    $filename = array_pop($args);
                                                    if ($filename !== 'f1' and $filename !== 'f2') {
                                                        send_file_not_found();
                                                    }
                                                    if (!($file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename . '.png'))) {
                                                        if (!($file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename . '.jpg'))) {
                                                            send_file_not_found();
                                                        }
                                                    }
                                                    \core\session\manager::write_close();
                                                    // Unlock session during file serving.
                                                    send_stored_file($file, 60 * 60, 0, false, array('preview' => $preview));
                                                } else {
                                                    send_file_not_found();
                                                }
                                            }
                                        } else {
                                            if ($component === 'grouping') {
                                                if ($context->contextlevel != CONTEXT_COURSE) {
                                                    send_file_not_found();
                                                }
                                                require_login($course);
                                                $groupingid = (int) array_shift($args);
                                                // note: everybody has access to grouping desc images for now
                                                if ($filearea === 'description') {
                                                    $filename = array_pop($args);
                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                    if (!($file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename)) or $file->is_directory()) {
                                                        send_file_not_found();
                                                    }
                                                    \core\session\manager::write_close();
                                                    // Unlock session during file serving.
                                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                } else {
                                                    send_file_not_found();
                                                }
                                                // ========================================================================================================================
                                            } else {
                                                if ($component === 'backup') {
                                                    if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
                                                        require_login($course);
                                                        require_capability('moodle/backup:downloadfile', $context);
                                                        $filename = array_pop($args);
                                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                        if (!($file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename)) or $file->is_directory()) {
                                                            send_file_not_found();
                                                        }
                                                        \core\session\manager::write_close();
                                                        // Unlock session during file serving.
                                                        send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
                                                    } else {
                                                        if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
                                                            require_login($course);
                                                            require_capability('moodle/backup:downloadfile', $context);
                                                            $sectionid = (int) array_shift($args);
                                                            $filename = array_pop($args);
                                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                            if (!($file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename)) or $file->is_directory()) {
                                                                send_file_not_found();
                                                            }
                                                            \core\session\manager::write_close();
                                                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                        } else {
                                                            if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
                                                                require_login($course, false, $cm);
                                                                require_capability('moodle/backup:downloadfile', $context);
                                                                $filename = array_pop($args);
                                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                if (!($file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                    send_file_not_found();
                                                                }
                                                                \core\session\manager::write_close();
                                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                            } else {
                                                                if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
                                                                    // Backup files that were generated by the automated backup systems.
                                                                    require_login($course);
                                                                    require_capability('moodle/site:config', $context);
                                                                    $filename = array_pop($args);
                                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                    if (!($file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                        send_file_not_found();
                                                                    }
                                                                    \core\session\manager::write_close();
                                                                    // Unlock session during file serving.
                                                                    send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
                                                                } else {
                                                                    send_file_not_found();
                                                                }
                                                            }
                                                        }
                                                    }
                                                    // ========================================================================================================================
                                                } else {
                                                    if ($component === 'question') {
                                                        require_once $CFG->libdir . '/questionlib.php';
                                                        question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
                                                        send_file_not_found();
                                                        // ========================================================================================================================
                                                    } else {
                                                        if ($component === 'grading') {
                                                            if ($filearea === 'description') {
                                                                // files embedded into the form definition description
                                                                if ($context->contextlevel == CONTEXT_SYSTEM) {
                                                                    require_login();
                                                                } else {
                                                                    if ($context->contextlevel >= CONTEXT_COURSE) {
                                                                        require_login($course, false, $cm);
                                                                    } else {
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                                $formid = (int) array_shift($args);
                                                                $sql = "SELECT ga.id\n                FROM {grading_areas} ga\n                JOIN {grading_definitions} gd ON (gd.areaid = ga.id)\n                WHERE gd.id = ? AND ga.contextid = ?";
                                                                $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
                                                                if (!$areaid) {
                                                                    send_file_not_found();
                                                                }
                                                                $fullpath = "/{$context->id}/{$component}/{$filearea}/{$formid}/" . implode('/', $args);
                                                                if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                                                                    send_file_not_found();
                                                                }
                                                                \core\session\manager::write_close();
                                                                // Unlock session during file serving.
                                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                            }
                                                            // ========================================================================================================================
                                                        } else {
                                                            if (strpos($component, 'mod_') === 0) {
                                                                $modname = substr($component, 4);
                                                                if (!file_exists("{$CFG->dirroot}/mod/{$modname}/lib.php")) {
                                                                    send_file_not_found();
                                                                }
                                                                require_once "{$CFG->dirroot}/mod/{$modname}/lib.php";
                                                                if ($context->contextlevel == CONTEXT_MODULE) {
                                                                    if ($cm->modname !== $modname) {
                                                                        // somebody tries to gain illegal access, cm type must match the component!
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                                if ($filearea === 'intro') {
                                                                    if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
                                                                        send_file_not_found();
                                                                    }
                                                                    require_course_login($course, true, $cm);
                                                                    // all users may access it
                                                                    $filename = array_pop($args);
                                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                    if (!($file = $fs->get_file($context->id, 'mod_' . $modname, 'intro', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                        send_file_not_found();
                                                                    }
                                                                    // finally send the file
                                                                    send_stored_file($file, null, 0, false, array('preview' => $preview));
                                                                }
                                                                $filefunction = $component . '_pluginfile';
                                                                $filefunctionold = $modname . '_pluginfile';
                                                                if (function_exists($filefunction)) {
                                                                    // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                    $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                } else {
                                                                    if (function_exists($filefunctionold)) {
                                                                        // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                        $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                    }
                                                                }
                                                                send_file_not_found();
                                                                // ========================================================================================================================
                                                            } else {
                                                                if (strpos($component, 'block_') === 0) {
                                                                    $blockname = substr($component, 6);
                                                                    // note: no more class methods in blocks please, that is ....
                                                                    if (!file_exists("{$CFG->dirroot}/blocks/{$blockname}/lib.php")) {
                                                                        send_file_not_found();
                                                                    }
                                                                    require_once "{$CFG->dirroot}/blocks/{$blockname}/lib.php";
                                                                    if ($context->contextlevel == CONTEXT_BLOCK) {
                                                                        $birecord = $DB->get_record('block_instances', array('id' => $context->instanceid), '*', MUST_EXIST);
                                                                        if ($birecord->blockname !== $blockname) {
                                                                            // somebody tries to gain illegal access, cm type must match the component!
                                                                            send_file_not_found();
                                                                        }
                                                                        if ($context->get_course_context(false)) {
                                                                            // If block is in course context, then check if user has capability to access course.
                                                                            require_course_login($course);
                                                                        } else {
                                                                            if ($CFG->forcelogin) {
                                                                                // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
                                                                                require_login();
                                                                            }
                                                                        }
                                                                        $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
                                                                        // User can't access file, if block is hidden or doesn't have block:view capability
                                                                        if ($bprecord && !$bprecord->visible || !has_capability('moodle/block:view', $context)) {
                                                                            send_file_not_found();
                                                                        }
                                                                    } else {
                                                                        $birecord = null;
                                                                    }
                                                                    $filefunction = $component . '_pluginfile';
                                                                    if (function_exists($filefunction)) {
                                                                        // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                        $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                    }
                                                                    send_file_not_found();
                                                                    // ========================================================================================================================
                                                                } else {
                                                                    if (strpos($component, '_') === false) {
                                                                        // all core subsystems have to be specified above, no more guessing here!
                                                                        send_file_not_found();
                                                                    } else {
                                                                        // try to serve general plugin file in arbitrary context
                                                                        $dir = core_component::get_component_directory($component);
                                                                        if (!file_exists("{$dir}/lib.php")) {
                                                                            send_file_not_found();
                                                                        }
                                                                        include_once "{$dir}/lib.php";
                                                                        $filefunction = $component . '_pluginfile';
                                                                        if (function_exists($filefunction)) {
                                                                            // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                            $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                        }
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
 /**
  * Return a list of current user contacts
  * This function checks if the current user can send messages to all the users or only to managers
  *
  * @param int $group Group to filter
  * @param string $fi Firstname initial to filter
  * @param string $li Lastname initial to filter
  * @param int $roleid Role id to filter
  * @return array Array of contacts
  */
 public function get_contacts($group, $fi, $li, $roleid)
 {
     global $DB, $OUTPUT, $SESSION, $USER;
     if (!$this->cansend) {
         return array();
     }
     // Cache (see refresh cache bellow)
     $hash = "-{$group}-{$fi}-{$li}-{$roleid}-";
     if (isset($SESSION->jmailcache->contacts[$this->course->id][$hash])) {
         // Problem when sending messages to new users.
         //return $SESSION->jmailcache->contacts[$this->course->id][$hash];
     }
     if (!$this->globalinbox) {
         if (!has_capability('moodle/course:viewparticipants', $this->context)) {
             return array();
         }
     }
     $groupmode = groups_get_course_groupmode($this->course);
     // Groups are being used
     $currentgroup = groups_get_course_group($this->course, true);
     if (!$currentgroup) {
         // To make some other functions work better later
         $currentgroup = NULL;
     }
     $this->isseparategroups = ($this->course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context));
     if ($this->isseparategroups and !$currentgroup) {
         return array();
     }
     $capability = null;
     // Users without cansendtoall capability cand send only to managers
     // Managers are those who can send to all messages
     if (!$this->cansendtoall and $this->cansendtomanagers) {
         $capability = "block/jmail:sendtoall";
     }
     list($esql, $params) = get_enrolled_sql($this->context, $capability, $currentgroup, true);
     $joins = array("FROM {user} u");
     $wheres = array();
     $select = "SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email";
     $joins[] = "JOIN ({$esql}) e ON e.id = u.id";
     // course enrolled users only
     $params['courseid'] = $this->course->id;
     // performance hacks - we preload user contexts together with accounts
     list($ccselect, $ccjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
     $select .= $ccselect;
     $joins[] = $ccjoin;
     if ($roleid) {
         $contextlist = get_related_contexts_string($this->context);
         $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid {$contextlist})";
         $params['roleid'] = $roleid;
     }
     if ($fi) {
         $wheres[] = $DB->sql_like('firstname', ':search1', false, false);
         $params['search1'] = "{$fi}%";
     }
     if ($li) {
         $wheres[] = $DB->sql_like('lastname', ':search2', false, false);
         $params['search2'] = "{$li}%";
     }
     if (!empty($this->config->filterfield)) {
         $wheres[] = "u." . $this->config->filterfield . " = :filterfield";
         $params['filterfield'] = $USER->{$this->config->filterfield};
     }
     $from = implode("\n", $joins);
     if ($wheres) {
         $where = "WHERE " . implode(" AND ", $wheres);
     } else {
         $where = "";
     }
     $sort = '';
     $start = '';
     $end = '';
     $userlist = $DB->get_records_sql("{$select} {$from} {$where} {$sort}", $params, $start, $end);
     if ($userlist) {
         foreach ($userlist as $key => $u) {
             $userlist[$key]->fullname = fullname($u);
             $userlist[$key]->profileimage = $OUTPUT->user_picture($u);
             unset($userlist[$key]->email);
         }
     }
     $SESSION->jmailcache->contacts[$this->course->id][$hash] = $userlist;
     return $userlist;
 }
Exemple #13
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
     }
     // Add a user setting branch
     $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
     $usersetting->id = 'usersettings';
     if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
         // Automatically start by making it active
         $usersetting->make_active();
     }
     // Check if the user has been deleted
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     // Add the profile edit link
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     // View the roles settings
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Portfolio
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Add reports node.
     $reporttab = $usersetting->add(get_string('activityreports'));
     $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
     foreach ($reports as $reportfunction) {
         $reportfunction($reporttab, $user, $course);
     }
     $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
     if ($anyreport || $course->showreports && $currentuser) {
         // Add grade hardcoded grade report if necessary.
         $gradeaccess = false;
         if (has_capability('moodle/grade:viewall', $coursecontext)) {
             // Can view all course grades.
             $gradeaccess = true;
         } else {
             if ($course->showgrades) {
                 if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
                     // Can view own grades.
                     $gradeaccess = true;
                 } else {
                     if (has_capability('moodle/grade:viewall', $usercontext)) {
                         // Can view grades of this user - parent most probably.
                         $gradeaccess = true;
                     } else {
                         if ($anyreport) {
                             // Can view grades of this user - parent most probably.
                             $gradeaccess = true;
                         }
                     }
                 }
             }
         }
         if ($gradeaccess) {
             $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $usercontext->instanceid)));
         }
     }
     // Check the number of nodes in the report node... if there are none remove the node
     $reporttab->trim_if_empty();
     // Login as ...
     if (!$user->deleted and !$currentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
         $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey()));
         $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
     }
     // Let admin tools hook into user settings navigation.
     $tools = get_plugin_list_with_function('tool', 'extend_navigation_user_settings', 'lib.php');
     foreach ($tools as $toolfunction) {
         $toolfunction($usersetting, $user, $usercontext, $course, $coursecontext);
     }
     return $usersetting;
 }
Exemple #14
0
 /**
  * Return list of groups.
  *
  * @return array list of groups.
  */
 public function get_group_list()
 {
     // No groups for system.
     if (empty($this->course)) {
         return array();
     }
     $context = context_course::instance($this->course->id);
     $groups = array();
     $groupmode = groups_get_course_groupmode($this->course);
     if ($groupmode == VISIBLEGROUPS || ($groupmode == SEPARATEGROUPS and has_capability('moodle/site:accessallgroups', $context))) {
         // Get all groups.
         if ($cgroups = groups_get_all_groups($this->course->id)) {
             foreach ($cgroups as $cgroup) {
                 $groups[$cgroup->id] = $cgroup->name;
             }
         }
     }
     return $groups;
 }
Exemple #15
0
 /**
  * Sets up this object's group variables, mainly to restrict the selection of users to display.
  */
 function setup_groups()
 {
     global $CFG;
     /// find out current groups mode
     if ($this->groupmode = groups_get_course_groupmode($this->course)) {
         $this->currentgroup = groups_get_course_group($this->course, true);
         $this->group_selector = groups_print_course_menu($this->course, $this->pbarurl, true);
         if ($this->groupmode == SEPARATEGROUPS and !$this->currentgroup and !has_capability('moodle/site:accessallgroups', $this->context)) {
             $this->currentgroup = -2;
             // means can not accesss any groups at all
         }
         if ($this->currentgroup) {
             $this->groupsql = " JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id ";
             $this->groupwheresql = " AND gm.groupid = {$this->currentgroup} ";
         }
     }
 }
Exemple #16
0
/**
 * This function returns an object of all users whithin current course who match
 * the search query.
 *  *Modified version of datalib.php's search_user() function
 *
 * @param object $course Current Course object
 * @param string $query Search query
 * @param boolean $dispadmins Flag to return course admins or not
 * @param boolean $displayunconfirmed Flag to specify to return unconfirmed users
 * @return object result set of all matching users
 * @todo Add option to remove active user from results
 */
function email_search_course_users($course, $query = '', $dispadmins = false, $dispunconfirmed = true)
{
    global $CFG, $USER;
    $LIKE = sql_ilike();
    $order = 'ORDER BY firstname, lastname, id';
    $select = 'u.deleted = \'0\'';
    if (!$dispunconfirmed) {
        $select .= ' AND u.confirmed = \'1\'';
    }
    if (!$course or $course->id == SITEID) {
        $results = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email\n                      FROM {$CFG->prefix}user u\n                      WHERE {$select}\n                          AND (u.firstname {$LIKE} '{$query}%' OR u.lastname {$LIKE} '{$query}%')\n                          AND u.username != 'guest'\n                          {$order}");
    } else {
        if ($course->id == SITEID) {
            $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
        } else {
            $context = get_context_instance(CONTEXT_COURSE, $course->id);
        }
        $contextlists = get_related_contexts_string($context);
        // Returns only group(s) members for users without the viewallgroups capability
        $groupmembers = '';
        // Separate groups
        $groupmode = groups_get_course_groupmode($course);
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
            // Returns all groups current user is assigned to in course
            if ($groups = groups_get_all_groups($course->id, $USER->id)) {
                $groupmembers = array();
                foreach ($groups as $group) {
                    $groupmembers += groups_get_members($group->id, 'u.id');
                }
                if (!empty($groupmembers)) {
                    $groupmembers = 'AND u.id IN (' . implode(',', array_keys($groupmembers)) . ')';
                } else {
                    // Nobody in their groups :(
                    return false;
                }
            } else {
                // They have no group :(
                return false;
            }
        }
        // Hides course admin roles (eg: admin && course creator) if requested (default)
        if (!$dispadmins) {
            $avoidroles = array();
            if ($roles = get_roles_used_in_context($context, true)) {
                $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
                $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $context);
                if (!$CFG->email_add_admins) {
                    $adminsroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW, $context);
                }
                foreach ($roles as $role) {
                    if (!isset($canviewroles[$role->id])) {
                        // Avoid this role (eg course creator)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }
                    if (isset($doanythingroles[$role->id])) {
                        // Avoid this role (ie admin)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }
                    if (!$CFG->email_add_admins) {
                        if (isset($adminsroles[$role->id])) {
                            // Avoid this role (ie admin)
                            $avoidroles[] = $role->id;
                            unset($roles[$role->id]);
                            continue;
                        }
                    }
                }
            }
            // exclude users with roles we are avoiding
            if ($avoidroles) {
                $adminroles = 'AND ra.roleid NOT IN (';
                $adminroles .= implode(',', $avoidroles);
                $adminroles .= ')';
            } else {
                $adminroles = '';
            }
        } else {
            $adminroles = '';
        }
        $results = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email\n                      FROM {$CFG->prefix}user u,\n                           {$CFG->prefix}role_assignments ra\n                      WHERE {$select} AND ra.contextid {$contextlists} AND ra.userid = u.id\n                          AND (u.firstname {$LIKE} '{$query}%' OR u.lastname {$LIKE} '{$query}%')\n                          AND (u.username != 'guest')\n                          {$adminroles} {$groupmembers} {$order}");
    }
    return $results;
}
Exemple #17
0
/**
 * Checks to see if a user can view the blogs of another user.
 * Only blog level is checked here, the capabilities are enforced
 * in blog/index.php
 */
function blog_user_can_view_user_post($targetuserid, $blogEntry = null)
{
    global $CFG, $USER;
    if (empty($CFG->bloglevel)) {
        return false;
        // blog system disabled
    }
    // a hack to publish some blogs openly.  Uses $CFG->openblogs = array(44, 322); in config.php
    if (isset($CFG->openblogs) && in_array($targetuserid, $CFG->openblogs)) {
        return true;
    }
    if (!empty($USER->id) and $USER->id == $targetuserid) {
        return true;
        // can view own posts in any case
    }
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    if (has_capability('moodle/blog:manageentries', $sitecontext)) {
        return true;
        // can manage all posts
    }
    // coming for 1 post, make sure it's not a draft
    if ($blogEntry and $blogEntry->publishstate == 'draft') {
        return false;
        // can not view draft of others
    }
    // coming for 1 post, make sure user is logged in, if not a public blog
    if ($blogEntry && $blogEntry->publishstate != 'public' && !isloggedin()) {
        return false;
    }
    switch ($CFG->bloglevel) {
        case BLOG_GLOBAL_LEVEL:
            return true;
            break;
        case BLOG_SITE_LEVEL:
            if (!empty($USER->id)) {
                // not logged in viewers forbidden
                return true;
            }
            return false;
            break;
        case BLOG_COURSE_LEVEL:
            $mycourses = array_keys(get_my_courses($USER->id));
            $usercourses = array_keys(get_my_courses($targetuserid));
            $shared = array_intersect($mycourses, $usercourses);
            if (!empty($shared)) {
                return true;
            }
            return false;
            break;
        case BLOG_GROUP_LEVEL:
            $mycourses = array_keys(get_my_courses($USER->id));
            $usercourses = array_keys(get_my_courses($targetuserid));
            $shared = array_intersect($mycourses, $usercourses);
            foreach ($shared as $courseid) {
                $course = get_record('course', 'id', $courseid);
                $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
                if (has_capability('moodle/site:accessallgroups', $coursecontext) or groups_get_course_groupmode($course) != SEPARATEGROUPS) {
                    return true;
                } else {
                    if ($usergroups = groups_get_all_groups($courseid, $targetuserid)) {
                        foreach ($usergroups as $usergroup) {
                            if (groups_is_member($usergroup->id)) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
            break;
        case BLOG_USER_LEVEL:
        default:
            $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
            return has_capability('moodle/user:readuserblogs', $personalcontext);
            break;
    }
}
 protected function definition()
 {
     global $OUTPUT, $PAGE, $COURSE, $CFG, $USER;
     $mform =& $this->_form;
     $courseid = $this->_customdata['courseid'];
     $postid = !empty($this->_customdata['options']->postid) ? $this->_customdata['options']->postid : 0;
     // Update of save a post.
     $action = $postid > 0 ? 'updatepost' : 'savepost';
     $context = context_course::instance($courseid);
     // ...get formparameters from cache.
     $cache = cache::make('format_socialwall', 'postformparams');
     $formparams = $cache->get($courseid . '_' . $postid);
     $loadposteditor = optional_param('loadposteditor', -1, PARAM_INT);
     if ($loadposteditor != -1) {
         $formparams['loadposteditor'] = $loadposteditor;
         // ...remember this setting, if page is reloaded.
         $cache->set($courseid . '_' . $postid, $formparams);
     }
     // ...get errors from cache and set them to elements.
     $errorcache = cache::make('format_socialwall', 'postformerrors');
     if ($errors = $errorcache->get($courseid)) {
         foreach ($errors as $element => $error) {
             $mform->setElementError($element, $error['message']);
         }
     }
     $errorcache->delete($courseid);
     // ... value of this element is set by javascript (postform.js) before submit.
     $mform->addElement('hidden', 'cmsequence', '', array('id' => 'cmsequence'));
     $mform->setType('cmsequence', PARAM_TEXT);
     $mform->setDefault('cmsequence', '');
     // ... posttext.
     $buttongroup = array();
     $buttongroup[] = $mform->createElement('submit', 'submitbutton', get_string($action, 'format_socialwall'));
     if ($action == 'updatepost') {
         $buttongroup[] = $mform->createElement('cancel');
     }
     $mform->addGroup($buttongroup);
     // ... htmleditor/texarea to post text.
     $canposthtml = has_capability('format/socialwall:posthtml', $context);
     $showeditor = (!empty($formparams['loadposteditor']) and $canposthtml);
     $params = array('class' => 'sw-texarea', 'id' => 'posttext');
     if ($showeditor) {
         $mform->addElement('editor', 'posttext', get_string('poststatusordnote', 'format_socialwall'), $params);
         $mform->setType('posttext', PARAM_RAW);
         if (isset($formparams['posttext'])) {
             $element = $mform->getElement('posttext');
             $element->setValue(array('text' => $formparams['posttext']));
         }
     } else {
         $mform->addElement('textarea', 'posttext', get_string('poststatusordnote', 'format_socialwall'), $params);
         $mform->setType('posttext', PARAM_TEXT);
         if (isset($formparams['posttext'])) {
             $mform->setDefault('posttext', $formparams['posttext']);
         }
     }
     $postoptions = array();
     // ... Select group.
     $groupmode = groups_get_course_groupmode($COURSE);
     if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', $context)) {
         $allgroups = groups_get_all_groups($courseid, $USER->id);
     } else {
         $allgroups = groups_get_all_groups($courseid);
     }
     $groupsmenu = array();
     $groupsmenu[0] = get_string('allparticipants');
     foreach ($allgroups as $gid => $unused) {
         $groupsmenu[$gid] = format_string($allgroups[$gid]->name);
     }
     if (count($groupsmenu) > 0) {
         $postoptions[] = $mform->createElement('select', 'togroupid', '', $groupsmenu);
         if (isset($formparams['togroupid'])) {
             $mform->setDefault('togroupid', $formparams['togroupid']);
         }
     }
     // ... options group.
     $poststatusmenu = array(0 => get_string('poststatus', 'format_socialwall'));
     if (has_capability('format/socialwall:makesticky', $context)) {
         $poststatusmenu[1] = get_string('makesticky', 'format_socialwall');
     }
     if (has_capability('format/socialwall:postprivate', $context)) {
         $poststatusmenu[2] = get_string('privatepost', 'format_socialwall');
     }
     if ($PAGE->user_allowed_editing()) {
         $poststatusmenu[4] = get_string('makealert', 'format_socialwall');
     }
     if (count($poststatusmenu) > 1) {
         $postoptions[] = $mform->createElement('select', 'poststatus', '', $poststatusmenu);
         if (isset($formparams['poststatus'])) {
             $mform->setDefault('poststatus', $formparams['poststatus']);
         }
     }
     // ...switch htmleditor on/off.
     if ($canposthtml) {
         $key = !empty($formparams['loadposteditor']) ? 'turneditoroff' : 'turneditoron';
         $postoptions[] = $mform->createElement('submit', $key, get_string($key, 'format_socialwall'));
     }
     if (count($postoptions) > 0) {
         $mform->addGroup($postoptions);
     }
     // ... display the activites prepared for the next post only by a teacher.
     if ($PAGE->user_allowed_editing()) {
         if (!isset($USER->editing) or !$USER->editing) {
             $addstr = get_string('addactivityresource', 'format_socialwall');
             $mform->addElement('submit', 'turneditingon', $addstr, array('id' => 'sw-addactivitylink'));
         }
     } else {
         $o = html_writer::tag('div', '', array('class' => 'clearfix'));
         $mform->addElement('html', $o);
         // ...upload options for all users, which cannot edit page.
         $attachgroup = array();
         $course = course_get_format($COURSE)->get_course();
         $canpostfile = has_capability('format/socialwall:postfile', $context) && !empty($course->enablestudentupload);
         if ($canpostfile) {
             $uploadfileicon = html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('icon', 'resource')));
             $linktext = $uploadfileicon . get_string('uploadafile', 'format_socialwall');
             $url = new moodle_url('/course/view.php', array('id' => $courseid, 'loadfilemanager' => 1));
             $link = html_writer::link($url, $linktext, array('id' => 'uploadfile'));
             $attachgroup[] = $mform->createElement('static', 'uploadfile', '', $link);
         }
         $canposturl = has_capability('format/socialwall:posturl', $context) && !empty($course->enablestudentupload);
         if ($canposturl) {
             $addlinkicon = html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('icon', 'url')));
             $at = html_writer::link('#', $addlinkicon . get_string('addalink', 'format_socialwall'), array('id' => 'addalink'));
             $attachgroup[] = $mform->createElement('static', 'addalink', '', $at);
         }
         if (!empty($attachgroup)) {
             $mform->addGroup($attachgroup);
         }
         $loadfilemanager = optional_param('loadfilemanager', 0, PARAM_INT);
         if ($canpostfile and $loadfilemanager == 1) {
             $mform->addElement('html', html_writer::start_div('', array('id' => 'fileswrapper')));
             // ... filemanager.
             $filemanageroptions = array();
             $filemanageroptions['accepted_types'] = '*';
             $filemanageroptions['maxbytes'] = 0;
             $filemanageroptions['maxfiles'] = 1;
             $filemanageroptions['mainfile'] = true;
             $mform->addElement('filemanager', 'files', get_string('selectfiles'), array(), $filemanageroptions);
             $mform->addElement('html', html_writer::end_div());
             $mform->addElement('hidden', 'loadfilemanager', '1', array('id' => 'loadfilemanager'));
             $mform->setType('loadfilemanager', PARAM_INT);
         }
         // ...external url.
         $style = isset($errors['externalurl']) ? 'display:auto' : 'display:none';
         $mform->addElement('html', html_writer::start_div('', array('id' => 'externalurlwrapper', 'style' => $style)));
         $mform->addElement('url', 'externalurl', get_string('externalurl', 'url'), array('size' => '60'), array('usefilepicker' => true));
         $mform->setType('externalurl', PARAM_URL);
         if (isset($errors['externalurl'])) {
             $mform->setDefault('externalurl', $errors['externalurl']['value']);
         }
         // ... get urlresource filter a try.
         $filters = filter_get_active_in_context($context);
         if (isset($filters['urlresource'])) {
             require_once $CFG->dirroot . '/filter/urlresource/lib.php';
             filter_url_resource_helper::add_postformfields($mform, $courseid);
         }
         $mform->addElement('html', html_writer::end_div());
     }
     // Id of post to remember the update option for further pageloads.
     $mform->addElement('hidden', 'id', 0, array('id' => 'id'));
     $mform->setType('id', PARAM_INT);
     $mform->setDefault('id', $postid);
     // Id of course we are in.
     $mform->addElement('hidden', 'courseid');
     $mform->setType('courseid', PARAM_INT);
     $mform->setDefault('courseid', $courseid);
     $mform->addElement('hidden', 'action', $action);
     $mform->setType('action', PARAM_TEXT);
     $mform->disable_form_change_checker();
 }
 function definition()
 {
     global $CFG, $COURSE, $USER;
     $mform =& $this->_form;
     $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
     $modinfo = get_fast_modinfo($COURSE);
     $mform->addElement('header', 'filters', get_string('managefilters'));
     //TODO: add better string
     if ($COURSE->id == SITEID) {
         $viewparticipants = has_capability('moodle/site:viewparticipants', get_context_instance(CONTEXT_SYSTEM));
     } else {
         $viewparticipants = has_capability('moodle/course:viewparticipants', $context);
     }
     $viewfullnames = has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $COURSE->id));
     if ($viewparticipants) {
         $options = array();
         $options[0] = get_string('allparticipants');
         if ($guest = get_guest()) {
             $options[$guest->id] = fullname($guest);
         }
         if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS) {
             $groups = groups_get_user_groups($COURSE->id);
             $groups = $groups[0];
         } else {
             $groups = '';
         }
         if ($courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.id, u.firstname, u.lastname', 'lastname ASC, firstname DESC', '', '', $groups)) {
             foreach ($courseusers as $courseuser) {
                 $options[$courseuser->id] = fullname($courseuser, $viewfullnames);
             }
         }
         $mform->addElement('select', 'user', get_string('participants'), $options);
         $mform->setAdvanced('user');
     }
     switch ($COURSE->format) {
         case 'weeks':
             $sectiontitle = get_string('week');
             break;
         case 'topics':
             $sectiontitle = get_string('topic');
             break;
         default:
             $sectiontitle = get_string('section');
             break;
     }
     $options = array('' => get_string('allactivities'));
     $modsused = array();
     foreach ($modinfo->cms as $cm) {
         if (!$cm->uservisible) {
             continue;
         }
         $modsused[$cm->modname] = true;
     }
     foreach ($modsused as $modname => $unused) {
         $libfile = "{$CFG->dirroot}/mod/{$modname}/lib.php";
         if (!file_exists($libfile)) {
             unset($modsused[$modname]);
             continue;
         }
         include_once $libfile;
         $libfunction = $modname . "_get_recent_mod_activity";
         if (!function_exists($libfunction)) {
             unset($modsused[$modname]);
             continue;
         }
         $options["mod/{$modname}"] = get_string('allmods', '', get_string('modulenameplural', $modname));
     }
     foreach ($modinfo->sections as $section => $cmids) {
         $options["section/{$section}"] = "-- {$sectiontitle} {$section} --";
         foreach ($cmids as $cmid) {
             $cm = $modinfo->cms[$cmid];
             if (empty($modsused[$cm->modname]) or !$cm->uservisible) {
                 continue;
             }
             $options[$cm->id] = format_string($cm->name);
         }
     }
     $mform->addElement('select', 'modid', get_string('activities'), $options);
     $mform->setAdvanced('modid');
     if (has_capability('moodle/site:accessallgroups', $context)) {
         if ($groups = groups_get_all_groups($COURSE->id)) {
             $options = array('0' => get_string('allgroups'));
             foreach ($groups as $group) {
                 $options[$group->id] = format_string($group->name);
             }
             $mform->addElement('select', 'group', get_string('groups'), $options);
             $mform->setAdvanced('group');
         }
     } else {
         $mform->addElement('hidden', 'group');
         $mform->setType('group', PARAM_INT);
         $mform->setConstants(array('group' => 0));
     }
     $options = array('default' => get_string('bycourseorder'), 'dateasc' => get_string('datemostrecentlast'), 'datedesc' => get_string('datemostrecentfirst'));
     $mform->addElement('select', 'sortby', get_string('sortby'), $options);
     $mform->setAdvanced('sortby');
     $mform->addElement('date_time_selector', 'date', get_string('since'), array('optional' => true));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setType('courseid', PARAM_INT);
     $this->add_action_buttons(false, get_string('showrecent'));
 }
 /**
  * Get all Posts (with authors) from the database by courseid
  * 
  * @param int $course, with theme settings loaded.
  * @return \stdClass, postsdata (infodata for all posts).
  */
 protected function get_all_posts($course, $options = null, $limitfrom = 0, $limitcount = 0, $orderby = array())
 {
     global $DB, $COURSE, $USER;
     $courseid = $course->id;
     $context = \context_course::instance($courseid);
     // ... prepare posts infodata.
     $postsdata = new \stdClass();
     $postsdata->posts = array();
     $postsdata->poststotal = 0;
     $postsdata->postsloaded = 0;
     $postsdata->filteroptions = $options;
     $postsdata->authors = array();
     if ($limitcount == 0) {
         $limitcount = !empty($course->tlnumposts) ? $course->tlnumposts : 0;
     }
     $cond = array("WHERE sp.courseid = ?");
     $params = array($courseid);
     $join = "";
     // ... no private posts?
     if (!has_capability('format/socialwall:viewprivate', $context)) {
         $cond[] = " sp.private = '0'";
     }
     // ... only users groups?
     if (!empty($options->filtergroups)) {
         $cond[] = " sp.togroupid = ?";
         $params[] = $options->filtergroups;
     } else {
         // ... if seperate groups are set and user is not allowed to see other groups set filter.
         $groupmode = groups_get_course_groupmode($COURSE);
         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', $context)) {
             $keys = array(0);
             // To all participants.
             if ($usersgroups = groups_get_all_groups($courseid, $USER->id)) {
                 $keys = array_merge($keys, array_keys($usersgroups));
             }
             list($ingroups, $inparams) = $DB->get_in_or_equal($keys);
             $cond[] = " sp.togroupid {$ingroups}";
             $params = array_merge($params, $inparams);
         }
     }
     if (!empty($options->filtermodules)) {
         $join = "JOIN {format_socialwall_attaches} at ON at.postid = sp.id ";
         $join .= "JOIN {course_modules} cm ON cm.id = at.coursemoduleid ";
         $join .= "JOIN {modules} m ON m.id = cm.module ";
         $cond[] = " m.name = ?";
         $params[] = $options->filtermodules;
     }
     if (!empty($options->filteralerts)) {
         $cond[] = " sp.alert = '1'";
     }
     if (!empty($options->postid)) {
         $cond[] = " sp.id = ? ";
         $params[] = $options->postid;
     }
     // ...show only one post on page, when option showalert is set.
     if (!empty($options->showalert)) {
         $cond[] = " sp.id = ?";
         $params[] = $options->showalert;
     }
     if (!empty($options->orderby)) {
         $orderby[] = 'sp.' . $options->orderby;
     }
     $ordering = '';
     if (!empty($orderby)) {
         $ordering = 'ORDER BY ' . implode(', ', $orderby);
     }
     $where = implode(' AND ', $cond);
     // ... get all posts.
     $sqlfrom = "FROM {format_socialwall_posts} sp {$join} {$where} ";
     $sql = "SELECT DISTINCT sp.* " . $sqlfrom . " {$ordering} ";
     $countsql = "SELECT count(DISTINCT sp.id) as total " . $sqlfrom;
     if (!($postsdata->poststotal = $DB->count_records_sql($countsql, $params))) {
         return $postsdata;
     }
     if (!($postsdata->posts = $DB->get_records_sql($sql, $params, $limitfrom, $limitcount))) {
         return $postsdata;
     }
     $postsdata->postsloaded = $limitfrom + count($postsdata->posts);
     return $postsdata;
 }
Exemple #21
0
$url = new moodle_url('/grade/import/csv/index.php', array('id' => $id));
if ($separator !== '') {
    $url->param('separator', $separator);
}
if ($verbosescales !== 1) {
    $url->param('verbosescales', $verbosescales);
}
$PAGE->set_url($url);
if (!($course = $DB->get_record('course', array('id' => $id)))) {
    print_error('nocourseid');
}
require_login($course);
$context = context_course::instance($id);
require_capability('moodle/grade:import', $context);
require_capability('gradeimport/csv:view', $context);
$separatemode = (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));
$currentgroup = groups_get_course_group($course);
print_grade_page_head($course->id, 'import', 'csv', get_string('importcsv', 'grades'));
// Set up the grade import mapping form.
$gradeitems = array();
if ($id) {
    if ($grade_items = grade_item::fetch_all(array('courseid' => $id))) {
        foreach ($grade_items as $grade_item) {
            // Skip course type and category type.
            if ($grade_item->itemtype == 'course' || $grade_item->itemtype == 'category') {
                continue;
            }
            $displaystring = null;
            if (!empty($grade_item->itemmodule)) {
                $displaystring = get_string('modulename', $grade_item->itemmodule) . get_string('labelsep', 'langconfig') . $grade_item->get_name();
            } else {
Exemple #22
0
 function definition()
 {
     global $CFG, $COURSE, $USER;
     $mform =& $this->_form;
     $context = context_course::instance($COURSE->id);
     $modinfo = get_fast_modinfo($COURSE);
     $sections = get_all_sections($COURSE->id);
     $mform->addElement('header', 'filters', get_string('managefilters'));
     //TODO: add better string
     $groupoptions = array();
     if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
         // limited group access
         $groups = groups_get_user_groups($COURSE->id);
         $allgroups = groups_get_all_groups($COURSE->id);
         if (!empty($groups[$COURSE->defaultgroupingid])) {
             foreach ($groups[$COURSE->defaultgroupingid] as $groupid) {
                 $groupoptions[$groupid] = format_string($allgroups[$groupid]->name, true, array('context' => $context));
             }
         }
     } else {
         $groupoptions = array('0' => get_string('allgroups'));
         if (has_capability('moodle/site:accessallgroups', $context)) {
             // user can see all groups
             $allgroups = groups_get_all_groups($COURSE->id);
         } else {
             // user can see course level groups
             $allgroups = groups_get_all_groups($COURSE->id, 0, $COURSE->defaultgroupingid);
         }
         foreach ($allgroups as $group) {
             $groupoptions[$group->id] = format_string($group->name, true, array('context' => $context));
         }
     }
     if ($COURSE->id == SITEID) {
         $viewparticipants = has_capability('moodle/site:viewparticipants', context_system::instance());
     } else {
         $viewparticipants = has_capability('moodle/course:viewparticipants', $context);
     }
     if ($viewparticipants) {
         $viewfullnames = has_capability('moodle/site:viewfullnames', context_course::instance($COURSE->id));
         $options = array();
         $options[0] = get_string('allparticipants');
         $options[$CFG->siteguest] = get_string('guestuser');
         if (isset($groupoptions[0])) {
             // can see all enrolled users
             if ($enrolled = get_enrolled_users($context, null, 0, user_picture::fields('u'))) {
                 foreach ($enrolled as $euser) {
                     $options[$euser->id] = fullname($euser, $viewfullnames);
                 }
             }
         } else {
             // can see users from some groups only
             foreach ($groupoptions as $groupid => $unused) {
                 if ($enrolled = get_enrolled_users($context, null, $groupid, user_picture::fields('u'))) {
                     foreach ($enrolled as $euser) {
                         if (!array_key_exists($euser->id, $options)) {
                             $options[$euser->id] = fullname($euser, $viewfullnames);
                         }
                     }
                 }
             }
         }
         $mform->addElement('select', 'user', get_string('participants'), $options);
         $mform->setAdvanced('user');
     }
     $sectiontitle = get_string('sectionname', 'format_' . $COURSE->format);
     $options = array('' => get_string('allactivities'));
     $modsused = array();
     foreach ($modinfo->cms as $cm) {
         if (!$cm->uservisible) {
             continue;
         }
         $modsused[$cm->modname] = true;
     }
     foreach ($modsused as $modname => $unused) {
         $libfile = "{$CFG->dirroot}/mod/{$modname}/lib.php";
         if (!file_exists($libfile)) {
             unset($modsused[$modname]);
             continue;
         }
         include_once $libfile;
         $libfunction = $modname . "_get_recent_mod_activity";
         if (!function_exists($libfunction)) {
             unset($modsused[$modname]);
             continue;
         }
         $options["mod/{$modname}"] = get_string('allmods', '', get_string('modulenameplural', $modname));
     }
     foreach ($modinfo->sections as $section => $cmids) {
         $options["section/{$section}"] = "-- " . get_section_name($COURSE, $sections[$section]) . " --";
         foreach ($cmids as $cmid) {
             $cm = $modinfo->cms[$cmid];
             if (empty($modsused[$cm->modname]) or !$cm->uservisible) {
                 continue;
             }
             $options[$cm->id] = format_string($cm->name);
         }
     }
     $mform->addElement('select', 'modid', get_string('activities'), $options);
     $mform->setAdvanced('modid');
     if ($groupoptions) {
         $mform->addElement('select', 'group', get_string('groups'), $groupoptions);
         $mform->setAdvanced('group');
     } else {
         // no access to groups in separate mode
         $mform->addElement('hidden', 'group');
         $mform->setType('group', PARAM_INT);
         $mform->setConstants(array('group' => -1));
     }
     $options = array('default' => get_string('bycourseorder'), 'dateasc' => get_string('datemostrecentlast'), 'datedesc' => get_string('datemostrecentfirst'));
     $mform->addElement('select', 'sortby', get_string('sortby'), $options);
     $mform->setAdvanced('sortby');
     $mform->addElement('date_time_selector', 'date', get_string('since'), array('optional' => true));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setType('courseid', PARAM_INT);
     $this->add_action_buttons(false, get_string('showrecent'));
 }
Exemple #23
0
/**
 * Determine if a given group is visible to user or not in a given context.
 *
 * @since Moodle 2.6
 * @param int      $groupid Group id to test. 0 for all groups.
 * @param stdClass $course  Course object.
 * @param stdClass $cm      Course module object.
 * @param int      $userid  user id to test against. Defaults to $USER.
 * @return boolean true if visible, false otherwise
 */
function groups_group_visible($groupid, $course, $cm = null, $userid = null)
{
    global $USER;
    if (empty($userid)) {
        $userid = $USER->id;
    }
    $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
    if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
        // Groups are not used, or everything is visible, no need to go any further.
        return true;
    }
    $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
    if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
        // User can see everything. Groupid = 0 is handled here as well.
        return true;
    } else {
        if ($groupid != 0) {
            // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
            $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
            if (array_key_exists($groupid, $groups)) {
                // User can see the group.
                return true;
            }
        }
    }
    return false;
}
Exemple #24
0
    if ($CFG->bloglevel < BLOG_SITE_LEVEL) {
        print_error('groupblogdisable', 'blog');
    }
    if (!($group = groups_get_group($groupid))) {
        print_error(get_string('invalidgroupid', 'blog'));
    }
    if (!($course = $DB->get_record('course', array('id' => $group->courseid)))) {
        print_error('invalidcourseid');
    }
    $coursecontext = context_course::instance($course->id);
    $courseid = $course->id;
    require_login($course);
    if (!has_capability('moodle/blog:view', $sitecontext)) {
        print_error(get_string('cannotviewcourseorgroupblog', 'blog'));
    }
    if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
        if (!groups_is_member($groupid)) {
            print_error('notmemberofgroup');
        }
    }
}
if (!empty($userid)) {
    if ($CFG->bloglevel < BLOG_USER_LEVEL) {
        print_error('blogdisable', 'blog');
    }
    if (!($user = $DB->get_record('user', array('id' => $userid)))) {
        print_error('invaliduserid');
    }
    if ($user->deleted) {
        echo $OUTPUT->header();
        echo $OUTPUT->heading(get_string('userdeleted'));
Exemple #25
0
/**
 * Returns posts made by the selected user in the requested courses.
 *
 * This method can be used to return all of the posts made by the requested user
 * within the given courses.
 * For each course the access of the current user and requested user is checked
 * and then for each post access to the post and forum is checked as well.
 *
 * This function is safe to use with usercapabilities.
 *
 * @global moodle_database $DB
 * @param stdClass $user The user whose posts we want to get
 * @param array $courses The courses to search
 * @param bool $musthaveaccess If set to true errors will be thrown if the user
 *                             cannot access one or more of the courses to search
 * @param bool $discussionsonly If set to true only discussion starting posts
 *                              will be returned.
 * @param int $limitfrom The offset of records to return
 * @param int $limitnum The number of records to return
 * @return stdClass An object the following properties
 *               ->totalcount: the total number of posts made by the requested user
 *                             that the current user can see.
 *               ->courses: An array of courses the current user can see that the
 *                          requested user has posted in.
 *               ->forums: An array of forums relating to the posts returned in the
 *                         property below.
 *               ->posts: An array containing the posts to show for this request.
 */
function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
    global $DB, $USER, $CFG;

    $return = new stdClass;
    $return->totalcount = 0;    // The total number of posts that the current user is able to view
    $return->courses = array(); // The courses the current user can access
    $return->forums = array();  // The forums that the current user can access that contain posts
    $return->posts = array();   // The posts to display

    // First up a small sanity check. If there are no courses to check we can
    // return immediately, there is obviously nothing to search.
    if (empty($courses)) {
        return $return;
    }

    // A couple of quick setups
    $isloggedin = isloggedin();
    $isguestuser = $isloggedin && isguestuser();
    $iscurrentuser = $isloggedin && $USER->id == $user->id;

    // Checkout whether or not the current user has capabilities over the requested
    // user and if so they have the capabilities required to view the requested
    // users content.
    $usercontext = context_user::instance($user->id, MUST_EXIST);
    $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
    $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);

    // Before we actually search each course we need to check the user's access to the
    // course. If the user doesn't have the appropraite access then we either throw an
    // error if a particular course was requested or we just skip over the course.
    foreach ($courses as $course) {
        $coursecontext = context_course::instance($course->id, MUST_EXIST);
        if ($iscurrentuser || $hascapsonuser) {
            // If it is the current user, or the current user has capabilities to the
            // requested user then all we need to do is check the requested users
            // current access to the course.
            // Note: There is no need to check group access or anything of the like
            // as either the current user is the requested user, or has granted
            // capabilities on the requested user. Either way they can see what the
            // requested user posted, although its VERY unlikely in the `parent` situation
            // that the current user will be able to view the posts in context.
            if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
                // Need to have full access to a course to see the rest of own info
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }
        } else {
            // Check whether the current user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course)) {
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }

            // Check whether the requested user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course, $user)) {
                if ($musthaveaccess) {
                    print_error('notenrolled', 'forum');
                }
                continue;
            }

            // If groups are in use and enforced throughout the course then make sure
            // we can meet in at least one course level group.
            // Note that we check if either the current user or the requested user have
            // the capability to access all groups. This is because with that capability
            // a user in group A could post in the group B forum. Grrrr.
            if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
              && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
                // If its the guest user to bad... the guest user cannot access groups
                if (!$isloggedin or $isguestuser) {
                    // do not use require_login() here because we might have already used require_login($course)
                    if ($musthaveaccess) {
                        redirect(get_login_url());
                    }
                    continue;
                }
                // Get the groups of the current user
                $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Get the groups the requested user is a member of
                $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Check whether they are members of the same group. If they are great.
                $intersect = array_intersect($mygroups, $usergroups);
                if (empty($intersect)) {
                    // But they're not... if it was a specific course throw an error otherwise
                    // just skip this course so that it is not searched.
                    if ($musthaveaccess) {
                        print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
                    }
                    continue;
                }
            }
        }
        // Woo hoo we got this far which means the current user can search this
        // this course for the requested user. Although this is only the course accessibility
        // handling that is complete, the forum accessibility tests are yet to come.
        $return->courses[$course->id] = $course;
    }
    // No longer beed $courses array - lose it not it may be big
    unset($courses);

    // Make sure that we have some courses to search
    if (empty($return->courses)) {
        // If we don't have any courses to search then the reality is that the current
        // user doesn't have access to any courses is which the requested user has posted.
        // Although we do know at this point that the requested user has posts.
        if ($musthaveaccess) {
            print_error('permissiondenied');
        } else {
            return $return;
        }
    }

    // Next step: Collect all of the forums that we will want to search.
    // It is important to note that this step isn't actually about searching, it is
    // about determining which forums we can search by testing accessibility.
    $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);

    // Will be used to build the where conditions for the search
    $forumsearchwhere = array();
    // Will be used to store the where condition params for the search
    $forumsearchparams = array();
    // Will record forums where the user can freely access everything
    $forumsearchfullaccess = array();
    // DB caching friendly
    $now = round(time(), -2);
    // For each course to search we want to find the forums the user has posted in
    // and providing the current user can access the forum create a search condition
    // for the forum to get the requested users posts.
    foreach ($return->courses as $course) {
        // Now we need to get the forums
        $modinfo = get_fast_modinfo($course);
        if (empty($modinfo->instances['forum'])) {
            // hmmm, no forums? well at least its easy... skip!
            continue;
        }
        // Iterate
        foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
            if (!$cm->uservisible or !isset($forums[$forumid])) {
                continue;
            }
            // Get the forum in question
            $forum = $forums[$forumid];
            // This is needed for functionality later on in the forum code....
            $forum->cm = $cm;

            // Check that either the current user can view the forum, or that the
            // current user has capabilities over the requested user and the requested
            // user can view the discussion
            if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
                continue;
            }

            // This will contain forum specific where clauses
            $forumsearchselect = array();
            if (!$iscurrentuser && !$hascapsonuser) {
                // Make sure we check group access
                if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
                    $groups = $modinfo->get_groups($cm->groupingid);
                    $groups[] = -1;
                    list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
                    $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
                    $forumsearchselect[] = "d.groupid $groupid_sql";
                }

                // hidden timed discussions
                if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
                    $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
                    $forumsearchparams['userid'.$forumid] = $user->id;
                    $forumsearchparams['timestart'.$forumid] = $now;
                    $forumsearchparams['timeend'.$forumid] = $now;
                }

                // qanda access
                if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
                    // We need to check whether the user has posted in the qanda forum.
                    $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
                    if (!empty($discussionspostedin)) {
                        $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
                        foreach ($discussionspostedin as $d) {
                            $forumonlydiscussions[] = $d->id;
                        }
                        list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
                        $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
                        $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
                    } else {
                        $forumsearchselect[] = "p.parent = 0";
                    }

                }

                if (count($forumsearchselect) > 0) {
                    $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
                    $forumsearchparams['forum'.$forumid] = $forumid;
                } else {
                    $forumsearchfullaccess[] = $forumid;
                }
            } else {
                // The current user/parent can see all of their own posts
                $forumsearchfullaccess[] = $forumid;
            }
        }
    }

    // If we dont have any search conditions, and we don't have any forums where
    // the user has full access then we just return the default.
    if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
        return $return;
    }

    // Prepare a where condition for the full access forums.
    if (count($forumsearchfullaccess) > 0) {
        list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
        $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
        $forumsearchwhere[] = "(d.forum $fullidsql)";
    }

    // Prepare SQL to both count and search.
    // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
    // oracle and mssql.
    $userfields = user_picture::fields('u', null, 'useridx');
    $countsql = 'SELECT COUNT(*) ';
    $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
    $wheresql = implode(" OR ", $forumsearchwhere);

    if ($discussionsonly) {
        if ($wheresql == '') {
            $wheresql = 'p.parent = 0';
        } else {
            $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
        }
    }

    $sql = "FROM {forum_posts} p
            JOIN {forum_discussions} d ON d.id = p.discussion
            JOIN {user} u ON u.id = p.userid
           WHERE ($wheresql)
             AND p.userid = :userid ";
    $orderby = "ORDER BY p.modified DESC";
    $forumsearchparams['userid'] = $user->id;

    // Set the total number posts made by the requested user that the current user can see
    $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
    // Set the collection of posts that has been requested
    $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);

    // We need to build an array of forums for which posts will be displayed.
    // We do this here to save the caller needing to retrieve them themselves before
    // printing these forums posts. Given we have the forums already there is
    // practically no overhead here.
    foreach ($return->posts as $post) {
        if (!array_key_exists($post->forum, $return->forums)) {
            $return->forums[$post->forum] = $forums[$post->forum];
        }
    }

    return $return;
}
Exemple #26
0
/**
 * Determine if the current user can see at least one of the groups of the specified user.
 *
 * @param stdClass $course  Course object.
 * @param int $userid  user id to check against.
 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
 * @return boolean true if visible, false otherwise
 * @since Moodle 2.9
 */
function groups_user_groups_visible($course, $userid, $cm = null)
{
    global $USER;
    $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
    if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
        // Groups are not used, or everything is visible, no need to go any further.
        return true;
    }
    $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
    if (has_capability('moodle/site:accessallgroups', $context)) {
        // User can see everything.
        return true;
    } else {
        // Group mode is separate, and user doesn't have access all groups capability.
        if (empty($cm)) {
            $usergroups = groups_get_all_groups($course->id, $userid);
            $currentusergroups = groups_get_all_groups($course->id, $USER->id);
        } else {
            $usergroups = groups_get_activity_allowed_groups($cm, $userid);
            $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
        }
        $samegroups = array_intersect_key($currentusergroups, $usergroups);
        if (!empty($samegroups)) {
            // We share groups!
            return true;
        }
    }
    return false;
}
Exemple #27
0
$datestring->mins = get_string('mins');
$datestring->sec = get_string('sec');
$datestring->secs = get_string('secs');
if ($mode !== null) {
    $mode = (int) $mode;
    $SESSION->userindexmode = $mode;
} else {
    if (isset($SESSION->userindexmode)) {
        $mode = (int) $SESSION->userindexmode;
    } else {
        $mode = MODE_BRIEF;
    }
}
// Check to see if groups are being used in this course
// and if so, set $currentgroup to reflect the current group.
$groupmode = groups_get_course_groupmode($course);
// Groups are being used.
$currentgroup = groups_get_course_group($course, true);
if (!$currentgroup) {
    // To make some other functions work better later.
    $currentgroup = null;
}
$isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));
$PAGE->set_title("{$course->shortname}: " . get_string('participants'));
$PAGE->set_heading($course->fullname);
$PAGE->set_pagetype('course-view-' . $course->format);
$PAGE->add_body_class('path-user');
// So we can style it independently.
$PAGE->set_other_editing_capability('moodle/course:manageactivities');
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('participants'));
Exemple #28
0
 /**
  * Validate access permissions to the report
  *
  * @param  int  $courseid the courseid
  * @param  int  $userid   the user id to retrieve data from
  * @param  int $groupid   the group id
  * @return array with the parameters cleaned and other required information
  * @since  Moodle 3.2
  */
 protected static function check_report_access($courseid, $userid, $groupid = 0)
 {
     global $USER;
     // Validate the parameter.
     $params = self::validate_parameters(self::get_grades_table_parameters(), array('courseid' => $courseid, 'userid' => $userid, 'groupid' => $groupid));
     // Compact/extract functions are not recommended.
     $courseid = $params['courseid'];
     $userid = $params['userid'];
     $groupid = $params['groupid'];
     // Function get_course internally throws an exception if the course doesn't exist.
     $course = get_course($courseid);
     $context = context_course::instance($courseid);
     self::validate_context($context);
     // Specific capabilities.
     require_capability('gradereport/user:view', $context);
     $user = null;
     if (empty($userid)) {
         require_capability('moodle/grade:viewall', $context);
     } else {
         $user = core_user::get_user($userid, '*', MUST_EXIST);
         core_user::require_active_user($user);
         // Check if we can view the user group (if any).
         // When userid == 0, we are retrieving all the users, we'll check then if a groupid is required.
         if (!groups_user_groups_visible($course, $user->id)) {
             throw new moodle_exception('notingroup');
         }
     }
     $access = false;
     if (has_capability('moodle/grade:viewall', $context)) {
         // Can view all course grades.
         $access = true;
     } else {
         if ($userid == $USER->id and has_capability('moodle/grade:view', $context) and $course->showgrades) {
             // View own grades.
             $access = true;
         }
     }
     if (!$access) {
         throw new moodle_exception('nopermissiontoviewgrades', 'error');
     }
     if (!empty($groupid)) {
         // Determine is the group is visible to user.
         if (!groups_group_visible($groupid, $course)) {
             throw new moodle_exception('notingroup');
         }
     } else {
         // Check to see if groups are being used here.
         if ($groupmode = groups_get_course_groupmode($course)) {
             $groupid = groups_get_course_group($course);
             // Determine is the group is visible to user (this is particullary for the group 0).
             if (!groups_group_visible($groupid, $course)) {
                 throw new moodle_exception('notingroup');
             }
         } else {
             $groupid = 0;
         }
     }
     return array($params, $course, $context, $user, $groupid);
 }
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
     // Course context
     $systemcontext = get_system_context();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canviewusercourse && !$canviewuser || !can_access_course($course, $user->id)) {
                 return false;
             }
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
                 // If groups are in use, make sure we can see that group
                 return false;
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
     }
     // Add a user setting branch
     $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
     $usersetting->id = 'usersettings';
     if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
         // Automatically start by making it active
         $usersetting->make_active();
     }
     // Check if the user has been deleted
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     // Add the profile edit link
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link
     if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
     }
     // View the roles settings
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Portfolio
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_instances(true, false)) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', get_system_context())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Repository
     if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
         if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
             require_once $CFG->dirroot . '/repository/lib.php';
             $editabletypes = repository::get_editable_types($usercontext);
             $haseditabletypes = !empty($editabletypes);
             unset($editabletypes);
             $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
         } else {
             $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
         }
         if ($haseditabletypes) {
             $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id));
             $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
         }
     }
     // Messaging
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs
     if ($currentuser && !empty($CFG->bloglevel)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Login as ...
     if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
         $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey()));
         $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
     }
     return $usersetting;
 }
Exemple #30
0
    $datestring->sec   = get_string('sec');
    $datestring->secs  = get_string('secs');

    if ($mode !== NULL) {
        $mode = (int)$mode;
        $SESSION->userindexmode = $mode;
    } else if (isset($SESSION->userindexmode)) {
        $mode = (int)$SESSION->userindexmode;
    } else {
        $mode = MODE_BRIEF;
    }

/// Check to see if groups are being used in this course
/// and if so, set $currentgroup to reflect the current group

    $groupmode    = groups_get_course_groupmode($course);   // Groups are being used
    $currentgroup = groups_get_course_group($course, true);

    if (!$currentgroup) {      // To make some other functions work better later
        $currentgroup  = NULL;
    }

    $isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));

    if ($course->id===SITEID) {
        $PAGE->navbar->ignore_active();
    }

    $PAGE->navbar->add(get_string('participants'));
    $PAGE->set_title("$course->shortname: ".get_string('participants'));
    $PAGE->set_heading($course->fullname);