コード例 #1
1
ファイル: GroupMagic.php プロジェクト: frapersan/group-magic
 private function _getUserCourseGroupings($userId, $courseId)
 {
     global $CFG;
     require_once $CFG->dirroot . '/group/lib.php';
     return groups_get_user_groups($courseId, $userId);
     /* group/lib.php */
 }
コード例 #2
1
function bp_em_group_events_build_sql_conditions($conditions, $args)
{
    if (!empty($args['group']) && is_numeric($args['group'])) {
        $conditions['group'] = "( `group_id`={$args['group']} )";
    } elseif (!empty($args['group']) && $args['group'] == 'my') {
        $groups = groups_get_user_groups(get_current_user_id());
        if (count($groups) > 0) {
            $conditions['group'] = "( `group_id` IN (" . implode(',', $groups['groups']) . ") )";
        }
    }
    //deal with private groups and events
    if (is_user_logged_in()) {
        global $wpdb;
        //find out what private groups they belong to, and don't show private group events not in their memberships
        $group_ids = BP_Groups_Member::get_group_ids(get_current_user_id());
        if ($group_ids['total'] > 0) {
            $conditions['group_privacy'] = "(`event_private`=0 OR (`event_private`=1 AND (`group_id` IS NULL OR `group_id` = 0)) OR (`event_private`=1 AND `group_id` IN (" . implode(',', $group_ids['groups']) . ")))";
        } else {
            //find out what private groups they belong to, and don't show private group events not in their memberships
            $conditions['group_privacy'] = "(`event_private`=0 OR (`event_private`=1 AND (`group_id` IS NULL OR `group_id` = 0)))";
        }
    }
    return $conditions;
}
 public function report_data($visualreport)
 {
     $data = array();
     $data['header'] = array();
     $data['header']['student'] = 'student';
     $data['header']['grade'] = 'grade';
     $data['header']['item'] = 'item';
     $data['header']['group'] = 'group';
     foreach ($visualreport->grades as $itemkey => $itemgrades) {
         foreach ($itemgrades as $studentkey => $studentdata) {
             if ($studentdata != null && $studentdata->finalgrade != null) {
                 foreach (groups_get_user_groups($visualreport->courseid, $studentkey) as $grouping) {
                     if (count($grouping) > 0) {
                         foreach ($grouping as $group) {
                             $data[$studentkey . '-' . $itemkey . '-' . $group]['student'] = $visualreport->users[$studentkey]->firstname . ' ' . $visualreport->users[$studentkey]->lastname;
                             $data[$studentkey . '-' . $itemkey . '-' . $group]['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                             $data[$studentkey . '-' . $itemkey . '-' . $group]['item'] = $visualreport->gtree->items[$itemkey]->get_name();
                             $data[$studentkey . '-' . $itemkey . '-' . $group]['group'] = groups_get_group_name($group);
                         }
                     } else {
                         $data[$studentkey . '-' . $itemkey . '-ng']['student'] = $visualreport->users[$studentkey]->firstname . ' ' . $visualreport->users[$studentkey]->lastname;
                         $data[$studentkey . '-' . $itemkey . '-ng']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                         $data[$studentkey . '-' . $itemkey . '-ng']['item'] = $visualreport->gtree->items[$itemkey]->get_name();
                         $data[$studentkey . '-' . $itemkey . '-ng']['group'] = get_string('nogroup', 'gradereport_visual');
                     }
                 }
             }
         }
     }
     return $data;
 }
 public function report_data($visualreport)
 {
     $data = array();
     $data['header'] = array();
     $data['header']['grade'] = 'grade';
     $data['header']['item'] = 'item';
     $data['header']['group'] = 'group';
     $count = array();
     foreach ($visualreport->grades as $itemkey => $itemgrades) {
         foreach ($itemgrades as $studentkey => $studentdata) {
             if ($studentdata != null && $studentdata->finalgrade != null) {
                 foreach (groups_get_user_groups($visualreport->courseid, $studentkey) as $grouping) {
                     if (count($grouping) > 0) {
                         foreach ($grouping as $group) {
                             if (!isset($data[$itemkey . '-' . $group])) {
                                 $data[$itemkey . '-' . $group] = array();
                                 $data[$itemkey . '-' . $group]['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                                 $data[$itemkey . '-' . $group]['item'] = $visualreport->gtree->items[$itemkey]->get_name();
                                 $data[$itemkey . '-' . $group]['group'] = groups_get_group_name($group);
                                 $count[$itemkey . '-' . $group] = 1;
                             } else {
                                 $data[$itemkey . '-' . $group]['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                                 $count[$itemkey . '-' . $group]++;
                             }
                         }
                     } else {
                         if (!isset($data[$itemkey . '-ng'])) {
                             $data[$itemkey . '-ng'] = array();
                             $data[$itemkey . '-ng']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                             $data[$itemkey . '-ng']['item'] = $visualreport->gtree->items[$itemkey]->get_name();
                             $data[$itemkey . '-ng']['group'] = get_string('nogroup', 'gradereport_visual');
                             $count[$itemkey . '-ng'] = 1;
                         } else {
                             $data[$itemkey . '-ng']['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                             $count[$itemkey . '-ng']++;
                         }
                     }
                     if (!isset($data[$itemkey . '-ag'])) {
                         $data[$itemkey . '-ag'] = array();
                         $data[$itemkey . '-ag']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                         $data[$itemkey . '-ag']['item'] = $visualreport->gtree->items[$itemkey]->get_name();
                         $data[$itemkey . '-ag']['group'] = get_string('allgroups', 'gradereport_visual');
                         $count[$itemkey . '-ag'] = 1;
                     } else {
                         $data[$itemkey . '-ag']['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100);
                         $count[$itemkey . '-ag']++;
                     }
                 }
             }
         }
     }
     foreach ($data as $key => $row) {
         if ($key != 'header') {
             $data[$key]['grade'] /= $count[$key];
         }
     }
     return $data;
 }
コード例 #5
0
ファイル: bp-em-groups.php プロジェクト: hypenotic/slowfood
function bp_em_group_events_build_sql_conditions($conditions, $args)
{
    if (!empty($args['group']) && is_numeric($args['group'])) {
        $conditions['group'] = "( `group_id`={$args['group']} )";
    } elseif ($args['group'] == 'my') {
        $groups = groups_get_user_groups(get_current_user_id());
        if (count($groups) > 0) {
            $conditions['group'] = "( `group_id` IN (" . implode(',', $groups['groups']) . ") )";
        }
    }
    return $conditions;
}
コード例 #6
0
ファイル: lib.php プロジェクト: Jtgadbois/Pedadida
/**
 * Returns the count of records for the provided user and forum and [optionally] group.
 *
 * @global object
 * @global object
 * @global object
 * @param object $cm
 * @param object $course
 * @return int
 */
function forum_tp_count_forum_unread_posts($cm, $course) {
    global $CFG, $USER, $DB;

    static $readcache = array();

    $forumid = $cm->instance;

    if (!isset($readcache[$course->id])) {
        $readcache[$course->id] = array();
        if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
            foreach ($counts as $count) {
                $readcache[$course->id][$count->id] = $count->unread;
            }
        }
    }

    if (empty($readcache[$course->id][$forumid])) {
        // no need to check group mode ;-)
        return 0;
    }

    $groupmode = groups_get_activity_groupmode($cm, $course);

    if ($groupmode != SEPARATEGROUPS) {
        return $readcache[$course->id][$forumid];
    }

    if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
        return $readcache[$course->id][$forumid];
    }

    require_once($CFG->dirroot.'/course/lib.php');

    $modinfo = get_fast_modinfo($course);
    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id, $USER->id);
    }

    $mygroups = $modinfo->groups[$cm->groupingid];

    // add all groups posts
    if (empty($mygroups)) {
        $mygroups = array(-1=>-1);
    } else {
        $mygroups[-1] = -1;
    }

    list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);

    $now = round(time(), -2); // db cache friendliness
    $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
    $params = array($USER->id, $forumid, $cutoffdate);

    if (!empty($CFG->forum_enabletimedposts)) {
        $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
        $params[] = $now;
        $params[] = $now;
    } else {
        $timedsql = "";
    }

    $params = array_merge($params, $groups_params);

    $sql = "SELECT COUNT(p.id)
              FROM {forum_posts} p
                   JOIN {forum_discussions} d ON p.discussion = d.id
                   LEFT JOIN {forum_read} r   ON (r.postid = p.id AND r.userid = ?)
             WHERE d.forum = ?
                   AND p.modified >= ? AND r.id is NULL
                   $timedsql
                   AND d.groupid $groups_sql";

    return $DB->get_field_sql($sql, $params);
}
コード例 #7
0
ファイル: lib.php プロジェクト: numbas/moodle
/**
 * Returns all users who has completed a specified feedback since a given time
 * many thanks to Manolescu Dorel, who contributed these two functions
 *
 * @global object
 * @global object
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @param array $activities Passed by reference
 * @param int $index Passed by reference
 * @param int $timemodified Timestamp
 * @param int $courseid
 * @param int $cmid
 * @param int $userid
 * @param int $groupid
 * @return void
 */
function feedback_get_recent_mod_activity(&$activities, &$index,
                                          $timemodified, $courseid,
                                          $cmid, $userid="", $groupid="") {

    global $CFG, $COURSE, $USER, $DB;

    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id'=>$courseid));
    }

    $modinfo = get_fast_modinfo($course);

    $cm = $modinfo->cms[$cmid];

    $sqlargs = array();

    //TODO: user user_picture::fields;
    $sql = " SELECT fk . * , fc . * , u.firstname, u.lastname, u.email, u.picture, u.email
                                            FROM {feedback_completed} fc
                                                JOIN {feedback} fk ON fk.id = fc.feedback
                                                JOIN {user} u ON u.id = fc.userid ";

    if ($groupid) {
        $sql .= " JOIN {groups_members} gm ON  gm.userid=u.id ";
    }

    $sql .= " WHERE fc.timemodified > ? AND fk.id = ? ";
    $sqlargs[] = $timemodified;
    $sqlargs[] = $cm->instace;

    if ($userid) {
        $sql .= " AND u.id = ? ";
        $sqlargs[] = $userid;
    }

    if ($groupid) {
        $sql .= " AND gm.groupid = ? ";
        $sqlargs[] = $groupid;
    }

    if (!$feedbackitems = $DB->get_records_sql($sql, $sqlargs)) {
        return;
    }

    $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
    $groupmode       = groups_get_activity_groupmode($cm, $course);

    if (is_null($modinfo->groups)) {
        // load all my groups and cache it in modinfo
        $modinfo->groups = groups_get_user_groups($course->id);
    }

    $aname = format_string($cm->name, true);
    foreach ($feedbackitems as $feedbackitem) {
        if ($feedbackitem->userid != $USER->id) {

            if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
                $usersgroups = groups_get_all_groups($course->id,
                                                     $feedbackitem->userid,
                                                     $cm->groupingid);
                if (!is_array($usersgroups)) {
                    continue;
                }
                $usersgroups = array_keys($usersgroups);
                $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
                if (empty($intersect)) {
                    continue;
                }
            }
        }

        $tmpactivity = new stdClass();

        $tmpactivity->type      = 'feedback';
        $tmpactivity->cmid      = $cm->id;
        $tmpactivity->name      = $aname;
        $tmpactivity->sectionnum= $cm->sectionnum;
        $tmpactivity->timestamp = $feedbackitem->timemodified;

        $tmpactivity->content->feedbackid = $feedbackitem->id;
        $tmpactivity->content->feedbackuserid = $feedbackitem->userid;

        //TODO: add all necessary user fields, this is not enough for user_picture
        $tmpactivity->user->userid   = $feedbackitem->userid;
        $tmpactivity->user->fullname = fullname($feedbackitem, $viewfullnames);
        $tmpactivity->user->picture  = $feedbackitem->picture;

        $activities[$index++] = $tmpactivity;
    }

    return;
}
コード例 #8
0
ファイル: lib.php プロジェクト: nuckey/moodle
/**
 * Returns all assignments since a given time in specified forum.
 */
function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
    global $CFG, $COURSE, $USER, $DB;

    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id'=>$courseid));
    }

    $modinfo =& get_fast_modinfo($course);

    $cm = $modinfo->cms[$cmid];

    $params = array();
    if ($userid) {
        $userselect = "AND u.id = :userid";
        $params['userid'] = $userid;
    } else {
        $userselect = "";
    }

    if ($groupid) {
        $groupselect = "AND gm.groupid = :groupid";
        $groupjoin   = "JOIN {groups_members} gm ON  gm.userid=u.id";
        $params['groupid'] = $groupid;
    } else {
        $groupselect = "";
        $groupjoin   = "";
    }

    $params['cminstance'] = $cm->instance;
    $params['timestart'] = $timestart;

    $userfields = user_picture::fields('u', null, 'userid');

    if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,
                                                     $userfields
                                                FROM {assignment_submissions} asb
                                                JOIN {assignment} a      ON a.id = asb.assignment
                                                JOIN {user} u            ON u.id = asb.userid
                                          $groupjoin
                                               WHERE asb.timemodified > :timestart AND a.id = :cminstance
                                                     $userselect $groupselect
                                            ORDER BY asb.timemodified ASC", $params)) {
         return;
    }

    $groupmode       = groups_get_activity_groupmode($cm, $course);
    $cm_context      = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader          = has_capability('moodle/grade:viewall', $cm_context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);

    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
    }

    $show = array();

    foreach($submissions as $submission) {
        if ($submission->userid == $USER->id) {
            $show[] = $submission;
            continue;
        }
        // the act of submitting of assignment may be considered private - only graders will see it if specified
        if (empty($CFG->assignment_showrecentsubmissions)) {
            if (!$grader) {
                continue;
            }
        }

        if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
            if (isguestuser()) {
                // shortcut - guest user does not belong into any group
                continue;
            }

            // this will be slow - show only users that share group with me in this cm
            if (empty($modinfo->groups[$cm->id])) {
                continue;
            }
            $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
            if (is_array($usersgroups)) {
                $usersgroups = array_keys($usersgroups);
                $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
                if (empty($intersect)) {
                    continue;
                }
            }
        }
        $show[] = $submission;
    }

    if (empty($show)) {
        return;
    }

    if ($grader) {
        require_once($CFG->libdir.'/gradelib.php');
        $userids = array();
        foreach ($show as $id=>$submission) {
            $userids[] = $submission->userid;

        }
        $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
    }

    $aname = format_string($cm->name,true);
    foreach ($show as $submission) {
        $tmpactivity = new stdClass();

        $tmpactivity->type         = 'assignment';
        $tmpactivity->cmid         = $cm->id;
        $tmpactivity->name         = $aname;
        $tmpactivity->sectionnum   = $cm->sectionnum;
        $tmpactivity->timestamp    = $submission->timemodified;

        if ($grader) {
            $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
        }

        $userfields = explode(',', user_picture::fields());
        foreach ($userfields as $userfield) {
            if ($userfield == 'id') {
                $tmpactivity->user->{$userfield} = $submission->userid; // aliased in SQL above
            } else {
                $tmpactivity->user->{$userfield} = $submission->{$userfield};
            }
        }
        $tmpactivity->user->fullname = fullname($submission, $viewfullnames);

        $activities[$index++] = $tmpactivity;
    }

    return;
}
コード例 #9
0
ファイル: lib.php プロジェクト: nadavkav/MoodleTAO
/**
 * Returns all assignments since a given time in specified forum.
 */
function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0)
{
    global $CFG, $COURSE, $USER;
    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = get_record('course', 'id', $courseid);
    }
    $modinfo =& get_fast_modinfo($course);
    $cm = $modinfo->cms[$cmid];
    if ($userid) {
        $userselect = "AND u.id = {$userid}";
    } else {
        $userselect = "";
    }
    if ($groupid) {
        $groupselect = "AND gm.groupid = {$groupid}";
        $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON  gm.userid=u.id";
    } else {
        $groupselect = "";
        $groupjoin = "";
    }
    if (!($submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,\n                                                u.firstname, u.lastname, u.email, u.picture\n                                           FROM {$CFG->prefix}assignment_submissions asb\n                                                JOIN {$CFG->prefix}assignment a      ON a.id = asb.assignment\n                                                JOIN {$CFG->prefix}user u            ON u.id = asb.userid\n                                                {$groupjoin}\n                                          WHERE asb.timemodified > {$timestart} AND a.id = {$cm->instance}\n                                                {$userselect} {$groupselect}\n                                       ORDER BY asb.timemodified ASC"))) {
        return;
    }
    $groupmode = groups_get_activity_groupmode($cm, $course);
    $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader = has_capability('moodle/grade:viewall', $cm_context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id);
        // load all my groups and cache it in modinfo
    }
    $show = array();
    foreach ($submissions as $submission) {
        if ($submission->userid == $USER->id) {
            $show[] = $submission;
            continue;
        }
        // the act of submitting of assignment may be considered private - only graders will see it if specified
        if (empty($CFG->assignment_showrecentsubmissions)) {
            if (!$grader) {
                continue;
            }
        }
        if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
            if (isguestuser()) {
                // shortcut - guest user does not belong into any group
                continue;
            }
            // this will be slow - show only users that share group with me in this cm
            if (empty($modinfo->groups[$cm->id])) {
                continue;
            }
            $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
            if (is_array($usersgroups)) {
                $usersgroups = array_keys($usersgroups);
                $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
                if (empty($intersect)) {
                    continue;
                }
            }
        }
        $show[] = $submission;
    }
    if (empty($show)) {
        return;
    }
    if ($grader) {
        require_once $CFG->libdir . '/gradelib.php';
        $userids = array();
        foreach ($show as $id => $submission) {
            $userids[] = $submission->userid;
        }
        $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
    }
    $aname = format_string($cm->name, true);
    foreach ($show as $submission) {
        $tmpactivity = new object();
        $tmpactivity->type = 'assignment';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $aname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $submission->timemodified;
        if ($grader) {
            $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
        }
        $tmpactivity->user->userid = $submission->userid;
        $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
        $tmpactivity->user->picture = $submission->picture;
        $activities[$index++] = $tmpactivity;
    }
    return;
}
コード例 #10
0
ファイル: lib.php プロジェクト: miguelangelUvirtual/uEducon
/**
 * Returns the courses to load events for, the
 *
 * @param array $courseeventsfrom An array of courses to load calendar events for
 * @param bool $ignorefilters specify the use of filters, false is set as default
 * @return array An array of courses, groups, and user to load calendar events for based upon filters
 */
function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false)
{
    global $USER, $CFG, $DB;
    // For backwards compatability we have to check whether the courses array contains
    // just id's in which case we need to load course objects.
    $coursestoload = array();
    foreach ($courseeventsfrom as $id => $something) {
        if (!is_object($something)) {
            $coursestoload[] = $id;
            unset($courseeventsfrom[$id]);
        }
    }
    if (!empty($coursestoload)) {
        // TODO remove this in 2.2
        debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
        $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
    }
    $courses = array();
    $user = false;
    $group = false;
    // capabilities that allow seeing group events from all groups
    // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
    $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
    $isloggedin = isloggedin();
    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
        $courses = array_keys($courseeventsfrom);
    }
    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
        $courses[] = SITEID;
    }
    $courses = array_unique($courses);
    sort($courses);
    if (!empty($courses) && in_array(SITEID, $courses)) {
        // Sort courses for consistent colour highlighting
        // Effectively ignoring SITEID as setting as last course id
        $key = array_search(SITEID, $courses);
        unset($courses[$key]);
        $courses[] = SITEID;
    }
    if ($ignorefilters || $isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER)) {
        $user = $USER->id;
    }
    if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
        if (count($courseeventsfrom) == 1) {
            $course = reset($courseeventsfrom);
            if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
                $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
                $group = array_keys($coursegroups);
            }
        }
        if ($group === false) {
            if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
                $group = true;
            } else {
                if ($isloggedin) {
                    $groupids = array();
                    // We already have the courses to examine in $courses
                    // For each course...
                    foreach ($courseeventsfrom as $courseid => $course) {
                        // If the user is an editing teacher in there,
                        if (!empty($USER->groupmember[$course->id])) {
                            // We've already cached the users groups for this course so we can just use that
                            $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
                        } else {
                            if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
                                // If this course has groups, show events from all of those related to the current user
                                $coursegroups = groups_get_user_groups($course->id, $USER->id);
                                $groupids = array_merge($groupids, $coursegroups['0']);
                            }
                        }
                    }
                    if (!empty($groupids)) {
                        $group = $groupids;
                    }
                }
            }
        }
    }
    if (empty($courses)) {
        $courses = false;
    }
    return array($courses, $group, $user);
}
コード例 #11
0
ファイル: lib.php プロジェクト: kai707/ITSA-backup
 /**
  * Processes the data sent by the form (grades and feedbacks).
  * Caller is reposible for all access control checks
  * @param array $data form submission (with magic quotes)
  * @return array empty array if success, array of warnings if something fails.
  */
 function process_data($data)
 {
     $warnings = array();
     $separategroups = false;
     $mygroups = array();
     if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
         $separategroups = true;
         $mygroups = groups_get_user_groups($this->course->id);
         $mygroups = $mygroups[0];
         // ignore groupings
         // reorder the groups fro better perf bellow
         $current = array_search($this->currentgroup, $mygroups);
         if ($current !== false) {
             unset($mygroups[$current]);
             array_unshift($mygroups, $this->currentgroup);
         }
     }
     // always initialize all arrays
     $queue = array();
     foreach ($data as $varname => $postedvalue) {
         $needsupdate = false;
         // skip, not a grade nor feedback
         if (strpos($varname, 'grade') === 0) {
             $data_type = 'grade';
         } else {
             if (strpos($varname, 'feedback') === 0) {
                 $data_type = 'feedback';
             } else {
                 continue;
             }
         }
         $gradeinfo = explode("_", $varname);
         $userid = clean_param($gradeinfo[1], PARAM_INT);
         $itemid = clean_param($gradeinfo[2], PARAM_INT);
         $oldvalue = $data->{'old' . $varname};
         // was change requested?
         if ($oldvalue == $postedvalue) {
             // string comparison
             continue;
         }
         if (!($grade_item = grade_item::fetch(array('id' => $itemid, 'courseid' => $this->courseid)))) {
             // we must verify course id here!
             error('Incorrect grade item id');
         }
         // Pre-process grade
         if ($data_type == 'grade') {
             $feedback = false;
             $feedbackformat = false;
             if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
                 if ($postedvalue == -1) {
                     // -1 means no grade
                     $finalgrade = null;
                 } else {
                     $finalgrade = $postedvalue;
                 }
             } else {
                 $finalgrade = unformat_float($postedvalue);
             }
             $errorstr = '';
             // Warn if the grade is out of bounds.
             if (is_null($finalgrade)) {
                 // ok
             } else {
                 $bounded = $grade_item->bounded_grade($finalgrade);
                 if ($bounded > $finalgrade) {
                     $errorstr = 'lessthanmin';
                 } else {
                     if ($bounded < $finalgrade) {
                         $errorstr = 'morethanmax';
                     }
                 }
             }
             if ($errorstr) {
                 $user = get_record('user', 'id', $userid, '', '', '', '', 'id, firstname, lastname');
                 $gradestr = new object();
                 $gradestr->username = fullname($user);
                 $gradestr->itemname = $grade_item->get_name();
                 $warnings[] = get_string($errorstr, 'grades', $gradestr);
             }
         } else {
             if ($data_type == 'feedback') {
                 $finalgrade = false;
                 $trimmed = trim($postedvalue);
                 if (empty($trimmed)) {
                     $feedback = NULL;
                 } else {
                     $feedback = stripslashes($postedvalue);
                 }
             }
         }
         // group access control
         if ($separategroups) {
             // note: we can not use $this->currentgroup because it would fail badly
             //       when having two browser windows each with different group
             $sharinggroup = false;
             foreach ($mygroups as $groupid) {
                 if (groups_is_member($groupid, $userid)) {
                     $sharinggroup = true;
                     break;
                 }
             }
             if (!$sharinggroup) {
                 // either group membership changed or somebedy is hacking grades of other group
                 $warnings[] = get_string('errorsavegrade', 'grades');
                 continue;
             }
         }
         $grade_item->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
     }
     return $warnings;
 }
コード例 #12
0
ファイル: locallib.php プロジェクト: EsdrasCaleb/moodle
    /**
     * Returns user override
     *
     * Algorithm:  For each assign setting, if there is a matching user-specific override,
     *   then use that otherwise, if there are group-specific overrides, return the most
     *   lenient combination of them.  If neither applies, leave the assign setting unchanged.
     *
     * @param int $userid The userid.
     * @return override  if exist
     */
    public function override_exists($userid) {
        global $DB;

        // Check for user override.
        $override = $DB->get_record('assign_overrides', array('assignid' => $this->get_instance()->id, 'userid' => $userid));

        if (!$override) {
            $override = new stdClass();
            $override->duedate = null;
            $override->cutoffdate = null;
            $override->allowsubmissionsfromdate = null;
        }

        // Check for group overrides.
        $groupings = groups_get_user_groups($this->get_instance()->course, $userid);

        if (!empty($groupings[0])) {
            // Select all overrides that apply to the User's groups.
            list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
            $sql = "SELECT * FROM {assign_overrides}
                    WHERE groupid $extra AND assignid = ?";
            $params[] = $this->get_instance()->id;
            $records = $DB->get_records_sql($sql, $params);

            // Combine the overrides.
            $duedates = array();
            $cutoffdates = array();
            $allowsubmissionsfromdates = array();

            foreach ($records as $gpoverride) {
                if (isset($gpoverride->duedate)) {
                    $duedates[] = $gpoverride->duedate;
                }
                if (isset($gpoverride->cutoffdate)) {
                    $cutoffdates[] = $gpoverride->cutoffdate;
                }
                if (isset($gpoverride->allowsubmissionsfromdate)) {
                    $allowsubmissionsfromdates[] = $gpoverride->allowsubmissionsfromdate;
                }
            }
            // If there is a user override for a setting, ignore the group override.
            if (is_null($override->allowsubmissionsfromdate) && count($allowsubmissionsfromdates)) {
                $override->allowsubmissionsfromdate = min($allowsubmissionsfromdates);
            }
            if (is_null($override->cutoffdate) && count($cutoffdates)) {
                if (in_array(0, $cutoffdates)) {
                    $override->cutoffdate = 0;
                } else {
                    $override->cutoffdate = max($cutoffdates);
                }
            }
            if (is_null($override->duedate) && count($duedates)) {
                if (in_array(0, $duedates)) {
                    $override->duedate = 0;
                } else {
                    $override->duedate = max($duedates);
                }
            }

        }

        return $override;
    }
コード例 #13
0
    function widget($args, $instance)
    {
        global $bp;
        //only show widget to logged in users
        if (!is_user_logged_in()) {
            return;
        }
        //get the groups the user is part of
        $results = groups_get_user_groups(get_current_user_id());
        //don't show widget if user doesn't have any groups
        if ($results['total'] == 0) {
            return;
        }
        extract($args);
        $title = apply_filters('widget_title', empty($instance['title']) ? sprintf(__('Recent %s from your Groups', 'bp-group-documents'), $this->bp_group_documents_name) : sanitize_text_field($instance['title']));
        echo $before_widget . $before_title . $title . $after_title;
        do_action('bp_group_documents_usergroups_widget_before_html');
        $document_list = BP_Group_Documents::get_list_for_usergroups_widget(absint($instance['num_items']), (bool) $instance['featured']);
        if ($document_list && count($document_list) >= 1) {
            echo '<ul id="bp-group-documents-usergroups" class="bp-group-documents-list">';
            foreach ($document_list as $item) {
                $document = new BP_Group_Documents($item['id']);
                $group = new BP_Groups_Group($document->group_id);
                echo '<li>';
                if (get_option('bp_group_documents_display_icons')) {
                    $document->icon();
                }
                ?>
                                <a class="bp-group-documents-title" id="group-document-link-<?php 
                echo $document->id;
                ?>
"
                                   href="<?php 
                $document->url();
                ?>
" target="_blank">
                        <?php 
                echo $document->name;
                ?>
</a>
                        <?php 
                echo sprintf(__('posted in %s', 'bp-group-documents'), '<a href="' . bp_get_group_permalink($group) . '">' . esc_attr($group->name) . '</a>');
                echo '</li>';
            }
            echo '</ul>';
        } else {
            echo '<div class="widget-error">' . sprintf(__('There are no %s to display.', 'bp-group-documents'), $this->bp_group_documents_name) . '</div></p>';
        }
        echo $after_widget;
    }
コード例 #14
0
ファイル: group.php プロジェクト: sajjadalisiddiqui/cms
<?php

global $EM_Event;
if (!function_exists('bp_is_active') || !bp_is_active('groups')) {
    return false;
}
$user_groups = array();
$group_data = groups_get_user_groups(get_current_user_id());
if (!is_super_admin()) {
    foreach ($group_data['groups'] as $group_id) {
        if (groups_is_user_admin(get_current_user_id(), $group_id)) {
            $user_groups[] = groups_get_group(array('group_id' => $group_id));
        }
    }
    $group_count = count($user_groups);
} else {
    $groups = groups_get_groups(array('show_hidden' => true, 'per_page' => 0));
    $user_groups = $groups['groups'];
    $group_count = $groups['total'];
}
if (count($user_groups) > 0) {
    ?>
	<p>
	<select name="group_id">
		<option value=""><?php 
    _e('Not a Group Event', 'dbem');
    ?>
</option>
		<?php 
    //in case user isn't a group mod, but can edit other users' events
    if (!empty($EM_Event->group_id) && !in_array($EM_Event->group_id, $group_data['groups'])) {
コード例 #15
0
/**
 * Returns all quiz graded users since a given time for specified quiz
 */
function quiz_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0)
{
    global $CFG, $COURSE, $USER;
    require_once 'locallib.php';
    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = get_record('course', 'id', $courseid);
    }
    $modinfo =& get_fast_modinfo($course);
    $cm = $modinfo->cms[$cmid];
    $quiz = get_record('quiz', 'id', $cm->instance);
    if ($userid) {
        $userselect = "AND u.id = {$userid}";
    } else {
        $userselect = '';
    }
    if ($groupid) {
        $groupselect = "AND gm.groupid = {$groupid}";
        $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON  gm.userid = u.id";
    } else {
        $groupselect = '';
        $groupjoin = '';
    }
    if (!($attempts = get_records_sql("\n              SELECT qa.*,\n                     u.firstname, u.lastname, u.email, u.picture, u.imagealt\n                FROM {$CFG->prefix}quiz_attempts qa\n                     JOIN {$CFG->prefix}user u ON u.id = qa.userid\n                     {$groupjoin}\n               WHERE qa.timefinish > {$timestart}\n                 AND qa.quiz = {$quiz->id}\n                 AND qa.preview = 0\n                     {$userselect}\n                     {$groupselect}\n            ORDER BY qa.timefinish ASC"))) {
        return;
    }
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
    $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
    $grader = has_capability('mod/quiz:viewreports', $context);
    $groupmode = groups_get_activity_groupmode($cm, $course);
    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id);
        // load all my groups and cache it in modinfo
    }
    $hasgrades = $quiz->grade != 0 && $quiz->sumgrades != 0;
    $usersgroups = null;
    $aname = format_string($cm->name, true);
    foreach ($attempts as $attempt) {
        if ($attempt->userid != $USER->id) {
            if (!$grader) {
                // Grade permission required
                continue;
            }
            if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
                if (is_null($usersgroups)) {
                    $usersgroups = groups_get_all_groups($course->id, $attempt->userid, $cm->groupingid);
                    if (is_array($usersgroups)) {
                        $usersgroups = array_keys($usersgroups);
                    } else {
                        $usersgroups = array();
                    }
                }
                if (!array_intersect($usersgroups, $modinfo->groups[$cm->id])) {
                    continue;
                }
            }
        }
        $options = quiz_get_reviewoptions($quiz, $attempt, $context);
        $tmpactivity = new stdClass();
        $tmpactivity->type = 'quiz';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $aname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $attempt->timefinish;
        $tmpactivity->content->attemptid = $attempt->id;
        $tmpactivity->content->attempt = $attempt->attempt;
        if ($hasgrades && $options->scores) {
            $tmpactivity->content->sumgrades = round($attempt->sumgrades, $quiz->decimalpoints);
            $tmpactivity->content->maxgrade = round($quiz->sumgrades, $quiz->decimalpoints);
        } else {
            $tmpactivity->content->sumgrades = null;
            $tmpactivity->content->maxgrade = null;
        }
        $tmpactivity->user->userid = $attempt->userid;
        $tmpactivity->user->fullname = fullname($attempt, $viewfullnames);
        $tmpactivity->user->picture = $attempt->picture;
        $tmpactivity->user->imagealt = $attempt->imagealt;
        $activities[$index++] = $tmpactivity;
    }
    return;
}
コード例 #16
0
ファイル: lib.php プロジェクト: saurabh947/MoodleLearning
/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in wiki activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @global $CFG
 * @global $DB
 * @uses CONTEXT_MODULE
 * @uses VISIBLEGROUPS
 * @param object $course
 * @param bool $viewfullnames capability
 * @param int $timestart
 * @return boolean
 **/
function wiki_print_recent_activity($course, $viewfullnames, $timestart)
{
    global $CFG, $DB, $OUTPUT;
    $sql = "SELECT p.*, w.id as wikiid, sw.groupid\n            FROM {wiki_pages} p\n                JOIN {wiki_subwikis} sw ON sw.id = p.subwikiid\n                JOIN {wiki} w ON w.id = sw.wikiid\n            WHERE p.timemodified > ? AND w.course = ?\n            ORDER BY p.timemodified ASC";
    if (!($pages = $DB->get_records_sql($sql, array($timestart, $course->id)))) {
        return false;
    }
    $modinfo = get_fast_modinfo($course);
    $wikis = array();
    $modinfo = get_fast_modinfo($course);
    foreach ($pages as $page) {
        if (!isset($modinfo->instances['wiki'][$page->wikiid])) {
            // not visible
            continue;
        }
        $cm = $modinfo->instances['wiki'][$page->wikiid];
        if (!$cm->uservisible) {
            continue;
        }
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        if (!has_capability('mod/wiki:viewpage', $context)) {
            continue;
        }
        $groupmode = groups_get_activity_groupmode($cm, $course);
        if ($groupmode) {
            if ($groupmode == SEPARATEGROUPS and !has_capability('mod/wiki:managewiki', $context)) {
                // separate mode
                if (isguestuser()) {
                    // shortcut
                    continue;
                }
                if (is_null($modinfo->groups)) {
                    $modinfo->groups = groups_get_user_groups($course->id);
                    // load all my groups and cache it in modinfo
                }
                if (!in_array($page->groupid, $modinfo->groups[0])) {
                    continue;
                }
            }
        }
        $wikis[] = $page;
    }
    unset($pages);
    if (!$wikis) {
        return false;
    }
    echo $OUTPUT->heading(get_string("updatedwikipages", 'wiki') . ':', 3);
    foreach ($wikis as $wiki) {
        $cm = $modinfo->instances['wiki'][$wiki->wikiid];
        $link = $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $wiki->id;
        print_recent_activity_note($wiki->timemodified, $wiki, $cm->name, $link, false, $viewfullnames);
    }
    return true;
    //  True if anything was printed, otherwise false
}
コード例 #17
0
function organizer_send_message($sender, $receiver, $slot, $type, $digest = null, $customdata = array())
{
    global $DB;
    if ($type == 'register_reminder:student') {
        $organizer = $slot;
    } else {
        $organizer = $DB->get_record('organizer', array('id' => $slot->organizerid));
    }
    $sender = is_int($sender) ? $DB->get_record('user', array('id' => $sender)) : $sender;
    $receiver = is_int($receiver) ? $DB->get_record('user', array('id' => $receiver)) : $receiver;
    $module = $DB->get_record('modules', array('name' => 'organizer'));
    $cm = $DB->get_record('course_modules', array('module' => $module->id, 'instance' => $organizer->id));
    $course = $DB->get_record('course', array('id' => $cm->course));
    $context = context_course::instance($cm->course);
    $roles = get_user_roles($context, $receiver->id);
    $now = time();
    if (!$cm->visible || $cm->availablefrom && $cm->availablefrom > $now || $cm->availableuntil && $cm->availableuntil < $now || count($roles) == 0) {
        return false;
    }
    $namesplit = explode(':', $type);
    $strings = new stdClass();
    $strings->sendername = fullname($sender);
    $strings->receivername = fullname($receiver);
    if ($type != 'register_reminder:student') {
        $strings->date = userdate($slot->starttime, get_string('datetemplate', 'organizer'));
        $strings->time = userdate($slot->starttime, get_string('timetemplate', 'organizer'));
        $strings->location = $slot->location;
    }
    $strings->organizername = $organizer->name;
    $strings->coursefullname = $course->fullname;
    $strings->courseshortname = $course->shortname;
    $strings->courseid = $course->idnumber == "" ? "" : $course->idnumber . ' ';
    if ($namesplit[0] == "edit_notify") {
        $strings->slot_teacher = $slot->teachervisible == 1 ? fullname($DB->get_record('user', array('id' => $slot->teacherid))) : get_string('teacherinvisible', 'organizer');
        $strings->slot_location = organizer_location_link($slot);
        $strings->slot_maxparticipants = $slot->maxparticipants;
        $strings->slot_comments = $slot->comments;
    }
    $courseurl = new moodle_url('/mod/organizer/view.php', array('id' => $cm->id));
    $strings->courselink = html_writer::link($courseurl, $course->fullname);
    if ($organizer->isgrouporganizer) {
        if (strpos($type, 'register_notify') !== false || strpos($type, 'group_registration_notify') !== false) {
            $group = groups_get_user_groups($organizer->course, $sender->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        } else {
            $group = groups_get_user_groups($organizer->course, $receiver->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        }
        $strings->groupname = $group->name;
        $type .= ":group";
    }
    if ($namesplit[0] == "eval_notify_newappointment") {
        $namesplit[0] = "eval_notify";
    }
    $message = new stdClass();
    $message->modulename = 'organizer';
    $message->component = 'mod_organizer';
    $message->name = "{$namesplit['0']}:{$namesplit['1']}";
    $message->notification = 1;
    $message->fullmessageformat = FORMAT_PLAIN;
    $message->userfrom = $sender;
    $message->userto = $receiver;
    if (isset($digest)) {
        $strings->digest = $digest;
        $type .= ":digest";
    }
    $message->subject = get_string("{$type}:subject", 'organizer', $strings);
    $message->message = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessage = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessagehtml = organizer_make_html(get_string("{$type}:fullmessage", 'organizer', $strings), $organizer, $cm, $course);
    if (isset($customdata['custommessage'])) {
        $message->fullmessage = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessage);
        $message->fullmessagehtml = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessagehtml);
    }
    $message->smallmessage = get_string("{$type}:smallmessage", 'organizer', $strings);
    if (ORGANIZER_ENABLE_MESSAGING) {
        return message_send($message);
    } else {
        return false;
    }
}
コード例 #18
0
/**
 * Update workshopplus grades in the gradebook
 *
 * Needed by grade_update_mod_grades() in lib/gradelib.php
 *
 * @category grade
 * @param stdClass $workshopplus instance object with extra cmidnumber and modname property
 * @param int $userid        update grade of specific user only, 0 means all participants
 * @return void
 */
function workshopplus_update_grades(stdclass $workshopplus, $userid = 0)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/gradelib.php';
    $whereuser = $userid ? ' AND authorid = :userid' : '';
    $params = array('workshopplusid' => $workshopplus->id, 'userid' => $userid);
    $sql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded
              FROM {workshopplus_submissions}
             WHERE workshopplusid = :workshopplusid AND example=0' . $whereuser;
    $records = $DB->get_records_sql($sql, $params);
    $submissiongrades = array();
    foreach ($records as $record) {
        $grade = new stdclass();
        $grade->userid = $record->authorid;
        if (!is_null($record->gradeover)) {
            $grade->rawgrade = grade_floatval($workshopplus->grade * $record->gradeover / 100);
            $grade->usermodified = $record->gradeoverby;
        } else {
            $grade->rawgrade = grade_floatval($workshopplus->grade * $record->grade / 100);
        }
        $grade->feedback = $record->feedbackauthor;
        $grade->feedbackformat = $record->feedbackauthorformat;
        $grade->datesubmitted = $record->timemodified;
        $grade->dategraded = $record->timegraded;
        $submissiongrades[$record->authorid] = $grade;
        ////// Find the groupmates and also update their records
        ////////////By Morteza
        /// find the group id of the current user
        $usergroups = groups_get_user_groups($workshopplus->course, $grade->userid);
        $currentgroupid = $usergroups[0][0];
        // Get the current group name from the group id.
        $currentgroupname = groups_get_group_name($currentgroupid);
        // loop over members of that group
        $groupmembers = groups_get_members($currentgroupid, $fields = 'u.*');
        /* Commenting out section for blind copy of grades
            * -- Sayantan - 28.04.2015
           foreach ($groupmembers as $memberid=>$member){                    
               if ($memberid != $grade->userid) {
                   $newgrade = clone $grade;
                   $newgrade->userid = $memberid;
                   $submissiongrades[$memberid] = $newgrade;
               }
           }
           */
        //////////end by Morteza
        /*
         * Begin: Change by Sayantan
         * Date: 28.04.2015
         */
        // Also think of scenario where author belonged to another group - Not possible unless students are
        // allowed to resubmit their solutions - have to think about this one
        // Check if this assignment has been graded previously (entry exists in grade_grades)
        //      no -> this is a new grading, simply copy grade of author to the group members
        //      yes -> this is a regrading
        $params = array('workshopplusid' => $workshopplus->id, 'userid' => $grade->userid);
        $sql = 'SELECT COUNT(1) AS cnt FROM moodle_grade_grades grades ' . 'INNER JOIN moodle_grade_items items ' . 'WHERE items.id = grades.itemid AND items.iteminstance = :workshopplusid AND grades.userid=:userid';
        $records = $DB->get_records_sql($sql, $params);
        $flag_re_grading = 0;
        foreach ($records as $record) {
            if ($record->cnt > 0) {
                // Check if records exist in grade_grades
                $flag_re_grading = 1;
                // If records exist in grade_grades then this is a regrading
            }
        }
        if ($flag_re_grading == 0) {
            // This is a new grading, hence copy grades
            foreach ($groupmembers as $memberid => $member) {
                if ($memberid != $grade->userid) {
                    $newgrade = clone $grade;
                    $newgrade->userid = $memberid;
                    $submissiongrades[$memberid] = $newgrade;
                }
            }
        } else {
            // This is a re grading, hence existing grades should not be overwritten
            //          + Check the time in which each member joined the group
            //          + If the time of joining group is later than time of previous grading then member was in a
            //          separate group when the initial grading was done and should get the grades he/she received
            //          in that group
            //          + If the member has no previous records - assign zero grade since this assignment was not
            //          done by that member (as he was not part of any group when the assignment was first graded)
            //
            foreach ($groupmembers as $memberid => $member) {
                if ($memberid != $grade->userid) {
                    // Check time at which $memberid joined the group
                    $joining_time = 0;
                    $params = array('userid' => $memberid);
                    $sql = 'SELECT timeadded FROM moodle_groups_members WHERE userid=:userid';
                    $records = $DB->get_records_sql($sql, $params);
                    foreach ($records as $record) {
                        $joining_time = $record->timeadded;
                    }
                    // Check time of previous grading
                    $grading_modified_time = 0;
                    $params = array('workshopplusid' => $workshopplus->id, 'userid' => $memberid);
                    $sql = 'SELECT grades.timemodified FROM moodle_grade_grades grades INNER JOIN moodle_grade_items items WHERE items.id = grades.itemid AND items.iteminstance=:workshopplusid AND grades.userid=:userid';
                    $records = $DB->get_records_sql($sql, $params);
                    // If no records are fetched then for the particular group member there exist no records in grades
                    // This means that when the previous grading was done this member was not part of any group
                    // and the grade assigned should be 0
                    if (sizeof($records) == 0) {
                        $newgrade = clone $grade;
                        $newgrade->userid = $memberid;
                        $grade->rawgrade = 0;
                        // Grade assigned to zero since this member was not present when previous grading was done
                        $submissiongrades[$memberid] = $newgrade;
                    } else {
                        foreach ($records as $record) {
                            $grading_modified_time = $record->timemodified;
                        }
                    }
                    // If records exist for the member in grades, and time of joining group is before time of previous grading
                    // then a simple copy of grades from the author's grades is okay
                    if (sizeof($records) < 0 && $grading_modified_time > $joining_time) {
                        $newgrade = clone $grade;
                        // Copy grade since member was in authors group earlier also
                        $newgrade->userid = $memberid;
                        $submissiongrades[$memberid] = $newgrade;
                    }
                    // If record exists for the member in grade but time of joining group is after time of last grading
                    // then we need to restore the previous grade that this member achieved
                    if (sizeof($records) < 0 && $grading_modified_time < $joining_time) {
                        // This member has already received a grade for this assignment
                        // but the member was in another group
                        // hence leave the previous grade untouched
                        // do not add this grade in the array $submissiongrades
                        // Thus in the grades table, the old grade for this member will remain unchanged
                        // Need to recalculate grades from the workshopplus submission of previous group
                        // the member belonged to
                        // Check the group history table
                        // Find a group with max(timeadded) < $grading_modified_time
                        $params = array('grading_modified_time' => $grading_modified_time, 'userid' => $memberid);
                        $sql = 'SELECT groupid FROM moodle_groups_members_history a WHERE userid=:userid AND timeadded=(SELECT MAX(timeadded) FROM moodle_groups_members_history b WHERE a.userid=b.userid AND a.groupid=b.groupid AND b.timeadded<:grading_modified_time)';
                        $records = $DB->get_records_sql($sql, $params);
                        // Find members of this group
                        foreach ($records as $record) {
                            $groupid = $records->groupid;
                        }
                        // loop over members of that group
                        $groupmembers = groups_get_members($groupid, $fields = 'u.*');
                        // Iterate over members to find submission for the given workshopplus id
                        foreach ($groupmembers as $oldmemberid => $oldmember) {
                            // Find submission for this group in workshopplus_submissions
                            $oldparams = array('workshopplusid' => $workshopplus->id, 'userid' => $oldmemberid);
                            $oldsql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded FROM {workshopplus_submissions} WHERE workshopplusid = :workshopplusid AND example=0 AND authorid=:userid ORDER BY timemodified DESC';
                            $oldrecords = $DB->get_records_sql($oldsql, $oldparams);
                            // Break whenever a submission is found for a member
                            if (sizeof($records != 0)) {
                                // Copy grade for this user
                                $oldgrade = new stdclass();
                                $oldgrade->userid = $memberid;
                                if (!is_null($oldrecords->gradeover)) {
                                    $oldgrade->rawgrade = grade_floatval($workshopplus->grade * $oldrecords->gradeover / 100);
                                    $oldgrade->usermodified = $oldrecords->gradeoverby;
                                } else {
                                    $oldgrade->rawgrade = grade_floatval($workshopplus->grade * $oldrecords->grade / 100);
                                }
                                $oldgrade->feedback = $oldrecords->feedbackauthor;
                                $oldgrade->feedbackformat = $oldrecords->feedbackauthorformat;
                                $oldgrade->datesubmitted = $oldrecords->timemodified;
                                $oldgrade->dategraded = $oldrecords->timegraded;
                                $submissiongrades[$memberid] = $oldgrade;
                                break;
                            }
                        }
                    }
                }
            }
        }
        /*
         * End: Change by Sayantan
         * Date: 28.04.2015
         */
    }
    // Updating assessment grades -- only comment added -- no change to code
    $whereuser = $userid ? ' AND userid = :userid' : '';
    $params = array('workshopplusid' => $workshopplus->id, 'userid' => $userid);
    $sql = 'SELECT userid, gradinggrade, timegraded
              FROM {workshopplus_aggregations}
             WHERE workshopplusid = :workshopplusid' . $whereuser;
    $records = $DB->get_records_sql($sql, $params);
    $assessmentgrades = array();
    foreach ($records as $record) {
        $grade = new stdclass();
        $grade->userid = $record->userid;
        $grade->rawgrade = grade_floatval($workshopplus->gradinggrade * $record->gradinggrade / 100);
        $grade->dategraded = $record->timegraded;
        $assessmentgrades[$record->userid] = $grade;
    }
    workshopplus_grade_item_update($workshopplus, $submissiongrades, $assessmentgrades);
}
コード例 #19
0
 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'));
 }
コード例 #20
0
ファイル: modinfolib.php プロジェクト: rwijaya/moodle
 /**
  * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
  * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
  */
 private function get_groups_all() {
     if (is_null($this->groups)) {
         // NOTE: Performance could be improved here. The system caches user groups
         // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
         // structure does not include grouping information. It probably could be changed to
         // do so, without a significant performance hit on login, thus saving this one query
         // each request.
         $this->groups = groups_get_user_groups($this->course->id, $this->userid);
     }
     return $this->groups;
 }
コード例 #21
0
 public function test_course_modinfo_properties()
 {
     global $USER, $DB;
     $this->resetAfterTest();
     $this->setAdminUser();
     // Generate the course and some modules. Make one section hidden.
     $course = $this->getDataGenerator()->create_course(array('format' => 'topics', 'numsections' => 3), array('createsections' => true));
     $DB->execute('UPDATE {course_sections} SET visible = 0 WHERE course = ? and section = ?', array($course->id, 3));
     $coursecontext = context_course::instance($course->id);
     $forum0 = $this->getDataGenerator()->create_module('forum', array('course' => $course->id), array('section' => 0));
     $assign0 = $this->getDataGenerator()->create_module('assign', array('course' => $course->id), array('section' => 0, 'visible' => 0));
     $forum1 = $this->getDataGenerator()->create_module('forum', array('course' => $course->id), array('section' => 1));
     $assign1 = $this->getDataGenerator()->create_module('assign', array('course' => $course->id), array('section' => 1));
     $page1 = $this->getDataGenerator()->create_module('page', array('course' => $course->id), array('section' => 1));
     $page3 = $this->getDataGenerator()->create_module('page', array('course' => $course->id), array('section' => 3));
     $modinfo = get_fast_modinfo($course->id);
     $this->assertEquals(array($forum0->cmid, $assign0->cmid, $forum1->cmid, $assign1->cmid, $page1->cmid, $page3->cmid), array_keys($modinfo->cms));
     $this->assertEquals($course->id, $modinfo->courseid);
     $this->assertEquals($USER->id, $modinfo->userid);
     $this->assertEquals(array(0 => array($forum0->cmid, $assign0->cmid), 1 => array($forum1->cmid, $assign1->cmid, $page1->cmid), 3 => array($page3->cmid)), $modinfo->sections);
     $this->assertEquals(array('forum', 'assign', 'page'), array_keys($modinfo->instances));
     $this->assertEquals(array($assign0->id, $assign1->id), array_keys($modinfo->instances['assign']));
     $this->assertEquals(array($forum0->id, $forum1->id), array_keys($modinfo->instances['forum']));
     $this->assertEquals(array($page1->id, $page3->id), array_keys($modinfo->instances['page']));
     $this->assertEquals(groups_get_user_groups($course->id), $modinfo->groups);
     $this->assertEquals(array(0 => array($forum0->cmid, $assign0->cmid), 1 => array($forum1->cmid, $assign1->cmid, $page1->cmid), 3 => array($page3->cmid)), $modinfo->get_sections());
     $this->assertEquals(array(0, 1, 2, 3), array_keys($modinfo->get_section_info_all()));
     $this->assertEquals($forum0->cmid . ',' . $assign0->cmid, $modinfo->get_section_info(0)->sequence);
     $this->assertEquals($forum1->cmid . ',' . $assign1->cmid . ',' . $page1->cmid, $modinfo->get_section_info(1)->sequence);
     $this->assertEquals('', $modinfo->get_section_info(2)->sequence);
     $this->assertEquals($page3->cmid, $modinfo->get_section_info(3)->sequence);
     $this->assertEquals($course->id, $modinfo->get_course()->id);
     $this->assertEquals(array('assign', 'forum', 'page'), array_keys($modinfo->get_used_module_names()));
     $this->assertEquals(array('assign', 'forum', 'page'), array_keys($modinfo->get_used_module_names(true)));
     // Admin can see hidden modules/sections.
     $this->assertTrue($modinfo->cms[$assign0->cmid]->uservisible);
     $this->assertTrue($modinfo->get_section_info(3)->uservisible);
     // Get modinfo for non-current user (without capability to view hidden activities/sections).
     $user = $this->getDataGenerator()->create_user();
     $modinfo = get_fast_modinfo($course->id, $user->id);
     $this->assertEquals($user->id, $modinfo->userid);
     $this->assertFalse($modinfo->cms[$assign0->cmid]->uservisible);
     $this->assertFalse($modinfo->get_section_info(3)->uservisible);
     // Attempt to access and set non-existing field.
     $this->assertTrue(empty($modinfo->somefield));
     $this->assertFalse(isset($modinfo->somefield));
     $modinfo->somefield;
     $this->assertDebuggingCalled();
     $modinfo->somefield = 'Some value';
     $this->assertDebuggingCalled();
     $this->assertEmpty($modinfo->somefield);
     $this->assertDebuggingCalled();
     // Attempt to overwrite existing field.
     $this->assertFalse(empty($modinfo->cms));
     $this->assertTrue(isset($modinfo->cms));
     $modinfo->cms = 'Illegal overwriting';
     $this->assertDebuggingCalled();
     $this->assertNotEquals('Illegal overwriting', $modinfo->cms);
 }
コード例 #22
0
ファイル: externallib.php プロジェクト: evltuma/moodle
 /**
  * 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;
 }
コード例 #23
0
ファイル: recent.php プロジェクト: nicolasconnault/moodle2.0
        }
    }
}
switch ($course->format) {
    case 'weeks':
        $sectiontitle = get_string('week');
        break;
    case 'topics':
        $sectiontitle = get_string('topic');
        break;
    default:
        $sectiontitle = get_string('section');
        break;
}
if (is_null($modinfo->groups)) {
    $modinfo->groups = groups_get_user_groups($course->id);
    // load all my groups and cache it in modinfo
}
$activities = array();
$index = 0;
foreach ($sections as $section) {
    $activity = new object();
    $activity->type = 'section';
    if ($section->section > 0) {
        $activity->name = $sectiontitle . ' ' . $section->section;
    } else {
        $activity->name = '';
    }
    $activity->visible = $section->visible;
    $activities[$index++] = $activity;
    if (empty($section->sequence)) {
コード例 #24
0
    public function recipientsform($courseid, $userid) {
        global $COURSE, $DB;

        $options = array();

        $owngroups = groups_get_user_groups($courseid, $userid);
        $content = html_writer::start_tag('div', array('id' => 'local_mail_recipients_form', 'class' => 'local_mail_form mail_hidden'));

        if ($COURSE->groupmode == SEPARATEGROUPS and empty($owngroups[0])) {
            return '';
        }
        $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_toolbar'));

        // Roles
        $context = context_course::instance($courseid);
        $roles = role_get_names($context);
        $userroles = local_mail_get_user_roleids($userid, $context);
        $mailsamerole = has_capability('local/mail:mailsamerole', $context);
        foreach ($roles as $key => $role) {
            $count = $DB->count_records_select('role_assignments', "contextid = :contextid AND roleid = :roleid AND userid <> :userid",
                array('contextid' => $context->id, 'roleid' => $role->id, 'userid' => $userid));
            if (($count && $mailsamerole)
                || ($count && !$mailsamerole && !in_array($role->id, $userroles))) {
                $options[$key] = $role->localname;
            }
        }
        $text = get_string('role', 'moodle');
        $content .= html_writer::start_tag('span', array('class' => 'roleselector'));
        $content .= html_writer::label($text, 'local_mail_roles');
        $text = get_string('all', 'local_mail');
        $content .= html_writer::select($options, 'local_mail_roles', '', array('' => $text), array('id' => 'local_mail_recipients_roles', 'class' => ''));
        $content .= html_writer::end_tag('span');
        // Groups
        $groups = groups_get_all_groups($courseid);
        if ($COURSE->groupmode == NOGROUPS or ($COURSE->groupmode == VISIBLEGROUPS and empty($groups))) {
            $content .= html_writer::tag('span', get_string('allparticipants', 'moodle'), array('class' => 'groupselector groupname'));
        } else {
            if ($COURSE->groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) {
                unset($options);
                foreach ($groups as $key => $group) {
                    $options[$key] = $group->name;
                }
                $text = get_string('group', 'moodle');
                $content .= html_writer::start_tag('span', array('class' => 'groupselector'));
                $content .= html_writer::label($text, 'local_mail_recipients_groups');
                $text = get_string('allparticipants', 'moodle');
                $content .= html_writer::select($options, 'local_mail_recipients_groups', '', array('' => $text), array('id' => 'local_mail_recipients_groups', 'class' => ''));
                $content .= html_writer::end_tag('span');
            } else if (count($owngroups[0]) == 1) {// SEPARATEGROUPS and user in only one group
                $text = get_string('group', 'moodle');
                $content .= html_writer::start_tag('span', array('class' => 'groupselector'));
                $content .= html_writer::label("$text: ", null);
                $content .= html_writer::tag('span', groups_get_group_name($owngroups[0][0]), array('class' => 'groupname'));
                $content .= html_writer::end_tag('span');
            } else if (count($owngroups[0]) > 1) {// SEPARATEGROUPS and user in several groups
                unset($options);
                foreach ($owngroups[0] as $key => $group) {
                    $options[$group] = groups_get_group_name($group);
                }
                $text = get_string('group', 'moodle');
                $content .= html_writer::start_tag('span', array('class' => 'groupselector'));
                $content .= html_writer::label($text, 'local_mail_recipients_groups');
                $text = get_string('allparticipants', 'moodle');
                $content .= html_writer::select($options, 'local_mail_recipients_groups', '',
                    array(key($options) => current($options)), array('id' => 'local_mail_recipients_groups', 'class' => ''));
                $content .= html_writer::end_tag('span');
            }
        }
        $content .= html_writer::tag('div', '', array('class' => 'mail_separator'));
        // Search
        $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_search'));
        $attributes = array(
                'type'  => 'text',
                'name'  => 'recipients_search',
                'value' => '',
                'maxlength' => '100',
                'class' => 'mail_search'
        );
        $text = get_string('search', 'local_mail');
        $content .= html_writer::label($text, 'recipients_search');
        $content .= html_writer::empty_tag('input', $attributes);
        // Select all recipients
        $content .= html_writer::start_tag('span', array('class' => 'mail_all_recipients_actions'));
        $attributes = array(
           'type' => 'button',
           'name' => "to_all",
           'value' => get_string('to', 'local_mail')
        );
        $content .= html_writer::empty_tag('input', $attributes);
        $attributes = array(
           'type' => 'button',
           'name' => "cc_all",
           'value' => get_string('cc', 'local_mail')
        );
        $content .= html_writer::empty_tag('input', $attributes);
        $attributes = array(
           'type' => 'button',
           'name' => "bcc_all",
           'value' => get_string('bcc', 'local_mail')
        );
        $content .= html_writer::empty_tag('input', $attributes);
        $attributes = array('type' => 'image',
                                'name' => "remove_all",
                                'src' => $this->output->pix_url('t/delete'),
                                'alt' => get_string('remove'));
        $content .= html_writer::empty_tag('input', $attributes);
        $content .= html_writer::end_tag('span');
        $content .= html_writer::end_tag('div');

        $content .= html_writer::end_tag('div');
        $content .= html_writer::tag('div', '', array('id' => 'local_mail_recipients_list', 'class' => 'mail_form_recipients'));
        $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_loading'));
        $content .= $this->output->pix_icon('i/loading', get_string('actions'), 'moodle', array('class' => 'loading_icon'));
        $content .= html_writer::end_tag('div');
        $content .= html_writer::end_tag('div');
        return $content;
    }
コード例 #25
0
ファイル: navigationlib.php プロジェクト: evltuma/moodle
 /**
  * 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;
 }
コード例 #26
0
/**
 * Returns all game graded users since a given time for specified game
 */
function game_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0)
{
    global $CFG, $COURSE, $USER;
    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = get_record('course', 'id', $courseid);
    }
    $modinfo =& get_fast_modinfo($course);
    $cm = $modinfo->cms[$cmid];
    if ($userid) {
        $userselect = "AND u.id = {$userid}";
    } else {
        $userselect = "";
    }
    if ($groupid) {
        $groupselect = "AND gm.groupid = {$groupid}";
        $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON  gm.userid=u.id";
    } else {
        $groupselect = "";
        $groupjoin = "";
    }
    if (!($attempts = get_records_sql("SELECT qa.*, q.grade,\n                                             u.firstname, u.lastname, u.email, u.picture \n                                        FROM {$CFG->prefix}game_attempts qa\n                                             JOIN {$CFG->prefix}game q ON q.id = qa.gameid\n                                             JOIN {$CFG->prefix}user u ON u.id = qa.userid\n                                             {$groupjoin}\n                                       WHERE qa.timefinish > {$timestart} AND q.id = {$cm->instance}\n                                             {$userselect} {$groupselect}\n                                    ORDER BY qa.timefinish ASC"))) {
        return;
    }
    $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader = has_capability('moodle/grade:viewall', $cm_context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
    //$grader          = has_capability('mod/game:grade', $cm_context);
    $grader = isteacher($courseid, $userid);
    $groupmode = groups_get_activity_groupmode($cm, $course);
    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id);
        // load all my groups and cache it in modinfo
    }
    $aname = format_string($cm->name, true);
    foreach ($attempts as $attempt) {
        if ($attempt->userid != $USER->id) {
            if (!$grader) {
                // grade permission required
                continue;
            }
            if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
                $usersgroups = groups_get_all_groups($course->id, $attempt->userid, $cm->groupingid);
                if (!is_array($usersgroups)) {
                    continue;
                }
                $usersgroups = array_keys($usersgroups);
                $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
                if (empty($intersect)) {
                    continue;
                }
            }
        }
        $tmpactivity = new object();
        $tmpactivity->type = 'game';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $aname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $attempt->timefinish;
        $tmpactivity->content->attemptid = $attempt->id;
        $tmpactivity->content->sumgrades = $attempt->score * $attempt->grade;
        $tmpactivity->content->maxgrade = $attempt->grade;
        $tmpactivity->content->attempt = $attempt->attempt;
        $tmpactivity->user->userid = $attempt->userid;
        $tmpactivity->user->fullname = fullname($attempt, $viewfullnames);
        $tmpactivity->user->picture = $attempt->picture;
        $activities[$index++] = $tmpactivity;
    }
    return;
}
コード例 #27
0
ファイル: lib.php プロジェクト: ajv/Offline-Caching
/**
 * Given a course and a date, prints a summary of all chat rooms past and present
 * This function is called from course/lib.php: print_recent_activity()
 *
 * @global object
 * @global object
 * @global object
 * @param object $course
 * @param array $viewfullnames
 * @param int|string $timestart Timestamp
 * @return bool
 */
function chat_print_recent_activity($course, $viewfullnames, $timestart)
{
    global $CFG, $USER, $DB, $OUTPUT;
    // this is approximate only, but it is really fast ;-)
    $timeout = $CFG->chat_old_ping * 10;
    if (!($mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime\n                                         FROM {course_modules} cm\n                                         JOIN {modules} md        ON md.id = cm.module\n                                         JOIN {chat} ch           ON ch.id = cm.instance\n                                         JOIN {chat_messages} chm ON chm.chatid = ch.id\n                                        WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'\n                                     GROUP BY cm.id\n                                     ORDER BY lasttime ASC", array($timestart, $course->id)))) {
        return false;
    }
    $past = array();
    $current = array();
    $modinfo =& get_fast_modinfo($course);
    // reference needed because we might load the groups
    foreach ($mcms as $cmid => $mcm) {
        if (!array_key_exists($cmid, $modinfo->cms)) {
            continue;
        }
        $cm = $modinfo->cms[$cmid];
        $cm->lasttime = $mcm->lasttime;
        if (!$modinfo->cms[$cm->id]->uservisible) {
            continue;
        }
        if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
            if ($timeout > time() - $cm->lasttime) {
                $current[] = $cm;
            } else {
                $past[] = $cm;
            }
            continue;
        }
        if (is_null($modinfo->groups)) {
            $modinfo->groups = groups_get_user_groups($course->id);
            // load all my groups and cache it in modinfo
        }
        // verify groups in separate mode
        if (!($mygroupids = $modinfo->groups[$cm->groupingid])) {
            continue;
        }
        // ok, last post was not for my group - we have to query db to get last message from one of my groups
        // only minor problem is that the order will not be correct
        $mygroupids = implode(',', $mygroupids);
        $cm->mygroupids = $mygroupids;
        if (!($mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime\n                                           FROM {course_modules} cm\n                                           JOIN {chat} ch           ON ch.id = cm.instance\n                                           JOIN {chat_messages_current} chm ON chm.chatid = ch.id\n                                          WHERE chm.timestamp > ? AND cm.id = ? AND\n                                                (chm.groupid IN ({$mygroupids}) OR chm.groupid = 0)\n                                       GROUP BY cm.id", array($timestart, $cm->id)))) {
            continue;
        }
        $cm->lasttime = $mcm->lasttime;
        if ($timeout > time() - $cm->lasttime) {
            $current[] = $cm;
        } else {
            $past[] = $cm;
        }
    }
    if (!$past and !$current) {
        return false;
    }
    $strftimerecent = get_string('strftimerecent');
    if ($past) {
        echo $OUTPUT->heading(get_string("pastchats", 'chat') . ':');
        foreach ($past as $cm) {
            $link = $CFG->wwwroot . '/mod/chat/view.php?id=' . $cm->id;
            $date = userdate($cm->lasttime, $strftimerecent);
            echo '<div class="head"><div class="date">' . $date . '</div></div>';
            echo '<div class="info"><a href="' . $link . '">' . format_string($cm->name, true) . '</a></div>';
        }
    }
    if ($current) {
        echo $OUTPUT->heading(get_string("currentchats", 'chat') . ':');
        $oldest = floor((time() - $CFG->chat_old_ping) / 10) * 10;
        // better db caching
        $timeold = time() - $CFG->chat_old_ping;
        $timeold = floor($timeold / 10) * 10;
        // better db caching
        $timeoldext = time() - $CFG->chat_old_ping * 10;
        // JSless gui_basic needs much longer timeouts
        $timeoldext = floor($timeoldext / 10) * 10;
        // better db caching
        $params = array('timeold' => $timeold, 'timeoldext' => $timeoldext, 'cmid' => $cm->id);
        $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
        foreach ($current as $cm) {
            //count users first
            if (isset($cm->mygroupids)) {
                $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
            } else {
                $groupselect = "";
            }
            if (!($users = $DB->get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email, u.picture\n                                                  FROM {course_modules} cm\n                                                  JOIN {chat} ch        ON ch.id = cm.instance\n                                                  JOIN {chat_users} chu ON chu.chatid = ch.id\n                                                  JOIN {user} u         ON u.id = chu.userid\n                                                 WHERE cm.id = :cmid {$timeout} {$groupselect}\n                                              GROUP BY u.id, u.firstname, u.lastname, u.email, u.picture", $params))) {
            }
            $link = $CFG->wwwroot . '/mod/chat/view.php?id=' . $cm->id;
            $date = userdate($cm->lasttime, $strftimerecent);
            echo '<div class="head"><div class="date">' . $date . '</div></div>';
            echo '<div class="info"><a href="' . $link . '">' . format_string($cm->name, true) . '</a></div>';
            echo '<div class="userlist">';
            if ($users) {
                echo '<ul>';
                foreach ($users as $user) {
                    echo '<li>' . fullname($user, $viewfullnames) . '</li>';
                }
                echo '</ul>';
            }
            echo '</div>';
        }
    }
    return true;
}
コード例 #28
0
ファイル: lib.php プロジェクト: ncsu-delta/moodle
/**
 * Returns all activity in course workshops since a given time
 *
 * @param array $activities sequentially indexed array of objects
 * @param int $index
 * @param int $timestart
 * @param int $courseid
 * @param int $cmid
 * @param int $userid defaults to 0
 * @param int $groupid defaults to 0
 * @return void adds items into $activities and increases $index
 */
function workshop_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
    global $CFG, $COURSE, $USER, $DB;

    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id'=>$courseid));
    }

    $modinfo = get_fast_modinfo($course);

    $cm = $modinfo->cms[$cmid];

    $params = array();
    if ($userid) {
        $userselect = "AND (author.id = :authorid OR reviewer.id = :reviewerid)";
        $params['authorid'] = $userid;
        $params['reviewerid'] = $userid;
    } else {
        $userselect = "";
    }

    if ($groupid) {
        $groupselect = "AND (authorgroupmembership.groupid = :authorgroupid OR reviewergroupmembership.groupid = :reviewergroupid)";
        $groupjoin   = "LEFT JOIN {groups_members} authorgroupmembership ON authorgroupmembership.userid = author.id
                        LEFT JOIN {groups_members} reviewergroupmembership ON reviewergroupmembership.userid = reviewer.id";
        $params['authorgroupid'] = $groupid;
        $params['reviewergroupid'] = $groupid;
    } else {
        $groupselect = "";
        $groupjoin   = "";
    }

    $params['cminstance'] = $cm->instance;
    $params['submissionmodified'] = $timestart;
    $params['assessmentmodified'] = $timestart;

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
                   author.id AS authorid, author.lastname AS authorlastname, author.firstname AS authorfirstname,
                   author.picture AS authorpicture, author.imagealt AS authorimagealt, author.email AS authoremail,
                   a.id AS assessmentid, a.timemodified AS assessmentmodified,
                   reviewer.id AS reviewerid, reviewer.lastname AS reviewerlastname, reviewer.firstname AS reviewerfirstname,
                   reviewer.picture AS reviewerpicture, reviewer.imagealt AS reviewerimagealt, reviewer.email AS revieweremail
              FROM {workshop_submissions} s
        INNER JOIN {workshop} w ON s.workshopid = w.id
        INNER JOIN {user} author ON s.authorid = author.id
         LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
         LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
        $groupjoin
             WHERE w.id = :cminstance
                   AND s.example = 0
                   $userselect $groupselect
                   AND (s.timemodified > :submissionmodified OR a.timemodified > :assessmentmodified)
          ORDER BY s.timemodified ASC, a.timemodified ASC";

    $rs = $DB->get_recordset_sql($sql, $params);

    $groupmode       = groups_get_activity_groupmode($cm, $course);
    $context         = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader          = has_capability('moodle/grade:viewall', $context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $context);
    $viewauthors     = has_capability('mod/workshop:viewauthornames', $context);
    $viewreviewers   = has_capability('mod/workshop:viewreviewernames', $context);

    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
    }

    $submissions = array(); // recent submissions indexed by submission id
    $assessments = array(); // recent assessments indexed by assessment id
    $users       = array();

    foreach ($rs as $activity) {

        if ($viewfullnames) {
            // remember all user names we can use later
            if (empty($users[$activity->authorid])) {
                $u = new stdclass();
                $u->id = $activity->authorid;
                $u->lastname = $activity->authorlastname;
                $u->firstname = $activity->authorfirstname;
                $u->picture = $activity->authorpicture;
                $u->imagealt = $activity->authorimagealt;
                $u->email = $activity->authoremail;
                $users[$activity->authorid] = $u;
            }
            if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
                $u = new stdclass();
                $u->id = $activity->reviewerid;
                $u->lastname = $activity->reviewerlastname;
                $u->firstname = $activity->reviewerfirstname;
                $u->picture = $activity->reviewerpicture;
                $u->imagealt = $activity->reviewerimagealt;
                $u->email = $activity->revieweremail;
                $users[$activity->reviewerid] = $u;
            }
        }

        if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
            $s = new stdclass();
            $s->id = $activity->submissionid;
            $s->title = $activity->submissiontitle;
            $s->authorid = $activity->authorid;
            $s->timemodified = $activity->submissionmodified;
            if (has_capability('mod/workshop:viewauthornames', $context)) {
                $s->authornamevisible = true;
            } else {
                $s->authornamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($s->authorid === $USER->id) {
                    // own submissions always visible
                    $submissions[$activity->submissionid] = $s;
                    break;
                }

                if (has_capability('mod/workshop:viewallsubmissions', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
                        if (is_array($authorsgroups)) {
                            $authorsgroups = array_keys($authorsgroups);
                            $intersect = array_intersect($authorsgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all submissions and shares a group with the author
                                $submissions[$activity->submissionid] = $s;
                                break;
                            }
                        }

                    } else {
                        // can see all submissions from all groups
                        $submissions[$activity->submissionid] = $s;
                    }
                }
            } while (0);
        }

        if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
            $a = new stdclass();
            $a->id = $activity->assessmentid;
            $a->submissionid = $activity->submissionid;
            $a->submissiontitle = $activity->submissiontitle;
            $a->reviewerid = $activity->reviewerid;
            $a->timemodified = $activity->assessmentmodified;
            if (has_capability('mod/workshop:viewreviewernames', $context)) {
                $a->reviewernamevisible = true;
            } else {
                $a->reviewernamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($a->reviewerid === $USER->id) {
                    // own assessments always visible
                    $assessments[$activity->assessmentid] = $a;
                    break;
                }

                if (has_capability('mod/workshop:viewallassessments', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
                        if (is_array($reviewersgroups)) {
                            $reviewersgroups = array_keys($reviewersgroups);
                            $intersect = array_intersect($reviewersgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all assessments and shares a group with the reviewer
                                $assessments[$activity->assessmentid] = $a;
                                break;
                            }
                        }

                    } else {
                        // can see all assessments from all groups
                        $assessments[$activity->assessmentid] = $a;
                    }
                }
            } while (0);
        }
    }
    $rs->close();

    $workshopname = format_string($cm->name, true);

    if ($grader) {
        require_once($CFG->libdir.'/gradelib.php');
        $grades = grade_get_grades($courseid, 'mod', 'workshop', $cm->instance, array_keys($users));
    }

    foreach ($submissions as $submission) {
        $tmpactivity                = new stdclass();
        $tmpactivity->type          = 'workshop';
        $tmpactivity->cmid          = $cm->id;
        $tmpactivity->name          = $workshopname;
        $tmpactivity->sectionnum    = $cm->sectionnum;
        $tmpactivity->timestamp     = $submission->timemodified;
        $tmpactivity->subtype       = 'submission';
        $tmpactivity->content       = $submission;
        if ($grader) {
            $tmpactivity->grade     = $grades->items[0]->grades[$submission->authorid]->str_long_grade;
        }
        if ($submission->authornamevisible and !empty($users[$submission->authorid])) {
            $tmpactivity->user      = $users[$submission->authorid];
        }
        $activities[$index++]       = $tmpactivity;
    }

    foreach ($assessments as $assessment) {
        $tmpactivity                = new stdclass();
        $tmpactivity->type          = 'workshop';
        $tmpactivity->cmid          = $cm->id;
        $tmpactivity->name          = $workshopname;
        $tmpactivity->sectionnum    = $cm->sectionnum;
        $tmpactivity->timestamp     = $assessment->timemodified;
        $tmpactivity->subtype       = 'assessment';
        $tmpactivity->content       = $assessment;
        if ($grader) {
            $tmpactivity->grade     = $grades->items[1]->grades[$assessment->reviewerid]->str_long_grade;
        }
        if ($assessment->reviewernamevisible and !empty($users[$assessment->reviewerid])) {
            $tmpactivity->user      = $users[$assessment->reviewerid];
        }
        $activities[$index++]       = $tmpactivity;
    }
}
コード例 #29
0
ファイル: recent_form.php プロジェクト: nigeli/moodle
 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'));
 }
コード例 #30
0
ファイル: externallib.php プロジェクト: educacionbe/cursos
 /**
  * Returns a list of forum discussions as well as a summary of the discussion
  * in a provided list of forums.
  *
  * @param array $forumids the forum ids
  * @param int $limitfrom limit from SQL data
  * @param int $limitnum limit number SQL data
  *
  * @return array the forum discussion details
  * @since Moodle 2.5
  */
 public static function get_forum_discussions($forumids, $limitfrom = 0, $limitnum = 0)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . "/mod/forum/lib.php";
     // Validate the parameter.
     $params = self::validate_parameters(self::get_forum_discussions_parameters(), array('forumids' => $forumids, 'limitfrom' => $limitfrom, 'limitnum' => $limitnum));
     $forumids = $params['forumids'];
     $limitfrom = $params['limitfrom'];
     $limitnum = $params['limitnum'];
     // Array to store the forum discussions to return.
     $arrdiscussions = array();
     // Keep track of the users we have looked up in the DB.
     $arrusers = array();
     // Loop through them.
     foreach ($forumids as $id) {
         // Get the forum object.
         $forum = $DB->get_record('forum', array('id' => $id), '*', MUST_EXIST);
         $course = get_course($forum->course);
         $modinfo = get_fast_modinfo($course);
         $forums = $modinfo->get_instances_of('forum');
         $cm = $forums[$forum->id];
         // Get the module context.
         $modcontext = context_module::instance($cm->id);
         // Validate the context.
         self::validate_context($modcontext);
         require_capability('mod/forum:viewdiscussion', $modcontext);
         // Get the discussions for this forum.
         $params = array();
         $groupselect = "";
         $groupmode = groups_get_activity_groupmode($cm, $course);
         if ($groupmode and $groupmode != VISIBLEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
             // Get all the discussions from all the groups this user belongs to.
             $usergroups = groups_get_user_groups($course->id);
             if (!empty($usergroups['0'])) {
                 list($sql, $params) = $DB->get_in_or_equal($usergroups['0']);
                 $groupselect = "AND (groupid {$sql} OR groupid = -1)";
             }
         }
         array_unshift($params, $id);
         $select = "forum = ? {$groupselect}";
         if ($discussions = $DB->get_records_select('forum_discussions', $select, $params, 'timemodified DESC', '*', $limitfrom, $limitnum)) {
             // Check if they can view full names.
             $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
             // Get the unreads array, this takes a forum id and returns data for all discussions.
             $unreads = array();
             if ($cantrack = forum_tp_can_track_forums($forum)) {
                 if ($forumtracked = forum_tp_is_tracked($forum)) {
                     $unreads = forum_get_discussions_unread($cm);
                 }
             }
             // The forum function returns the replies for all the discussions in a given forum.
             $replies = forum_count_discussion_replies($id);
             foreach ($discussions as $discussion) {
                 // This function checks capabilities, timed discussions, groups and qanda forums posting.
                 if (!forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
                     continue;
                 }
                 $usernamefields = user_picture::fields();
                 // If we don't have the users details then perform DB call.
                 if (empty($arrusers[$discussion->userid])) {
                     $arrusers[$discussion->userid] = $DB->get_record('user', array('id' => $discussion->userid), $usernamefields, MUST_EXIST);
                 }
                 // Get the subject.
                 $subject = $DB->get_field('forum_posts', 'subject', array('id' => $discussion->firstpost), MUST_EXIST);
                 // Create object to return.
                 $return = new stdClass();
                 $return->id = (int) $discussion->id;
                 $return->course = $discussion->course;
                 $return->forum = $discussion->forum;
                 $return->name = $discussion->name;
                 $return->userid = $discussion->userid;
                 $return->groupid = $discussion->groupid;
                 $return->assessed = $discussion->assessed;
                 $return->timemodified = (int) $discussion->timemodified;
                 $return->usermodified = $discussion->usermodified;
                 $return->timestart = $discussion->timestart;
                 $return->timeend = $discussion->timeend;
                 $return->firstpost = (int) $discussion->firstpost;
                 $return->firstuserfullname = fullname($arrusers[$discussion->userid], $canviewfullname);
                 $return->firstuserimagealt = $arrusers[$discussion->userid]->imagealt;
                 $return->firstuserpicture = $arrusers[$discussion->userid]->picture;
                 $return->firstuseremail = $arrusers[$discussion->userid]->email;
                 $return->subject = $subject;
                 $return->numunread = '';
                 if ($cantrack && $forumtracked) {
                     if (isset($unreads[$discussion->id])) {
                         $return->numunread = (int) $unreads[$discussion->id];
                     }
                 }
                 // Check if there are any replies to this discussion.
                 if (!empty($replies[$discussion->id])) {
                     $return->numreplies = (int) $replies[$discussion->id]->replies;
                     $return->lastpost = (int) $replies[$discussion->id]->lastpostid;
                 } else {
                     // No replies, so the last post will be the first post.
                     $return->numreplies = 0;
                     $return->lastpost = (int) $discussion->firstpost;
                 }
                 // Get the last post as well as the user who made it.
                 $lastpost = $DB->get_record('forum_posts', array('id' => $return->lastpost), '*', MUST_EXIST);
                 if (empty($arrusers[$lastpost->userid])) {
                     $arrusers[$lastpost->userid] = $DB->get_record('user', array('id' => $lastpost->userid), $usernamefields, MUST_EXIST);
                 }
                 $return->lastuserid = $lastpost->userid;
                 $return->lastuserfullname = fullname($arrusers[$lastpost->userid], $canviewfullname);
                 $return->lastuserimagealt = $arrusers[$lastpost->userid]->imagealt;
                 $return->lastuserpicture = $arrusers[$lastpost->userid]->picture;
                 $return->lastuseremail = $arrusers[$lastpost->userid]->email;
                 // Add the discussion statistics to the array to return.
                 $arrdiscussions[$return->id] = (array) $return;
             }
         }
     }
     return $arrdiscussions;
 }