Example #1
0
/**
 * Deletes the link between the specified user and group.
 * @param mixed $groupid  The group id or group object
 * @param mixed $userid   The user id or user object
 * @return boolean True if deletion was successful, false otherwise
 */
function groups_remove_member($grouporid, $userorid)
{
    global $DB;
    if (is_object($userorid)) {
        $userid = $userorid->id;
        $user = $userorid;
    } else {
        $userid = $userorid;
        $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
    }
    if (is_object($grouporid)) {
        $groupid = $grouporid->id;
        $group = $grouporid;
    } else {
        $groupid = $grouporid;
        $group = $DB->get_record('groups', array('id' => $groupid), '*', MUST_EXIST);
    }
    if (!groups_is_member($groupid, $userid)) {
        return true;
    }
    $DB->delete_records('groups_members', array('groupid' => $groupid, 'userid' => $userid));
    //update group info
    $DB->set_field('groups', 'timemodified', time(), array('id' => $groupid));
    //trigger groups events
    $eventdata = new stdClass();
    $eventdata->groupid = $groupid;
    $eventdata->userid = $userid;
    events_trigger('groups_member_removed', $eventdata);
    return true;
}
 /**
  * Get list of course participants.
  *
  * @param int $courseid
  * @param text $withcapability
  * @param int $groupid
  * @param bool $onlyactive
  * @return array of course participants
  */
 public static function get_enrolled_users($courseid, $withcapability = null, $groupid = null, $onlyactive = false)
 {
     global $DB, $CFG, $USER;
     // Do basic automatic PARAM checks on incoming data, using params description
     // If any problems are found then exceptions are thrown with helpful error messages
     $params = self::validate_parameters(self::get_enrolled_users_parameters(), array('courseid' => $courseid, 'withcapability' => $withcapability, 'groupid' => $groupid, 'onlyactive' => $onlyactive));
     $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
     if ($courseid == SITEID) {
         $context = get_context_instance(CONTEXT_SYSTEM);
     } 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(get_string('errorcoursecontextnotvalid', 'webservice', $exceptionparam));
     }
     if ($courseid == SITEID) {
         require_capability('moodle/site:viewparticipants', $context);
     } else {
         require_capability('moodle/course:viewparticipants', $context);
     }
     if ($withcapability) {
         require_capability('moodle/role:review', $coursecontext);
     }
     if ($groupid && groups_is_member($groupid)) {
         require_capability('moodle/site:accessallgroups', $coursecontext);
     }
     if ($onlyactive) {
         require_capability('moodle/course:enrolreview', $coursecontext);
     }
     list($sqlparams, $params) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
     $sql = "SELECT ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id as usercontextid\n                  FROM {user_enrolments} ue\n                  JOIN {enrol} e ON (e.id = ue.enrolid)\n                  JOIN {user} u ON (ue.userid = u.id)\n                  JOIN {context} c ON (u.id = c.instanceid AND contextlevel = " . CONTEXT_USER . ")\n                  WHERE e.courseid = :courseid AND ue.userid IN ({$sqlparams})\n                  GROUP BY ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id";
     $params['courseid'] = $courseid;
     $enrolledusers = $DB->get_records_sql($sql, $params);
     $result = array();
     $isadmin = is_siteadmin($USER);
     $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
     foreach ($enrolledusers as $enrolleduser) {
         $profilimgurl = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f1');
         $profilimgurlsmall = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f2');
         $resultuser = array('courseid' => $enrolleduser->courseid, 'userid' => $enrolleduser->userid, 'fullname' => fullname($enrolleduser), 'profileimgurl' => $profilimgurl->out(false), 'profileimgurlsmall' => $profilimgurlsmall->out(false));
         // check if we can return username
         if ($isadmin) {
             $resultuser['username'] = $enrolleduser->username;
         }
         // check if we can return first and last name
         if ($isadmin or $canviewfullnames) {
             $resultuser['firstname'] = $enrolleduser->firstname;
             $resultuser['lastname'] = $enrolleduser->lastname;
         }
         $result[] = $resultuser;
     }
     return $result;
 }
Example #3
0
 /**
  * @return bool
  */
 public static function validate($params)
 {
     $dataformid = $params['dataformid'];
     $df = \mod_dataform_dataform::instance($dataformid);
     // Cannot add in a view that does not allow submission.
     if (!empty($params['viewid'])) {
         $view = $df->view_manager->get_view_by_id($params['viewid']);
         if (!$view or !$view->allows_submission()) {
             return false;
         }
     }
     // User at max entries (per interval).
     if ($df->user_at_max_entries(true)) {
         // No more entries for you (come back next interval or so).
         return false;
     }
     // Early entries.
     if ($df->is_early()) {
         $params['capabilities'] = array('mod/dataform:entryearlyadd');
         if (!parent::validate($params)) {
             return false;
         }
     }
     // Late entries.
     if ($df->is_past_due()) {
         $params['capabilities'] = array('mod/dataform:entrylateadd');
         if (!parent::validate($params)) {
             return false;
         }
     }
     $entry = !empty($params['entry']) ? $params['entry'] : \mod_dataform\pluginbase\dataformentry::blank_instance($df);
     // Own entry.
     if (\mod_dataform\pluginbase\dataformentry::is_own($entry)) {
         $params['capabilities'] = array('mod/dataform:entryownadd');
         return parent::validate($params);
     }
     // Group entry.
     if (\mod_dataform\pluginbase\dataformentry::is_grouped($entry)) {
         if (groups_is_member($entry->groupid)) {
             $params['capabilities'] = array('mod/dataform:entrygroupadd');
             return parent::validate($params);
         }
     }
     // Anonymous entry.
     if (\mod_dataform\pluginbase\dataformentry::is_anonymous($entry)) {
         if ((isguestuser() or !isloggedin()) and $df->anonymous) {
             return true;
         }
         $params['capabilities'] = array('mod/dataform:entryanonymousadd');
         return parent::validate($params);
     }
     // Any entry.
     if (\mod_dataform\pluginbase\dataformentry::is_others($entry)) {
         $params['capabilities'] = array('mod/dataform:entryanyadd');
         return parent::validate($params);
     }
     return false;
 }
 /**
  * @return bool
  */
 public static function validate($params)
 {
     $dataformid = $params['dataformid'];
     $df = \mod_dataform_dataform::instance($dataformid);
     // Cannot update in a view that does not allow submission.
     if (!empty($params['viewid'])) {
         $view = $df->view_manager->get_view_by_id($params['viewid']);
         if (!$view or !$view->allows_submission()) {
             return false;
         }
     }
     // Unspecified entry
     // if (empty($params['entry'])) {
     //    return self::has_capability('mod/dataform:entryanyupdate', $params);
     // }.
     // Early entries.
     if ($df->is_early()) {
         $params['capabilities'] = array('mod/dataform:entryearlyupdate');
         if (!parent::validate($params)) {
             return false;
         }
     }
     // Late entries.
     if ($df->is_past_due()) {
         $params['capabilities'] = array('mod/dataform:entrylateupdate');
         if (!parent::validate($params)) {
             return false;
         }
     }
     $entry = !empty($params['entry']) ? $params['entry'] : \mod_dataform\pluginbase\dataformentry::blank_instance($df);
     // Own entry.
     if (\mod_dataform\pluginbase\dataformentry::is_own($entry)) {
         $params['capabilities'] = array('mod/dataform:entryownupdate');
         return parent::validate($params);
     }
     // Group entry.
     if (\mod_dataform\pluginbase\dataformentry::is_grouped($entry)) {
         if (groups_is_member($entry->groupid)) {
             $params['capabilities'] = array('mod/dataform:entrygroupupdate');
             return parent::validate($params);
         }
     }
     // Anonymous entry.
     if (\mod_dataform\pluginbase\dataformentry::is_anonymous($entry)) {
         $params['capabilities'] = array('mod/dataform:entryanonymousupdate');
         return parent::validate($params);
     }
     // Any entry.
     if (\mod_dataform\pluginbase\dataformentry::is_others($entry)) {
         $params['capabilities'] = array('mod/dataform:entryanyupdate');
         return parent::validate($params);
     }
     return false;
 }
 public function test_destroy()
 {
     $fm = mr_fixture_manager::instance();
     $userid = $fm->get('user')->get('id');
     $groupid = $fm->get('group')->get('id');
     $this->assertFalse(groups_is_member($groupid, $userid));
     $gm = new mr_fixture_group_member($fm->get('group'), $fm->get('enroll'));
     $gm->build();
     $this->assertTrue(groups_is_member($groupid, $userid));
     $gm->destroy();
     $this->assertFalse(groups_is_member($groupid, $userid));
 }
Example #6
0
/**
 * Deletes the link between the specified user and group.
 * @param int $groupid The group to delete the user from
 * @param int $userid The user to delete
 * @return boolean True if deletion was successful, false otherwise
 */
function groups_remove_member($groupid, $userid)
{
    if (!groups_group_exists($groupid)) {
        return false;
    }
    if (!groups_is_member($groupid, $userid)) {
        return true;
    }
    if (!delete_records('groups_members', 'groupid', $groupid, 'userid', $userid)) {
        return false;
    }
    //update group info
    set_field('groups', 'timemodified', time(), 'id', $groupid);
    return true;
}
Example #7
0
/**
 * Returns a list of teachers by group
 * for sending email alerts to teachers
 *
 * @param stdClass $certificate
 * @param stdClass $user
 * @param stdClass $course
 * @param stdClass $cm
 * @return array the teacher array
 */
function certificate_get_teachers($certificate, $user, $course, $cm)
{
    global $USER;
    $context = context_module::instance($cm->id);
    $potteachers = get_users_by_capability($context, 'mod/certificate:manage', '', '', '', '', '', '', false, false);
    if (empty($potteachers)) {
        return array();
    }
    $teachers = array();
    if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS) {
        // Separate groups are being used
        if ($groups = groups_get_all_groups($course->id, $user->id)) {
            // Try to find all groups
            foreach ($groups as $group) {
                foreach ($potteachers as $t) {
                    if ($t->id == $user->id) {
                        continue;
                        // do not send self
                    }
                    if (groups_is_member($group->id, $t->id)) {
                        $teachers[$t->id] = $t;
                    }
                }
            }
        } else {
            // user not in group, try to find teachers without group
            foreach ($potteachers as $t) {
                if ($t->id == $USER->id) {
                    continue;
                    // do not send self
                }
                if (!groups_get_all_groups($course->id, $t->id)) {
                    //ugly hack
                    $teachers[$t->id] = $t;
                }
            }
        }
    } else {
        foreach ($potteachers as $t) {
            if ($t->id == $USER->id) {
                continue;
                // do not send self
            }
            $teachers[$t->id] = $t;
        }
    }
    return $teachers;
}
 /**
  * @return bool
  */
 public static function validate($params)
 {
     $dataformid = $params['dataformid'];
     $df = \mod_dataform_dataform::instance($dataformid);
     // Unspecified entry.
     if (empty($params['entry'])) {
         return self::has_capability('mod/dataform:entryanydelete', $params);
     }
     // Early entries.
     if ($df->is_early()) {
         $params['capabilities'] = array('mod/dataform:entryearlydelete');
         if (!parent::validate($params)) {
             return false;
         }
     }
     // Late entries.
     if ($df->is_past_due()) {
         $params['capabilities'] = array('mod/dataform:entrylatedelete');
         if (!parent::validate($params)) {
             return false;
         }
     }
     $entry = !empty($params['entry']) ? $params['entry'] : \mod_dataform\pluginbase\dataformentry::blank_instance($df);
     // Own entry.
     if (\mod_dataform\pluginbase\dataformentry::is_own($entry)) {
         $params['capabilities'] = array('mod/dataform:entryowndelete');
         return parent::validate($params);
     }
     // Group entry.
     if (\mod_dataform\pluginbase\dataformentry::is_grouped($entry)) {
         if (groups_is_member($entry->groupid)) {
             $params['capabilities'] = array('mod/dataform:entrygroupdelete');
             return parent::validate($params);
         }
     }
     // Anonymous entry.
     if (\mod_dataform\pluginbase\dataformentry::is_anonymous($entry)) {
         $params['capabilities'] = array('mod/dataform:entryanonymousdelete');
         return parent::validate($params);
     }
     // Any entry.
     if (\mod_dataform\pluginbase\dataformentry::is_others($entry)) {
         $params['capabilities'] = array('mod/dataform:entryanydelete');
         return parent::validate($params);
     }
     return false;
 }
Example #9
0
 /**
  * Get list of course participants.
  *
  * @param int $courseid
  * @param text $withcapability
  * @param int $groupid
  * @param bool $onlyactive
  * @return array of course participants
  */
 public static function get_enrolled_users($courseid, $withcapability, $groupid, $onlyactive)
 {
     global $DB;
     // Do basic automatic PARAM checks on incoming data, using params description
     // If any problems are found then exceptions are thrown with helpful error messages
     $params = self::validate_parameters(self::get_enrolled_users_parameters(), array('courseid' => $courseid, 'withcapability' => $withcapability, 'groupid' => $groupid, 'onlyactive' => $onlyactive));
     $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
     if ($courseid == SITEID) {
         $context = get_context_instance(CONTEXT_SYSTEM);
     } 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(get_string('errorcoursecontextnotvalid', 'webservice', $exceptionparam));
     }
     if ($courseid == SITEID) {
         require_capability('moodle/site:viewparticipants', $context);
     } else {
         require_capability('moodle/course:viewparticipants', $context);
     }
     if ($withcapability) {
         require_capability('moodle/role:review', $coursecontext);
     }
     if ($groupid) {
         if (groups_is_member($groupid)) {
             require_capability('moodle/site:accessallgroups', $coursecontext);
         }
     }
     if ($onlyactive) {
         require_capability('moodle/course:enrolreview', $coursecontext);
     }
     list($sql, $params) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
     $sql = "SELECT DISTINCT ue.userid, e.courseid\n                  FROM {user_enrolments} ue\n                  JOIN {enrol} e ON (e.id = ue.enrolid)\n                 WHERE e.courseid = :courseid AND ue.userid IN ({$sql})";
     $params['courseid'] = $courseid;
     $enrolledusers = $DB->get_records_sql($sql, $params);
     $result = array();
     foreach ($enrolledusers as $enrolleduser) {
         $result[] = array('courseid' => $enrolleduser->courseid, 'userid' => $enrolleduser->userid);
     }
     return $result;
 }
Example #10
0
/**
 * Deletes the link between the specified user and group.
 * @param int $groupid The group to delete the user from
 * @param int $userid The user to delete
 * @return boolean True if deletion was successful, false otherwise
 */
function groups_remove_member($groupid, $userid)
{
    if (!groups_group_exists($groupid)) {
        return false;
    }
    if (!groups_is_member($groupid, $userid)) {
        return true;
    }
    if (!delete_records('groups_members', 'groupid', $groupid, 'userid', $userid)) {
        return false;
    }
    //update group info
    set_field('groups', 'timemodified', time(), 'id', $groupid);
    //trigger groups events
    $eventdata = new object();
    $eventdata->groupid = $groupid;
    $eventdata->userid = $userid;
    events_trigger('groups_member_removed', $eventdata);
    return true;
}
Example #11
0
/**
 * Deletes the link between the specified user and group.
 * @param int $groupid The group to delete the user from
 * @param int $userid The user to delete
 * @return boolean True if deletion was successful, false otherwise
 */
function groups_remove_member($groupid, $userid)
{
    global $DB;
    if (!$DB->record_exists('user', array('id' => $userid))) {
        throw new moodle_exception('useriddoesntexist');
    }
    if (!groups_group_exists($groupid)) {
        throw new moodle_exception('cannotaddmembergroupiddoesntexist');
    }
    if (!groups_is_member($groupid, $userid)) {
        return true;
    }
    $DB->delete_records('groups_members', array('groupid' => $groupid, 'userid' => $userid));
    //update group info
    $DB->set_field('groups', 'timemodified', time(), array('id' => $groupid));
    //trigger groups events
    $eventdata = new object();
    $eventdata->groupid = $groupid;
    $eventdata->userid = $userid;
    events_trigger('groups_member_removed', $eventdata);
    return true;
}
Example #12
0
 /**
  * Event processor - cohort member added.
  * @param \core\event\cohort_member_added $event
  * @return bool
  */
 public static function member_added(\core\event\cohort_member_added $event)
 {
     global $DB, $CFG;
     require_once "{$CFG->dirroot}/group/lib.php";
     if (!enrol_is_enabled('cohort')) {
         return true;
     }
     // Does any enabled cohort instance want to sync with this cohort?
     $sql = "SELECT e.*, r.id as roleexists\n                  FROM {enrol} e\n             LEFT JOIN {role} r ON (r.id = e.roleid)\n                 WHERE e.customint1 = :cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus\n              ORDER BY e.id ASC";
     $params['cohortid'] = $event->objectid;
     $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
     if (!($instances = $DB->get_records_sql($sql, $params))) {
         return true;
     }
     $plugin = enrol_get_plugin('cohort');
     foreach ($instances as $instance) {
         if ($instance->status != ENROL_INSTANCE_ENABLED) {
             // No roles for disabled instances.
             $instance->roleid = 0;
         } else {
             if ($instance->roleid and !$instance->roleexists) {
                 // Invalid role - let's just enrol, they will have to create new sync and delete this one.
                 $instance->roleid = 0;
             }
         }
         unset($instance->roleexists);
         // No problem if already enrolled.
         $plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE);
         // Sync groups.
         if ($instance->customint2) {
             if (!groups_is_member($instance->customint2, $event->relateduserid)) {
                 if ($group = $DB->get_record('groups', array('id' => $instance->customint2, 'courseid' => $instance->courseid))) {
                     groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id);
                 }
             }
         }
     }
     return true;
 }
Example #13
0
    /**
     * Returns a list of teachers that should be grading given submission
     *
     * @param object $user
     * @return array
     */
    function get_graders($user) {
        //potential graders
        $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);

        $graders = array();
        if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
            if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
                foreach ($groups as $group) {
                    foreach ($potgraders as $t) {
                        if ($t->id == $user->id) {
                            continue; // do not send self
                        }
                        if (groups_is_member($group->id, $t->id)) {
                            $graders[$t->id] = $t;
                        }
                    }
                }
            } else {
                // user not in group, try to find graders without group
                foreach ($potgraders as $t) {
                    if ($t->id == $user->id) {
                        continue; // do not send self
                    }
                    if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
                        $graders[$t->id] = $t;
                    }
                }
            }
        } else {
            foreach ($potgraders as $t) {
                if ($t->id == $user->id) {
                    continue; // do not send self
                }
                $graders[$t->id] = $t;
            }
        }
        return $graders;
    }
Example #14
0
/**
 * checks to see if a user can view a particular post
 *
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @uses SEPARATEGROUPS
 * @param object $post
 * @param object $course
 * @param object $cm
 * @param object $forum
 * @param object $discussion
 * @param object $user
 */
function forum_user_can_view_post($post, $course, $cm, $forum, $discussion, $user=NULL){

    global $CFG, $USER;

    if (!$user){
        $user = $USER;
    }

    $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
    if (!has_capability('mod/forum:viewdiscussion', $modcontext)) {
        return false;
    }

// If it's a grouped discussion, make sure the user is a member
    if ($discussion->groupid > 0) {
        $groupmode = groups_get_activity_groupmode($cm);
        if ($groupmode == SEPARATEGROUPS) {
            return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $modcontext);
        }
    }
    return true;
}
Example #15
0
 }
 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid) && !empty($users)) {
     $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
     foreach ($users as $key => $user) {
         if (!isset($groupingusers[$user->id])) {
             unset($users[$key]);
         }
     }
 }
 /// Now prepare table with student assessments and submissions
 $tablesort->data = array();
 $tablesort->sortdata = array();
 foreach ($users as $user) {
     // skip if student not in group
     if ($currentgroup) {
         if (!groups_is_member($currentgroup, $user->id)) {
             continue;
         }
     }
     if ($submissions = workshop_get_user_submissions($workshop, $user)) {
         foreach ($submissions as $submission) {
             $data = array();
             $sortdata = array();
             $data[] = "<a name=\"userid{$user->id}\" href=\"{$CFG->wwwroot}/user/view.php?id={$user->id}&amp;course={$course->id}\">" . fullname($user) . '</a>';
             $sortdata['firstname'] = $user->firstname;
             $sortdata['lastname'] = $user->lastname;
             if ($workshop->wtype) {
                 $data[] = workshop_print_user_assessments($workshop, $user, $gradinggrade);
                 $data[] = $gradinggrade;
                 $sortdata['agrade'] = $gradinggrade;
             }
Example #16
0
/**
 * Prints the discussion view screen for a forum.
 *
 * @global object
 * @global object
 * @param object $course The current course object.
 * @param object $forum Forum to be printed.
 * @param int $maxdiscussions .
 * @param string $displayformat The display format to use (optional).
 * @param string $sort Sort arguments for database query (optional).
 * @param int $groupmode Group mode of the forum (optional).
 * @param void $unused (originally current group)
 * @param int $page Page mode, page to display (optional).
 * @param int $perpage The maximum number of discussions per page(optional)
 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
 *
 */
function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '', $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null)
{
    global $CFG, $USER, $OUTPUT;
    if (!$cm) {
        if (!($cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course))) {
            print_error('invalidcoursemodule');
        }
    }
    $context = context_module::instance($cm->id);
    if (empty($sort)) {
        $sort = "d.timemodified DESC";
    }
    $olddiscussionlink = false;
    // Sort out some defaults
    if ($perpage <= 0) {
        $perpage = 0;
        $page = -1;
    }
    if ($maxdiscussions == 0) {
        // all discussions - backwards compatibility
        $page = -1;
        $perpage = 0;
        if ($displayformat == 'plain') {
            $displayformat = 'header';
            // Abbreviate display by default
        }
    } else {
        if ($maxdiscussions > 0) {
            $page = -1;
            $perpage = $maxdiscussions;
        }
    }
    $fullpost = false;
    if ($displayformat == 'plain') {
        $fullpost = true;
    }
    // Decide if current user is allowed to see ALL the current discussions or not
    // First check the group stuff
    if ($currentgroup == -1 or $groupmode == -1) {
        $groupmode = groups_get_activity_groupmode($cm, $course);
        $currentgroup = groups_get_activity_group($cm);
    }
    $groups = array();
    //cache
    // If the user can post discussions, then this is a good place to put the
    // button for it. We do not show the button if we are showing site news
    // and the current user is a guest.
    $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
    if (!$canstart and $forum->type !== 'news') {
        if (isguestuser() or !isloggedin()) {
            $canstart = true;
        }
        if (!is_enrolled($context) and !is_viewing($context)) {
            // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
            // normal users with temporary guest access see this button too, they are asked to enrol instead
            // do not show the button to users with suspended enrolments here
            $canstart = enrol_selfenrol_available($course->id);
        }
    }
    if ($canstart) {
        echo '<div class="singlebutton forumaddnew">';
        echo "<form id=\"newdiscussionform\" method=\"get\" action=\"{$CFG->wwwroot}/mod/forum/post.php\">";
        echo '<div>';
        echo "<input type=\"hidden\" name=\"forum\" value=\"{$forum->id}\" />";
        switch ($forum->type) {
            case 'news':
            case 'blog':
                $buttonadd = get_string('addanewtopic', 'forum');
                break;
            case 'qanda':
                $buttonadd = get_string('addanewquestion', 'forum');
                break;
            default:
                $buttonadd = get_string('addanewdiscussion', 'forum');
                break;
        }
        echo '<input type="submit" value="' . $buttonadd . '" />';
        echo '</div>';
        echo '</form>';
        echo "</div>\n";
    } else {
        if (isguestuser() or !isloggedin() or $forum->type == 'news' or $forum->type == 'qanda' and !has_capability('mod/forum:addquestion', $context) or $forum->type != 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
            // no button and no info
        } else {
            if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
                // inform users why they can not post new discussion
                if (!$currentgroup) {
                    echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
                } else {
                    if (!groups_is_member($currentgroup)) {
                        echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
                    }
                }
            }
        }
    }
    // Get all the recent discussions we're allowed to see
    $getuserlastmodified = $displayformat == 'header';
    if (!($discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage))) {
        echo '<div class="forumnodiscuss">';
        if ($forum->type == 'news') {
            echo '(' . get_string('nonews', 'forum') . ')';
        } else {
            if ($forum->type == 'qanda') {
                echo '(' . get_string('noquestions', 'forum') . ')';
            } else {
                echo '(' . get_string('nodiscussions', 'forum') . ')';
            }
        }
        echo "</div>\n";
        return;
    }
    // If we want paging
    if ($page != -1) {
        ///Get the number of discussions found
        $numdiscussions = forum_get_discussions_count($cm);
        ///Show the paging bar
        echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f={$forum->id}");
        if ($numdiscussions > 1000) {
            // saves some memory on sites with very large forums
            $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
        } else {
            $replies = forum_count_discussion_replies($forum->id);
        }
    } else {
        $replies = forum_count_discussion_replies($forum->id);
        if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
            $olddiscussionlink = true;
        }
    }
    $canviewparticipants = has_capability('moodle/course:viewparticipants', $context);
    $strdatestring = get_string('strftimerecentfull');
    // Check if the forum is tracked.
    if ($cantrack = forum_tp_can_track_forums($forum)) {
        $forumtracked = forum_tp_is_tracked($forum);
    } else {
        $forumtracked = false;
    }
    if ($forumtracked) {
        $unreads = forum_get_discussions_unread($cm);
    } else {
        $unreads = array();
    }
    if ($displayformat == 'header') {
        echo '<table cellspacing="0" class="forumheaderlist">';
        echo '<thead>';
        echo '<tr>';
        echo '<th class="header topic" scope="col">' . get_string('discussion', 'forum') . '</th>';
        echo '<th class="header author" colspan="2" scope="col">' . get_string('startedby', 'forum') . '</th>';
        if ($groupmode > 0) {
            echo '<th class="header group" scope="col">' . get_string('group') . '</th>';
        }
        if (has_capability('mod/forum:viewdiscussion', $context)) {
            echo '<th class="header replies" scope="col">' . get_string('replies', 'forum') . '</th>';
            // If the forum can be tracked, display the unread column.
            if ($cantrack) {
                echo '<th class="header replies" scope="col">' . get_string('unread', 'forum');
                if ($forumtracked) {
                    echo '<a title="' . get_string('markallread', 'forum') . '" href="' . $CFG->wwwroot . '/mod/forum/markposts.php?f=' . $forum->id . '&amp;mark=read&amp;returnpage=view.php">' . '<img src="' . $OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="' . get_string('markallread', 'forum') . '" /></a>';
                }
                echo '</th>';
            }
        }
        echo '<th class="header lastpost" scope="col">' . get_string('lastpost', 'forum') . '</th>';
        if (has_capability('mod/forum:viewdiscussion', $context)) {
            if (\mod_forum\subscriptions::is_subscribable($forum)) {
                echo '<th class="header discussionsubscription" scope="col">&nbsp;</th>';
            }
        }
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
    }
    foreach ($discussions as $discussion) {
        if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) && !forum_user_has_posted($forum->id, $discussion->discussion, $USER->id)) {
            $canviewparticipants = false;
        }
        if (!empty($replies[$discussion->discussion])) {
            $discussion->replies = $replies[$discussion->discussion]->replies;
            $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
        } else {
            $discussion->replies = 0;
        }
        // SPECIAL CASE: The front page can display a news item post to non-logged in users.
        // All posts are read in this case.
        if (!$forumtracked) {
            $discussion->unread = '-';
        } else {
            if (empty($USER)) {
                $discussion->unread = 0;
            } else {
                if (empty($unreads[$discussion->discussion])) {
                    $discussion->unread = 0;
                } else {
                    $discussion->unread = $unreads[$discussion->discussion];
                }
            }
        }
        if (isloggedin()) {
            $ownpost = $discussion->userid == $USER->id;
        } else {
            $ownpost = false;
        }
        // Use discussion name instead of subject of first post
        $discussion->subject = $discussion->name;
        switch ($displayformat) {
            case 'header':
                if ($groupmode > 0) {
                    if (isset($groups[$discussion->groupid])) {
                        $group = $groups[$discussion->groupid];
                    } else {
                        $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
                    }
                } else {
                    $group = -1;
                }
                forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked, $canviewparticipants, $context);
                break;
            default:
                $link = false;
                if ($discussion->replies) {
                    $link = true;
                } else {
                    $modcontext = context_module::instance($cm->id);
                    $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
                }
                $discussion->forum = $forum->id;
                forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false, '', null, true, $forumtracked);
                break;
        }
    }
    if ($displayformat == "header") {
        echo '</tbody>';
        echo '</table>';
    }
    if ($olddiscussionlink) {
        if ($forum->type == 'news') {
            $strolder = get_string('oldertopics', 'forum');
        } else {
            $strolder = get_string('olderdiscussions', 'forum');
        }
        echo '<div class="forumolddiscuss">';
        echo '<a href="' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id . '&amp;showall=1">';
        echo $strolder . '</a> ...</div>';
    }
    if ($page != -1) {
        ///Show the paging bar
        echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f={$forum->id}");
    }
}
Example #17
0
function workshop_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, $workshop = "0", $user = "", $groupid = "")
{
    // Returns all workshop posts since a given time.  If workshop is specified then
    // this restricts the results
    global $CFG;
    if ($workshop) {
        $workshopselect = " AND cm.id = '{$workshop}'";
    } else {
        $workshopselect = "";
    }
    if ($user) {
        $userselect = " AND u.id = '{$user}'";
    } else {
        $userselect = "";
    }
    $posts = get_records_sql("SELECT s.*, u.firstname, u.lastname,\n            u.picture, cm.instance, w.name, cm.section, cm.groupmode,\n            cm.course, cm.groupingid, cm.groupmembersonly, cm.id as cmid\n            FROM {$CFG->prefix}workshop_submissions s,\n            {$CFG->prefix}user u,\n            {$CFG->prefix}course_modules cm,\n            {$CFG->prefix}workshop w\n            WHERE s.timecreated  > '{$sincetime}' {$workshopselect}\n            AND s.userid = u.id {$userselect}\n            AND w.course = '{$courseid}'\n            AND cm.instance = w.id\n            AND cm.course = w.course\n            AND s.workshopid = w.id\n            ORDER BY s.id");
    if (empty($posts)) {
        return;
    }
    foreach ($posts as $post) {
        if ((empty($groupid) || groups_is_member($groupid, $post->userid)) && groups_course_module_visible($post)) {
            $tmpactivity = new Object();
            $tmpactivity->type = "workshop";
            $tmpactivity->defaultindex = $index;
            $tmpactivity->instance = $post->instance;
            $tmpactivity->name = $post->name;
            $tmpactivity->section = $post->section;
            $tmpactivity->content->id = $post->id;
            $tmpactivity->content->title = $post->title;
            $tmpactivity->user->userid = $post->userid;
            $tmpactivity->user->fullname = fullname($post);
            $tmpactivity->user->picture = $post->picture;
            $tmpactivity->cmid = $post->cmid;
            $tmpactivity->timestamp = $post->timecreated;
            $activities[] = $tmpactivity;
            $index++;
        }
    }
    return;
}
Example #18
0
/**
 * Validate comment parameter before perform other comments actions
 *
 * @param stdClass $comment_param {
 *              context  => context the context object
 *              courseid => int course id
 *              cm       => stdClass course module object
 *              commentarea => string comment area
 *              itemid      => int itemid
 * }
 * @return boolean
 */
function data_comment_validate($comment_param) {
    global $DB;
    // validate comment area
    if ($comment_param->commentarea != 'database_entry') {
        throw new comment_exception('invalidcommentarea');
    }
    // validate itemid
    if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
        throw new comment_exception('invalidcommentitemid');
    }
    if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
        throw new comment_exception('invalidid', 'data');
    }
    if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
        throw new comment_exception('coursemisconf');
    }
    if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
        throw new comment_exception('invalidcoursemodule');
    }
    if (!$data->comments) {
        throw new comment_exception('commentsoff', 'data');
    }
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    //check if approved
    if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
        throw new comment_exception('notapproved', 'data');
    }

    // group access
    if ($record->groupid) {
        $groupmode = groups_get_activity_groupmode($cm, $course);
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
            if (!groups_is_member($record->groupid)) {
                throw new comment_exception('notmemberofgroup');
            }
        }
    }
    // validate context id
    if ($context->id != $comment_param->context->id) {
        throw new comment_exception('invalidcontext');
    }
    // validation for comment deletion
    if (!empty($comment_param->commentid)) {
        if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
            if ($comment->commentarea != 'database_entry') {
                throw new comment_exception('invalidcommentarea');
            }
            if ($comment->contextid != $comment_param->context->id) {
                throw new comment_exception('invalidcontext');
            }
            if ($comment->itemid != $comment_param->itemid) {
                throw new comment_exception('invalidcommentitemid');
            }
        } else {
            throw new comment_exception('invalidcommentid');
        }
    }
    return true;
}
Example #19
0
        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'));
        echo $OUTPUT->footer();
Example #20
0
File: lib.php Project: dg711/moodle
/**
 * Validate comment parameter before perform other comments actions
 *
 * @param stdClass $comment_param {
 *              context  => context the context object
 *              courseid => int course id
 *              cm       => stdClass course module object
 *              commentarea => string comment area
 *              itemid      => int itemid
 * }
 *
 * @package  mod_wiki
 * @category comment
 *
 * @return boolean
 */
function wiki_comment_validate($comment_param)
{
    global $DB, $CFG;
    require_once $CFG->dirroot . '/mod/wiki/locallib.php';
    // validate comment area
    if ($comment_param->commentarea != 'wiki_page') {
        throw new comment_exception('invalidcommentarea');
    }
    // validate itemid
    if (!($record = $DB->get_record('wiki_pages', array('id' => $comment_param->itemid)))) {
        throw new comment_exception('invalidcommentitemid');
    }
    if (!($subwiki = wiki_get_subwiki($record->subwikiid))) {
        throw new comment_exception('invalidsubwikiid');
    }
    if (!($wiki = wiki_get_wiki_from_pageid($comment_param->itemid))) {
        throw new comment_exception('invalidid', 'data');
    }
    if (!($course = $DB->get_record('course', array('id' => $wiki->course)))) {
        throw new comment_exception('coursemisconf');
    }
    if (!($cm = get_coursemodule_from_instance('wiki', $wiki->id, $course->id))) {
        throw new comment_exception('invalidcoursemodule');
    }
    $context = context_module::instance($cm->id);
    // group access
    if ($subwiki->groupid) {
        $groupmode = groups_get_activity_groupmode($cm, $course);
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
            if (!groups_is_member($subwiki->groupid)) {
                throw new comment_exception('notmemberofgroup');
            }
        }
    }
    // validate context id
    if ($context->id != $comment_param->context->id) {
        throw new comment_exception('invalidcontext');
    }
    // validation for comment deletion
    if (!empty($comment_param->commentid)) {
        if ($comment = $DB->get_record('comments', array('id' => $comment_param->commentid))) {
            if ($comment->commentarea != 'wiki_page') {
                throw new comment_exception('invalidcommentarea');
            }
            if ($comment->contextid != $context->id) {
                throw new comment_exception('invalidcontext');
            }
            if ($comment->itemid != $comment_param->itemid) {
                throw new comment_exception('invalidcommentitemid');
            }
        } else {
            throw new comment_exception('invalidcommentid');
        }
    }
    return true;
}
Example #21
0
function calendar_edit_event_allowed($event)
{
    global $USER;
    // Must be logged in
    if (!isloggedin()) {
        return false;
    }
    // can not be using guest account
    if ($USER->username == "guest") {
        return false;
    }
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    // if user has manageentries at site level, return true
    if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
        return true;
    }
    // if groupid is set, it's definitely a group event
    if ($event->groupid) {
        // Allow users to add/edit group events if:
        // 1) They have manageentries (= entries for whole course)
        // 2) They have managegroupentries AND are in the group
        $group = get_record('groups', 'id', $event->groupid);
        return $group && (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) || has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) && groups_is_member($event->groupid));
    } else {
        if ($event->courseid) {
            // if groupid is not set, but course is set,
            // it's definiely a course event
            return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
        } else {
            if ($event->userid && $event->userid == $USER->id) {
                // if course is not set, but userid id set, it's a user event
                return has_capability('moodle/calendar:manageownentries', $sitecontext);
            }
        }
    }
    return false;
}
Example #22
0
 /**
  * Returns a list of teachers that should be grading given submission.
  *
  * @param int $userid The submission to grade
  * @return array
  */
 protected function get_graders($userid)
 {
     // Potential graders should be active users only.
     $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade", null, 'u.*', null, null, null, true);
     $graders = array();
     if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
         if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {
             foreach ($groups as $group) {
                 foreach ($potentialgraders as $grader) {
                     if ($grader->id == $userid) {
                         // Do not send self.
                         continue;
                     }
                     if (groups_is_member($group->id, $grader->id)) {
                         $graders[$grader->id] = $grader;
                     }
                 }
             }
         } else {
             // User not in group, try to find graders without group.
             foreach ($potentialgraders as $grader) {
                 if ($grader->id == $userid) {
                     // Do not send self.
                     continue;
                 }
                 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
                     $graders[$grader->id] = $grader;
                 }
             }
         }
     } else {
         foreach ($potentialgraders as $grader) {
             if ($grader->id == $userid) {
                 // Do not send self.
                 continue;
             }
             // Must be enrolled.
             if (is_enrolled($this->get_course_context(), $grader->id)) {
                 $graders[$grader->id] = $grader;
             }
         }
     }
     return $graders;
 }
 /**
  * Make a role assignment in the specified course using the specified role
  * id for the user whose id information is passed in the line data.
  *
  * @access public
  * @static
  * @param stdClass      $course           Course in which to make the role assignment
  * @param stdClass      $enrol_instance   Enrol instance to use for adding users to course
  * @param string        $ident_field      The field (column) name in Moodle user rec against which to query using the imported data
  * @param int           $role_id          Id of the role to use in the role assignment
  * @param boolean       $group_assign     Whether or not to assign users to groups
  * @param int           $group_id         Id of group to assign to, 0 indicates use group name from import file
  * @param boolean       $group_create     Whether or not to create new groups if needed
  * @param stored_file   $import_file      File in local repository from which to get enrollment and group data
  * @return string                         String message with results
  *
  * @uses $DB
  */
 public static function import_file(stdClass $course, stdClass $enrol_instance, $ident_field, $role_id, $group_assign, $group_id, $group_create, stored_file $import_file)
 {
     global $DB;
     // Default return value
     $result = '';
     // Need one of these in the loop
     $course_context = context_course::instance($course->id);
     // Choose the regex pattern based on the $ident_field
     switch ($ident_field) {
         case 'email':
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w.%-]*@[a-z0-9][a-z0-9.-]{0,61}[a-z0-9]\\.[a-z]{2,6})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         case 'idnumber':
             $regex_pattern = '/^"?\\s*(\\d{1,32})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         default:
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w@.-]*)\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
     }
     // If doing group assignments, want to know the valid
     // groups for the course
     $selected_group = null;
     if ($group_assign) {
         if (false === ($existing_groups = groups_get_all_groups($course->id))) {
             $existing_groups = array();
         }
         if ($group_id > 0) {
             if (array_key_exists($group_id, $existing_groups)) {
                 $selected_group = $existing_groups[$group_id];
             } else {
                 // Error condition
                 return sprintf(get_string('ERR_INVALID_GROUP_ID', self::PLUGIN_NAME), $group_id);
             }
         }
     }
     // Iterate the list of active enrol plugins looking for
     // the meta course plugin
     $metacourse = false;
     $enrols_enabled = enrol_get_instances($course->id, true);
     foreach ($enrols_enabled as $enrol) {
         if ($enrol->enrol == 'meta') {
             $metacourse = true;
             break;
         }
     }
     // Get an instance of the enrol_manual_plugin (not to be confused
     // with the enrol_instance arg)
     $manual_enrol_plugin = enrol_get_plugin('manual');
     $user_rec = $new_group = $new_grouping = null;
     // Open and fetch the file contents
     $fh = $import_file->get_content_file_handle();
     $line_num = 0;
     while (false !== ($line = fgets($fh))) {
         $line_num++;
         // Clean these up for each iteration
         unset($user_rec, $new_group, $new_grouping);
         if (!($line = trim($line))) {
             continue;
         }
         // Parse the line, from which we may get one or two
         // matches since the group name is an optional item
         // on a line by line basis
         if (!preg_match($regex_pattern, $line, $matches)) {
             $result .= sprintf(get_string('ERR_PATTERN_MATCH', self::PLUGIN_NAME), $line_num, $line);
             continue;
         }
         $ident_value = $matches[1];
         $group_name = isset($matches[2]) ? $matches[2] : '';
         // User must already exist, we import enrollments
         // into courses, not users into the system. Exclude
         // records marked as deleted. Because idnumber is
         // not enforced unique, possible multiple records
         // returned when using that identifying field, so
         // use ->get_records method to make that detection
         // and inform user
         $user_rec_array = $DB->get_records('user', array($ident_field => addslashes($ident_value), 'deleted' => 0));
         // Should have one and only one record, otherwise
         // report it and move on to the next
         $user_rec_count = count($user_rec_array);
         if ($user_rec_count == 0) {
             // No record found
             $result .= sprintf(get_string('ERR_USERID_INVALID', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         } elseif ($user_rec_count > 1) {
             // Too many records
             $result .= sprintf(get_string('ERR_USER_MULTIPLE_RECS', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         }
         $user_rec = array_shift($user_rec_array);
         // Fetch all the role assignments this user might have for this course's context
         $roles = get_user_roles($course_context, $user_rec->id, false);
         // If a user has a role in this course, then we leave it alone and move on
         // to the group assignment if there is one. If they have no role, then we
         // should go ahead and add one, as long as it is not a metacourse.
         if (!$roles && $role_id > 0) {
             if ($metacourse) {
                 $result .= sprintf(get_string('ERR_ENROLL_META', self::PLUGIN_NAME), $line_num, $ident_value);
             } else {
                 try {
                     $manual_enrol_plugin->enrol_user($enrol_instance, $user_rec->id, $role_id);
                 } catch (Exception $exc) {
                     $result .= sprintf(get_string('ERR_ENROLL_FAILED', self::PLUGIN_NAME), $line_num, $ident_value);
                     $result .= $exc->getMessage();
                     continue;
                 }
             }
         }
         // If no group assignments, or group is from file, but no
         // group found, next line
         if (!$group_assign || $group_id == 0 && empty($group_name)) {
             continue;
         }
         // If no group pre-selected, see if group from import already
         // created for that course
         $assign_group_id = 0;
         $assign_group_name = '';
         if ($selected_group != null) {
             $assign_group_id = $selected_group->id;
             $assign_group_name = $selected_group->name;
         } else {
             foreach ($existing_groups as $existing_group) {
                 if ($existing_group->name != $group_name) {
                     continue;
                 }
                 $assign_group_id = $existing_group->id;
                 $assign_group_name = $existing_group->name;
                 break;
             }
             // No group by that name
             if ($assign_group_id == 0) {
                 // Can not create one, next line
                 if (!$group_create) {
                     continue;
                 }
                 // Make a new group for this course
                 $new_group = new stdClass();
                 $new_group->name = addslashes($group_name);
                 $new_group->courseid = $course->id;
                 if (false === ($assign_group_id = groups_create_group($new_group))) {
                     $result .= sprintf(get_string('ERR_CREATE_GROUP', self::PLUGIN_NAME), $line_num, $group_name);
                     continue;
                 } else {
                     // Add the new group to our list for the benefit of
                     // the next contestant. Strip the slashes off the
                     // name since we do a name comparison earlier when
                     // trying to find the group in our local cache and
                     // an escaped semi-colon will cause the test to fail.
                     $new_group->name = $assign_group_name = stripslashes($new_group->name);
                     $new_group->id = $assign_group_id;
                     $existing_groups[] = $new_group;
                 }
             }
             // if ($assign_group_id == 0)
         }
         // Put the user in the group if not aleady in it
         if (!groups_is_member($assign_group_id, $user_rec->id) && !groups_add_member($assign_group_id, $user_rec->id)) {
             $result .= sprintf(get_string('ERR_GROUP_MEMBER', self::PLUGIN_NAME), $line_num, $ident_value, $assign_group_name);
             continue;
         }
         // Any other work...
     }
     // while fgets
     fclose($fh);
     return empty($result) ? get_string('INF_IMPORT_SUCCESS', self::PLUGIN_NAME) : $result;
 }
Example #24
0
                 $newgrades[] = $newgrade;
             }
             // otherwise, we ignore this column altogether
             // because user has chosen to ignore them (e.g. institution, address etc)
             break;
     }
 }
 // no user mapping supplied at all, or user mapping failed
 if (empty($studentid) || !is_numeric($studentid)) {
     // user not found, abort whole import
     $status = false;
     import_cleanup($importcode);
     echo $OUTPUT->notification('user mapping error, could not find user!');
     break;
 }
 if ($separatemode and !groups_is_member($currentgroup, $studentid)) {
     // not allowed to import into this group, abort
     $status = false;
     import_cleanup($importcode);
     echo $OUTPUT->notification('user not member of current group, can not update!');
     break;
 }
 // insert results of this students into buffer
 if ($status and !empty($newgrades)) {
     foreach ($newgrades as $newgrade) {
         // check if grade_grade is locked and if so, abort
         if (!empty($newgrade->itemid) and $grade_grade = new grade_grade(array('itemid' => $newgrade->itemid, 'userid' => $studentid))) {
             if ($grade_grade->is_locked()) {
                 // individual grade locked
                 $status = false;
                 import_cleanup($importcode);
Example #25
0
    /**
     * Setup page tabs, if options is empty, will set up active tab automatically
     * @param array $options, tabs options
     */
    protected function setup_tabs($options = array()) {
        global $CFG, $PAGE;
        $groupmode = groups_get_activity_groupmode($PAGE->cm);

        if (empty($CFG->usecomments) || !has_capability('mod/wiki:viewcomment', $PAGE->context)){
            unset($this->tabs['comments']);
        }

        if (!has_capability('mod/wiki:editpage', $PAGE->context)){
            unset($this->tabs['edit']);
        }

        if ($groupmode and $groupmode == VISIBLEGROUPS) {
            $currentgroup = groups_get_activity_group($PAGE->cm);
            $manage = has_capability('mod/wiki:managewiki', $PAGE->cm->context);
            $edit = has_capability('mod/wiki:editpage', $PAGE->context);
            if (!$manage and !($edit and groups_is_member($currentgroup))) {
                unset($this->tabs['edit']);
            }
        }

        if (empty($options)) {
            $this->tabs_options = array('activetab' => substr(get_class($this), 10));
        } else {
            $this->tabs_options = $options;
        }

    }
 /**
  * Creates the blocks main content
  *
  * @return string
  */
 public function get_content()
 {
     global $USER, $COURSE, $CFG, $OUTPUT, $DB;
     // If content has already been generated, don't waste time generating it again.
     if ($this->content !== null) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->text = '';
     $this->content->footer = '';
     $blockinstancesonpage = array();
     // Guests do not have any progress. Don't show them the block.
     if (!isloggedin() or isguestuser()) {
         return $this->content;
     }
     // Draw the multi-bar content for the Dashboard and Front page.
     if (block_progress_on_site_page()) {
         $courses = enrol_get_my_courses();
         $coursenametoshow = get_config('block_progress', 'coursenametoshow') ?: 'shortname';
         $sql = "SELECT bi.id,\n                           bp.id AS blockpositionid,\n                           COALESCE(bp.region, bi.defaultregion) AS region,\n                           COALESCE(bp.weight, bi.defaultweight) AS weight,\n                           COALESCE(bp.visible, 1) AS visible,\n                           bi.configdata\n                      FROM {block_instances} bi\n                 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id\n                                               AND " . $DB->sql_like('bp.pagetype', ':pagetype', false) . "\n                     WHERE bi.blockname = 'progress'\n                       AND bi.parentcontextid = :contextid\n                  ORDER BY region, weight, bi.id";
         foreach ($courses as $courseid => $course) {
             // Get specific block config and context.
             $modules = block_progress_modules_in_use($course->id);
             if ($course->visible && !empty($modules)) {
                 $context = block_progress_get_course_context($course->id);
                 $params = array('contextid' => $context->id, 'pagetype' => 'course-view-%');
                 $blockinstances = $DB->get_records_sql($sql, $params);
                 $blockinstancesonpage = array_merge($blockinstancesonpage, array_keys($blockinstances));
                 foreach ($blockinstances as $blockid => $blockinstance) {
                     $blockinstance->config = unserialize(base64_decode($blockinstance->configdata));
                     if (!empty($blockinstance->config)) {
                         $blockinstance->events = block_progress_event_information($blockinstance->config, $modules, $course->id);
                         $blockinstance->events = block_progress_filter_visibility($blockinstance->events, $USER->id, $context, $course);
                     }
                     if ($blockinstance->visible == 0 || empty($blockinstance->config) || $blockinstance->events == 0 || !empty($blockinstance->config->group) && !has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($blockinstance->config->group, $USER->id)) {
                         unset($blockinstances[$blockid]);
                     }
                 }
                 // Output the Progress Bar.
                 if (!empty($blockinstances)) {
                     $courselink = new moodle_url('/course/view.php', array('id' => $course->id));
                     $linktext = HTML_WRITER::tag('h3', s($course->{$coursenametoshow}));
                     $this->content->text .= HTML_WRITER::link($courselink, $linktext);
                 }
                 foreach ($blockinstances as $blockid => $blockinstance) {
                     if ($blockinstance->config->progressTitle != '') {
                         $this->content->text .= HTML_WRITER::tag('p', s(format_string($blockinstance->config->progressTitle)));
                     }
                     $attempts = block_progress_attempts($modules, $blockinstance->config, $blockinstance->events, $USER->id, $course->id);
                     $this->content->text .= block_progress_bar($modules, $blockinstance->config, $blockinstance->events, $USER->id, $blockinstance->id, $attempts, $course->id);
                 }
             }
         }
         // Show a message explaining lack of bars, but only while editing is on.
         if ($this->page->user_is_editing() && $this->content->text == '') {
             $this->content->text = get_string('no_blocks', 'block_progress');
         }
     } else {
         // Check if user is in group for block.
         if (!empty($this->config->group) && !has_capability('moodle/site:accessallgroups', $this->context) && !groups_is_member($this->config->group, $USER->id)) {
             return $this->content;
         }
         // Check if any activities/resources have been created.
         $modules = block_progress_modules_in_use($COURSE->id);
         if (empty($modules)) {
             if (has_capability('moodle/block:edit', $this->context)) {
                 $this->content->text .= get_string('no_events_config_message', 'block_progress');
             }
             return $this->content;
         }
         // Check if activities/resources have been selected in config.
         $events = block_progress_event_information($this->config, $modules, $COURSE->id);
         $context = block_progress_get_course_context($COURSE->id);
         $events = block_progress_filter_visibility($events, $USER->id, $context);
         if ($events === null || $events === 0) {
             if (has_capability('moodle/block:edit', $this->context)) {
                 $this->content->text .= get_string('no_events_message', 'block_progress');
                 if ($USER->editing) {
                     $parameters = array('id' => $COURSE->id, 'sesskey' => sesskey(), 'bui_editid' => $this->instance->id);
                     $url = new moodle_url('/course/view.php', $parameters);
                     $label = get_string('selectitemstobeadded', 'block_progress');
                     $this->content->text .= $OUTPUT->single_button($url, $label);
                     if ($events === 0) {
                         $url->param('turnallon', '1');
                         $label = get_string('addallcurrentitems', 'block_progress');
                         $this->content->text .= $OUTPUT->single_button($url, $label);
                     }
                 }
             }
             return $this->content;
         } else {
             if (empty($events)) {
                 if (has_capability('moodle/block:edit', $this->context)) {
                     $this->content->text .= get_string('no_visible_events_message', 'block_progress');
                 }
                 return $this->content;
             }
         }
         // Display progress bar.
         $attempts = block_progress_attempts($modules, $this->config, $events, $USER->id, $COURSE->id);
         $this->content->text = block_progress_bar($modules, $this->config, $events, $USER->id, $this->instance->id, $attempts, $COURSE->id);
         $blockinstancesonpage = array($this->instance->id);
         // Allow teachers to access the overview page.
         if (has_capability('block/progress:overview', $this->context)) {
             $parameters = array('progressbarid' => $this->instance->id, 'courseid' => $COURSE->id);
             $url = new moodle_url('/blocks/progress/overview.php', $parameters);
             $label = get_string('overview', 'block_progress');
             $options = array('class' => 'overviewButton');
             $this->content->text .= $OUTPUT->single_button($url, $label, 'post', $options);
         }
     }
     // Organise access to JS.
     $jsmodule = array('name' => 'block_progress', 'fullpath' => '/blocks/progress/module.js', 'requires' => array(), 'strings' => array());
     $arguments = array($blockinstancesonpage, array($USER->id));
     $this->page->requires->js_init_call('M.block_progress.init', $arguments, false, $jsmodule);
     return $this->content;
 }
Example #27
0
/**
* Check to ensure a user can view a group discussion.
*
* @param object $discussion
* @param object $cm
* @param object $context
* @return boolean returns true if they can view post, false otherwise
*/
function forum_user_can_see_group_discussion($discussion, $cm, $context) {

    // If it's a grouped discussion, make sure the user is a member.
    if ($discussion->groupid > 0) {
        $groupmode = groups_get_activity_groupmode($cm);
        if ($groupmode == SEPARATEGROUPS) {
            return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
        }
    }

    return true;
}
Example #28
0
        $datestring = get_string("never");
    }
    print_row(get_string("lastaccess") . ":", $datestring);
}
// Show roles in this course
if ($rolestring = get_user_roles_in_course($id, $course->id)) {
    print_row(get_string('roles') . ':', $rolestring);
}
// Show groups this user is in
if (!isset($hiddenfields['groups'])) {
    $accessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
    if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
        $groupstr = '';
        foreach ($usergroups as $group) {
            if ($course->groupmode == SEPARATEGROUPS and !$accessallgroups and $user->id != $USER->id) {
                if (!groups_is_member($group->id, $user->id)) {
                    continue;
                }
            }
            if ($course->groupmode != NOGROUPS) {
                $groupstr .= ' <a href="' . $CFG->wwwroot . '/user/index.php?id=' . $course->id . '&amp;group=' . $group->id . '">' . format_string($group->name) . '</a>,';
            } else {
                $groupstr .= ' ' . format_string($group->name);
                // the user/index.php shows groups only when course in group mode
            }
        }
        if ($groupstr !== '') {
            print_row(get_string("group") . ":", rtrim($groupstr, ', '));
        }
    }
}
Example #29
0
/**
 * Checks if current user can edit a subwiki
 *
 * @param $subwiki
 */
function wiki_user_can_edit($subwiki)
{
    global $USER;
    $wiki = wiki_get_wiki($subwiki->wikiid);
    $cm = get_coursemodule_from_instance('wiki', $wiki->id);
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    // Working depending on activity groupmode
    switch (groups_get_activity_groupmode($cm)) {
        case NOGROUPS:
            if ($wiki->wikimode == 'collaborative') {
                // Collaborative Mode:
                // There is a wiki for all the class.
                //
                // Only edit capbility needed
                return has_capability('mod/wiki:editpage', $context);
            } else {
                if ($wiki->wikimode == 'individual') {
                    // Individual Mode
                    // There is a wiki per user
                    // Only the owner of that wiki can edit it
                    if ($subwiki->userid == $USER->id) {
                        return has_capability('mod/wiki:editpage', $context);
                    } else {
                        // Current user is not the owner of that wiki.
                        // User must have:
                        //      mod/wiki:editpage capability
                        // and
                        //      mod/wiki:managewiki capability
                        $edit = has_capability('mod/wiki:editpage', $context);
                        $manage = has_capability('mod/wiki:managewiki', $context);
                        return $edit && $manage;
                    }
                } else {
                    //Error
                    return false;
                }
            }
        case SEPARATEGROUPS:
            if ($wiki->wikimode == 'collaborative') {
                // Collaborative Mode:
                // There is one wiki per group.
                //
                // Only members of subwiki group could edit that wiki
                if ($subwiki->groupid == groups_get_activity_group($cm)) {
                    // Only edit capability needed
                    return has_capability('mod/wiki:editpage', $context);
                } else {
                    // User is not part of that group
                    // User must have:
                    //      mod/wiki:managewiki capability
                    // and
                    //      moodle/site:accessallgroups capability
                    // and
                    //      mod/wiki:editpage capability
                    $manage = has_capability('mod/wiki:managewiki', $context);
                    $access = has_capability('moodle/site:accessallgroups', $context);
                    $edit = has_capability('mod/wiki:editpage', $context);
                    return $manage && $access && $edit;
                }
            } else {
                if ($wiki->wikimode == 'individual') {
                    // Individual Mode:
                    // Each person owns a wiki.
                    //
                    // Only the owner of that wiki can edit it
                    if ($subwiki->userid == $USER->id) {
                        return has_capability('mod/wiki:editpage', $context);
                    } else {
                        // Current user is not the owner of that wiki.
                        // User must have:
                        //      mod/wiki:managewiki capability
                        // and
                        //      moodle/site:accessallgroups capability
                        // and
                        //      mod/wiki:editpage capability
                        $manage = has_capability('mod/wiki:managewiki', $context);
                        $access = has_capability('moodle/site:accessallgroups', $context);
                        $edit = has_capability('mod/wiki:editpage', $context);
                        return $manage && $access && $edit;
                    }
                } else {
                    //Error
                    return false;
                }
            }
        case VISIBLEGROUPS:
            if ($wiki->wikimode == 'collaborative') {
                // Collaborative Mode:
                // There is one wiki per group.
                //
                // Only members of subwiki group could edit that wiki
                if (groups_is_member($subwiki->groupid)) {
                    // Only edit capability needed
                    return has_capability('mod/wiki:editpage', $context);
                } else {
                    // User is not part of that group
                    // User must have:
                    //      mod/wiki:managewiki capability
                    // and
                    //      mod/wiki:editpage capability
                    $manage = has_capability('mod/wiki:managewiki', $context);
                    $edit = has_capability('mod/wiki:editpage', $context);
                    return $manage && $edit;
                }
            } else {
                if ($wiki->wikimode == 'individual') {
                    // Individual Mode:
                    // Each person owns a wiki.
                    //
                    // Only the owner of that wiki can edit it
                    if ($subwiki->userid == $USER->id) {
                        return has_capability('mod/wiki:editpage', $context);
                    } else {
                        // Current user is not the owner of that wiki.
                        // User must have:
                        //      mod/wiki:managewiki capability
                        // and
                        //      mod/wiki:editpage capability
                        $manage = has_capability('mod/wiki:managewiki', $context);
                        $edit = has_capability('mod/wiki:editpage', $context);
                        return $manage && $edit;
                    }
                } else {
                    //Error
                    return false;
                }
            }
        default:
            // Error
            return false;
    }
}
/**
 * @global object
 * @param array $userids
 * @param object $choicegroup Choice main table row
 * @param object $cm Course-module object
 * @param object $course Course object
 * @return bool
 */
function choicegroup_delete_responses($userids, $choicegroup, $cm, $course)
{
    global $CFG, $DB, $context;
    require_once $CFG->libdir . '/completionlib.php';
    if (!is_array($userids) || empty($userids)) {
        return false;
    }
    foreach ($userids as $num => $userid) {
        if (empty($userid)) {
            unset($userids[$num]);
        }
    }
    $completion = new completion_info($course);
    $eventparams = array('context' => $context, 'objectid' => $choicegroup->id);
    foreach ($userids as $userid) {
        if ($current = choicegroup_get_user_answer($choicegroup, $userid)) {
            $currentgroup = $DB->get_record('groups', array('id' => $current->id), 'id,name', MUST_EXIST);
            if (groups_is_member($current->id, $userid)) {
                groups_remove_member($current->id, $userid);
                $event = \mod_choicegroup\event\choice_removed::create($eventparams);
                $event->add_record_snapshot('course_modules', $cm);
                $event->add_record_snapshot('course', $course);
                $event->add_record_snapshot('choicegroup', $choicegroup);
                $event->trigger();
            }
            // Update completion state
            if ($completion->is_enabled($cm) && $choicegroup->completionsubmit) {
                $completion->update_state($cm, COMPLETION_INCOMPLETE, $userid);
            }
        }
    }
    return true;
}