function definition()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     list($instance, $plugin, $course) = $this->_customdata;
     $coursecontext = context_course::instance($course->id);
     $enrol = enrol_get_plugin('cohort');
     $groups = array(0 => get_string('none'));
     foreach (groups_get_all_groups($course->id) as $group) {
         $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
     }
     $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort'));
     $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
     $mform->setType('name', PARAM_TEXT);
     $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no'));
     $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
     if ($instance->id) {
         if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
             $cohorts = array($instance->customint1 => format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid))));
         } else {
             $cohorts = array($instance->customint1 => get_string('error'));
         }
         $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts);
         $mform->setConstant('customint1', $instance->customint1);
         $mform->hardFreeze('customint1', $instance->customint1);
     } else {
         $cohorts = array('' => get_string('choosedots'));
         $allcohorts = cohort_get_available_cohorts($coursecontext, 0, 0, 0);
         foreach ($allcohorts as $c) {
             $cohorts[$c->id] = format_string($c->name);
         }
         $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts);
         $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
     }
     $roles = get_assignable_roles($coursecontext);
     $roles[0] = get_string('none');
     $roles = array_reverse($roles, true);
     // Descending default sortorder.
     $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
     $mform->setDefault('roleid', $enrol->get_config('roleid'));
     if ($instance->id and !isset($roles[$instance->roleid])) {
         if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true);
             $roles[$instance->roleid] = role_get_name($role, $coursecontext);
         } else {
             $roles[$instance->roleid] = get_string('error');
         }
     }
     $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
     $mform->addElement('hidden', 'courseid', null);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     if ($instance->id) {
         $this->add_action_buttons(true);
     } else {
         $this->add_action_buttons(true, get_string('addinstance', 'enrol'));
     }
     $this->set_data($instance);
 }
 public function definition()
 {
     global $COURSE;
     $mform = $this->_form;
     // Adding the "general" fieldset, where all the common settings are showed.
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Adding the standard "name" field.
     $mform->addElement('text', 'name', get_string('name', 'teambuilder'), array('size' => '64'));
     $mform->setType('name', PARAM_TEXT);
     $mform->addRule('name', null, 'required', null, 'client');
     $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
     // Adding the required "intro" field to hold the description of the instance.
     $this->add_intro_editor(false, get_string('intro', 'teambuilder'));
     $mform->addHelpButton('introeditor', 'intro', 'teambuilder');
     // Adding the rest of teambuilder settings, spreeading all them into this fieldset
     // or adding more fieldsets ('header' elements) if needed for better logic.
     $groups = groups_get_all_groups($COURSE->id);
     $options[0] = 'All Students';
     foreach ($groups as $group) {
         $options[$group->id] = $group->name;
     }
     $mform->addElement('select', 'groupid', 'Group', $options);
     $mform->addElement('date_time_selector', 'open', 'Open Date');
     $mform->addElement('static', 'openInfo', '', 'You will not be able to modify your questionnaire after this date.');
     $mform->addElement('date_time_selector', 'close', 'Close Date');
     $mform->addElement('checkbox', 'allowupdate', 'Allow updating of answers');
     // Add standard elements, common to all modules.
     $features = new stdClass();
     $features->groups = false;
     $features->groupings = true;
     $features->groupmembersonly = true;
     $this->standard_coursemodule_elements($features);
     // Add standard buttons, common to all modules.
     $this->add_action_buttons();
 }
 /**
  * Constructor
  *
  * @param \mod_grouptool\output\sortlist $sortlist Sortlist to be used without
  */
 public function __construct(sortlist &$sortlist)
 {
     global $SESSION;
     $this->sortlist = $sortlist;
     $classes = optional_param_array('classes', array(0), \PARAM_INT);
     $action = optional_param('class_action', 0, \PARAM_ALPHA);
     $gobutton = optional_param('do_class_action', 0, \PARAM_BOOL);
     if (!empty($gobutton) && $classes != null && count($classes) != 0 && !empty($action)) {
         $keys = array();
         $groups = array();
         foreach ($classes as $groupingid) {
             $groups = array_merge($groups, groups_get_all_groups($this->sortlist->cm->course, 0, $groupingid));
         }
         foreach ($groups as $current) {
             switch ($action) {
                 case 'select':
                     $this->sortlist->selected[$current->id] = 1;
                     break;
                 case 'deselect':
                     $this->sortlist->selected[$current->id] = 0;
                     break;
                 case 'toggle':
                     $next = empty($this->sortlist->selected[$current->id]) ? 1 : 0;
                     $this->sortlist->selected[$current->id] = $next;
                     break;
             }
         }
         // Update SESSION!
         $SESSION->sortlist->selected = $this->sortlist->selected;
     }
 }
Esempio n. 4
0
 private function _getAllCourseGroups($courseId)
 {
     global $CFG;
     require_once $CFG->libdir . '/grouplib.php';
     return groups_get_all_groups($courseId);
     /* lib/grouplib.php */
 }
 public function destination_courses_selector(moodle_url $nextstageurl, destination_courses_search $courses = null, $courseid)
 {
     $html = html_writer::start_tag('div', array('class' => 'import-course-selector backup-restore'));
     $html .= html_writer::start_tag('form', array('method' => 'post', 'action' => $nextstageurl->out_omit_querystring()));
     foreach ($nextstageurl->params() as $key => $value) {
         $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $key, 'value' => $value));
     }
     $html .= html_writer::start_tag('div', array('class' => 'ics-existing-group backup-section'));
     $html .= $this->output->heading(get_string('selectgroups', 'local_syncgroups'), 2, array('class' => 'header'));
     $html .= html_writer::start_tag('ul');
     $groups = groups_get_all_groups($courseid, 0, 0, 'g.id, g.name');
     foreach ($groups as $group) {
         $html .= html_writer::start_tag('li') . html_writer::checkbox('groups[]', $group->id, false, $group->name) . html_writer::end_tag('li');
     }
     $html .= html_writer::end_tag('ul');
     $html .= html_writer::end_tag('div');
     // We only allow import adding for now. Enforce it here.
     $html .= html_writer::start_tag('div', array('class' => 'ics-existing-course backup-section'));
     $html .= $this->output->heading(get_string('syncgroupsto', 'local_syncgroups'), 2, array('class' => 'header'));
     $html .= $this->backup_detail_pair(get_string('selectacourse', 'backup'), $this->render($courses));
     $html .= $this->backup_detail_pair('', html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('continue'))));
     $html .= html_writer::end_tag('div');
     $html .= html_writer::end_tag('form');
     $html .= html_writer::end_tag('div');
     return $html;
 }
function report_roster_get_group_options($id)
{
    $groupsfromdb = groups_get_all_groups($id);
    $groups = array();
    foreach ($groupsfromdb as $key => $value) {
        $groups[$key] = $value->name;
    }
    return $groups;
}
Esempio n. 7
0
 /**
  * Gets all groups for the given course.
  *
  * @param int $courseid Course id
  * @return array Array of all the group objects
  */
 protected function get_all_groups($courseid)
 {
     global $CFG;
     require_once $CFG->libdir . '/grouplib.php';
     if ($courseid != $this->allgroupscourseid) {
         $this->allgroups = groups_get_all_groups($courseid, 0, 0, 'g.id, g.name');
         $this->allgroupscourseid = $courseid;
     }
     return $this->allgroups;
 }
 /**
  * get all group members of $USER (of all groups $USER belongs to)
  * 
  * @param int $courseid
  * @return array: all members of all groups $USER belongs to
  */
 public static function booking_get_groupmembers($courseid)
 {
     global $USER, $DB;
     $groupmembers = array();
     $usergroups = groups_get_all_groups($courseid, $USER->id);
     if (!empty($usergroups)) {
         $groupsparam = implode(',', array_keys($usergroups));
         $groupmembers = $DB->get_records_sql("SELECT u.id\n                    FROM {user} u, {groups_members} gm\n                    WHERE u.id = gm.userid AND gm.groupid IN (?)\n                    ORDER BY lastname ASC", array($groupsparam));
     }
     return $groupmembers;
 }
 public function __construct($recordorid, $options = array())
 {
     global $USER;
     parent::__construct($recordorid, $options);
     $this->cm = get_coursemodule_from_instance('mediagallery', $this->record->id);
     if (!empty($this->cm)) {
         $this->context = \context_module::instance($this->cm->id);
         $this->options['currentgroup'] = groups_get_activity_group($this->cm, true);
         $this->options['groupmode'] = groups_get_activity_groupmode($this->cm);
         $this->options['groups'] = groups_get_all_groups($this->cm->course, $USER->id, $this->cm->groupingid);
     }
 }
 /**
  *
  *
  * @param int|null $userid
  *
  * @return array An array of group objects keyed by groupid
  */
 public function get_user_groups($userid = null)
 {
     global $USER;
     // assume current user when none specified
     if (empty($userid)) {
         $userid = $USER->id;
     }
     if (!empty($this->rtq->getRTQ()->grouping)) {
         return groups_get_all_groups($this->rtq->getCourse()->id, $userid, $this->rtq->getRTQ()->grouping);
     } else {
         return array();
         // return empty array when there is no grouping
     }
 }
 public function __construct()
 {
     global $DB;
     parent::__construct(get_string('gradedistributionbar', 'gradereport_visual'));
     $this->layout = visualization::LAYOUT_AXIS;
     $this->layoutsettings = null;
     //array('false', 'true');
     $this->nodeshape = visualization::SHAPE_VERTICAL_BAR;
     $this->xaxis = 'grade';
     $this->yaxis = 'students';
     $this->xaxislabelformat = '0\\%';
     //$this->xaxismax = 100 + grade_distribution::RANGE;
     //$this->xaxismin = grade_distribution::RANGE;
     $this->xaxisxoffset = -27;
     $this->xaxislabel = get_string('grade', 'gradereport_visual');
     if ($this->percent) {
         $this->yaxislabelformat = '0\\%';
         $this->yaxislabel = get_string('percentstudents', 'gradereport_visual');
     } else {
         $this->yaxislabel = get_string('numberstudents', 'gradereport_visual');
     }
     $this->title = get_string('gradedistribution:title', 'gradereport_visual');
     $this->capability = 'gradereport/visual:vis:grade_distribution_bar';
     $this->usegroups = true;
     $options = array();
     foreach (groups_get_all_groups(required_param('id')) as $groupkey => $group) {
         $options[$groupkey] = grade_report_visual::truncate($group->name);
     }
     $options[0] = 'All Groups';
     if (isset($DB) && !is_null($DB)) {
         $course = $DB->get_record('course', array('id' => required_param('id')));
     } else {
         $course = get_record('course', 'id', required_param('id'));
     }
     if (!$course) {
         print_error('nocourseid');
     }
     $active = groups_get_course_group($course, true);
     if (!$active) {
         $active = 0;
     }
     $this->selector = new selector('group', $options, $active);
     $this->selectors = array($this->selector);
     $this->colorencoder = new encoder(encoder::ENCODER_COLOR, 'item');
     $this->encoders = array($this->colorencoder);
     $this->itemlegend = new legend($this->colorencoder, array(get_string('coursetotal', 'grades')));
     $this->legends = array($this->itemlegend);
 }
Esempio n. 12
0
 protected function definition()
 {
     global $CFG, $DB;
     $collection = $this->_customdata['collection'];
     $context = $this->_customdata['context'];
     $mform = $this->_form;
     // Text search box.
     $mform->addElement('text', 'search', get_string('search'));
     $mform->setType('search', PARAM_TEXT);
     $options = array(\mod_mediagallery\base::TYPE_ALL => get_string('typeall', 'mediagallery'), \mod_mediagallery\base::TYPE_IMAGE => get_string('typeimage', 'mediagallery'), \mod_mediagallery\base::TYPE_VIDEO => get_string('typevideo', 'mediagallery'), \mod_mediagallery\base::TYPE_AUDIO => get_string('typeaudio', 'mediagallery'));
     $mform->addElement('select', 'type', get_string('mediatype', 'mediagallery'), $options);
     // Role select dropdown includes all roles, but using course-specific
     // names if applied. The reason for not restricting to roles that can
     // be assigned at course level is that upper-level roles display in the
     // enrolments table so it makes sense to let users filter by them.
     $rolenames = role_fix_names(get_profile_roles($context), $context, ROLENAME_ALIAS, true);
     if (!empty($CFG->showenrolledusersrolesonly)) {
         $rolenames = role_fix_names(get_roles_used_in_context($context));
     }
     $mform->addElement('select', 'role', get_string('role'), array(0 => get_string('all')) + $rolenames);
     // Filter by group.
     $allgroups = groups_get_all_groups($collection->course);
     $groupsmenu[0] = get_string('allparticipants');
     foreach ($allgroups as $gid => $unused) {
         $groupsmenu[$gid] = $allgroups[$gid]->name;
     }
     if (count($groupsmenu) > 1) {
         $mform->addElement('select', 'group', get_string('group'), $groupsmenu);
     }
     // Submit button does not use add_action_buttons because that adds
     // another fieldset which causes the CSS style to break in an unfixable
     // way due to fieldset quirks.
     $group = array();
     $group[] = $mform->createElement('submit', 'submitbutton', get_string('filter'));
     $group[] = $mform->createElement('submit', 'resetbutton', get_string('reset'));
     $group[] = $mform->createElement('submit', 'exportbutton', get_string('exportascsv', 'mediagallery'));
     $mform->addGroup($group, 'buttons', '', ' ', false);
     $mform->addElement('hidden', 'id', $context->instanceid);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'action', 'search');
     $mform->setType('action', PARAM_ALPHA);
 }
/**
 * Get all FN Site Groups. If a course is specified, and the course is using the FN Site
 * Groups enrolment plug-in, then return the groups currently in use in the course.
 *
 * @param int    $courseid   The id of the requested course
 * @param int    $userid     The id of the requested user or all.
 * @param int    $groupingid The id of the requested grouping or all.
 * @param string $fields     The fields to return or all.
 * @return array
 */
function fn_sg_get_all_groups($courseid = SITEID, $userid = 0, $groupingid = 0, $fields = 'g.*')
{
    global $CFG;
    if (!($course = get_record('course', 'id', $courseid, null, null, null, null, 'id,enrol'))) {
        return false;
    }
    if ($courseid != SITEID && fn_sg_course_uses_sgenrol($course)) {
        /// Get site groups used in course.
        $agroups = false;
    } else {
        $agroups = groups_get_all_groups(SITEID, $userid, $groupingid, $fields);
    }
    if (!is_array($agroups)) {
        $agroups = array();
    }
    if (!($groupings = groups_get_all_groupings(SITEID))) {
        $groupings = array();
    }
    $groups = array();
    foreach ($groupings as $groupingid => $grouping) {
        $groups['g_' . $groupingid] = $grouping;
        if ($ggroups = groups_get_all_groups(SITEID, $userid, $groupingid, $fields)) {
            foreach ($ggroups as $ggroupid => $ggroup) {
                $ggroup->name = ' - ' . $ggroup->name;
                $groups[$ggroupid] = $ggroup;
                unset($agroups[$ggroupid]);
            }
        }
    }
    $nogrouping = new Object();
    $nogrouping->id = 0;
    $nogrouping->name = 'NOT IN GROUPING';
    foreach ($agroups as $agroup) {
        $agroup->name = ' - ' . $agroup->name;
    }
    if (!empty($agroups)) {
        $groups = $groups + array('g_0' => $nogrouping) + $agroups;
    }
    return $groups;
}
 public function should_display($discussion)
 {
     // Check the forum isn't shared (this breaks things because we dunno
     // which groups to use)
     if ($discussion->get_forum()->is_shared()) {
         return false;
     }
     // Check the discussion's within time period
     if (!$discussion->has_unread_data()) {
         return false;
     }
     // Check they have actual permission
     $context = $discussion->get_forum()->get_context();
     if (!has_capability('mod/forumng:viewreadinfo', $context) || $discussion->is_deleted()) {
         return false;
     }
     // For group forum, check they have group access
     if ($groupid = $discussion->get_group_id()) {
         // This requires 'write' access i.e. you don't get it just from
         // visible groups
         if (!$discussion->get_forum()->can_access_group($groupid, true)) {
             return false;
         }
     } else {
         // If the forum is NOT grouped, but the course IS, then you must
         // be in a group or have access all groups (because we will only
         // show read data for students in groups you're in)
         $course = $discussion->get_forum()->get_course();
         if ($course->groupmode && !has_capability('moodle/site:accessallgroups', $context)) {
             // Check they are in at least one group
             global $USER;
             $groups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
             if (!$groups || count($groups) == 0) {
                 return false;
             }
         }
     }
     // OK...
     return true;
 }
Esempio n. 15
0
function get_target_group($discussion, $targetforum, $aag = true)
{
    // Work out target group for move.
    $targetgroup = $discussion->get_group_id();
    if ($targetforum->get_group_mode() == 0) {
        // Target forum doesn't have groups.
        $targetgroup = null;
    } else {
        if (!$targetgroup && $aag && $discussion->get_forum()->get_group_mode() != 0) {
            $targetgroup = null;
        } else {
            if ($targetgroup && $targetforum->get_grouping() != $discussion->get_forum()->get_grouping()) {
                // Target forum has groups :( Need to decide a group.
                // Had source group, but grouping has changed.
                // See if old group belongs to new grouping.
                $allowedgroups = groups_get_all_groups($targetforum->get_course_id(), 0, $targetforum->get_grouping(), 'g.id');
                if (count($allowedgroups) == 1) {
                    $targetgroup = key($allowedgroups);
                } else {
                    if (!array_key_exists($targetgroup, $allowedgroups)) {
                        // Old group not in new grouping, so don't know where to put it.
                        $targetgroup = null;
                    }
                }
            } else {
                // Check to see whether a single or multigroup forum.
                $groupids = get_allowed_groupids($targetforum, $aag);
                if (count($groupids) == 1) {
                    $targetgroup = key($groupids);
                } else {
                    if (!array_key_exists($targetgroup, $groupids)) {
                        $targetgroup = null;
                    }
                }
            }
        }
    }
    return $targetgroup;
}
Esempio n. 16
0
 function definition()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     $user = $this->_customdata['user'];
     $course = $this->_customdata['course'];
     $context = context_course::instance($course->id, IGNORE_MISSING);
     $allgroups = $this->_customdata['allgroups'];
     $usergroups = groups_get_all_groups($course->id, $user->id, 0, 'g.id');
     $options = array();
     foreach ($allgroups as $group) {
         if (isset($usergroups[$group->id])) {
             continue;
         }
         $options[$group->id] = $group->name;
     }
     $mform->addElement('header', 'general', fullname($user));
     $mform->addElement('select', 'groupids', get_string('addgroup', 'group'), $options, array('multiple' => 'multiple'));
     $mform->addRule('groupids', null, 'required');
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'user');
     $mform->setType('user', PARAM_INT);
     $mform->addElement('hidden', 'action');
     $mform->setType('action', PARAM_ALPHANUMEXT);
     $mform->addElement('hidden', 'ifilter');
     $mform->setType('ifilter', PARAM_ALPHA);
     $mform->addElement('hidden', 'page');
     $mform->setType('page', PARAM_INT);
     $mform->addElement('hidden', 'perpage');
     $mform->setType('perpage', PARAM_INT);
     $mform->addElement('hidden', 'sort');
     $mform->setType('sort', PARAM_ALPHA);
     $mform->addElement('hidden', 'dir');
     $mform->setType('dir', PARAM_ALPHA);
     $this->add_action_buttons();
     $this->set_data(array('action' => 'addmember', 'user' => $user->id));
 }
Esempio n. 17
0
/**
 * Run synchronization process
 *
 * @param progress_trace $trace
 * @param int|null $courseid or null for all courses
 * @return void
 */
function local_metagroups_sync(progress_trace $trace, $courseid = null)
{
    global $DB;
    if ($courseid !== null) {
        $courseids = array($courseid);
    } else {
        $courseids = local_metagroups_parent_courses();
    }
    foreach (array_unique($courseids) as $courseid) {
        $parent = get_course($courseid);
        // If parent course doesn't use groups, we can skip synchronization.
        if (groups_get_course_groupmode($parent) == NOGROUPS) {
            continue;
        }
        $trace->output($parent->fullname, 1);
        $children = local_metagroups_child_courses($parent->id);
        foreach ($children as $childid) {
            $child = get_course($childid);
            $trace->output($child->fullname, 2);
            $groups = groups_get_all_groups($child->id);
            foreach ($groups as $group) {
                if (!($metagroup = $DB->get_record('groups', array('courseid' => $parent->id, 'idnumber' => $group->id)))) {
                    $metagroup = new stdClass();
                    $metagroup->courseid = $parent->id;
                    $metagroup->idnumber = $group->id;
                    $metagroup->name = $group->name;
                    $metagroup->id = groups_create_group($metagroup, false, false);
                }
                $trace->output($metagroup->name, 3);
                $users = groups_get_members($group->id);
                foreach ($users as $user) {
                    groups_add_member($metagroup->id, $user->id, 'local_metagroups', $group->id);
                }
            }
        }
    }
}
Esempio n. 18
0
         $a->course = $shortname;
         $a->role = $rolecache[$rid]->name;
         $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
     }
 }
 // find group to add to
 if (!empty($user->{'group' . $i})) {
     // make sure user is enrolled into course before adding into groups
     if (!is_enrolled($coursecontext, $user->id)) {
         $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group' . $i}), 'error');
         continue;
     }
     //build group cache
     if (is_null($ccache[$shortname]->groups)) {
         $ccache[$shortname]->groups = array();
         if ($groups = groups_get_all_groups($courseid)) {
             foreach ($groups as $gid => $group) {
                 $ccache[$shortname]->groups[$gid] = new stdClass();
                 $ccache[$shortname]->groups[$gid]->id = $gid;
                 $ccache[$shortname]->groups[$gid]->name = $group->name;
                 if (!is_numeric($group->name)) {
                     // only non-numeric names are supported!!!
                     $ccache[$shortname]->groups[$group->name] = new stdClass();
                     $ccache[$shortname]->groups[$group->name]->id = $gid;
                     $ccache[$shortname]->groups[$group->name]->name = $group->name;
                 }
             }
         }
     }
     // group exists?
     $addgroup = $user->{'group' . $i};
Esempio n. 19
0
 /**
 * Check if the given enrolment key matches a group enrolment key for the given course
 *
 * @param    courseid  the current course id
 * @param    password  the submitted enrolment key
 */
 function check_group_entry($courseid, $password)
 {
     if ($groups = groups_get_all_groups($courseid)) {
         foreach ($groups as $group) {
             if (!empty($group->enrolmentkey) and stripslashes($password) == $group->enrolmentkey) {
                 return $group->id;
             }
         }
     }
     return false;
 }
Esempio n. 20
0
/**
 * Takes a bunch of information to format into an email and send
 * to the specified recipient.
 *
 * @param object $course the course
 * @param object $quiz the quiz
 * @param object $attempt this attempt just finished
 * @param object $context the quiz context
 * @param object $cm the coursemodule for this quiz
 *
 * @return int number of emails sent
 */
function quiz_send_notification_emails($course, $quiz, $attempt, $context, $cm)
{
    global $CFG, $USER;
    // we will count goods and bads for error logging
    $emailresult = array('good' => 0, 'block' => 0, 'fail' => 0);
    // do nothing if required objects not present
    if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
        debugging('quiz_send_notification_emails: Email(s) not sent due to program error.', DEBUG_DEVELOPER);
        return $emailresult['fail'];
    }
    // check for confirmation required
    $sendconfirm = false;
    $notifyexcludeusers = '';
    if (has_capability('mod/quiz:emailconfirmsubmission', $context, NULL, false)) {
        // exclude from notify emails later
        $notifyexcludeusers = $USER->id;
        // send the email
        $sendconfirm = true;
    }
    // check for notifications required
    $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.email, u.emailstop, u.lang, u.timezone, u.mailformat, u.maildisplay';
    $groups = groups_get_all_groups($course->id, $USER->id);
    if (is_array($groups) && count($groups) > 0) {
        $groups = array_keys($groups);
    } else {
        if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
            // If the user is not in a group, and the quiz is set to group mode,
            // then set $gropus to a non-existant id so that only users with
            // 'moodle/site:accessallgroups' get notified.
            $groups = -1;
        } else {
            $groups = '';
        }
    }
    $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission', $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
    // if something to send, then build $a
    if (!empty($userstonotify) or $sendconfirm) {
        $a = new stdClass();
        // course info
        $a->coursename = $course->fullname;
        $a->courseshortname = $course->shortname;
        // quiz info
        $a->quizname = $quiz->name;
        $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id;
        $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' . format_string($quiz->name) . ' report</a>';
        $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
        $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' . format_string($quiz->name) . ' review</a>';
        $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?q=' . $quiz->id;
        $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
        // attempt info
        $a->submissiontime = userdate($attempt->timefinish);
        $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
        // student who sat the quiz info
        $a->studentidnumber = $USER->idnumber;
        $a->studentname = fullname($USER);
        $a->studentusername = $USER->username;
    }
    // send confirmation if required
    if ($sendconfirm) {
        // send the email and update stats
        switch (quiz_send_confirmation($a)) {
            case true:
                $emailresult['good']++;
                break;
            case false:
                $emailresult['fail']++;
                break;
            case 'emailstop':
                $emailresult['block']++;
                break;
        }
    }
    // send notifications if required
    if (!empty($userstonotify)) {
        // loop through recipients and send an email to each and update stats
        foreach ($userstonotify as $recipient) {
            switch (quiz_send_notification($recipient, $a)) {
                case true:
                    $emailresult['good']++;
                    break;
                case false:
                    $emailresult['fail']++;
                    break;
                case 'emailstop':
                    $emailresult['block']++;
                    break;
            }
        }
    }
    // log errors sending emails if any
    if (!empty($emailresult['fail'])) {
        debugging('quiz_send_notification_emails:: ' . $emailresult['fail'] . ' email(s) failed to be sent.', DEBUG_DEVELOPER);
    }
    if (!empty($emailresult['block'])) {
        debugging('quiz_send_notification_emails:: ' . $emailresult['block'] . ' email(s) were blocked by the user.', DEBUG_DEVELOPER);
    }
    // return the number of successfully sent emails
    return $emailresult['good'];
}
Esempio n. 21
0
    echo get_string("choice", "choice") . "\n";
    /// generate the data for the body of the spreadsheet
    $i = 0;
    if ($users) {
        foreach ($users as $option => $userid) {
            $option_text = choice_get_option_text($choice, $option);
            foreach ($userid as $user) {
                echo $user->lastname;
                echo "\t" . $user->firstname;
                $studentid = " ";
                if (!empty($user->idnumber)) {
                    $studentid = $user->idnumber;
                }
                echo "\t" . $studentid . "\t";
                $ug2 = '';
                if ($usergrps = groups_get_all_groups($course->id, $user->id)) {
                    foreach ($usergrps as $ug) {
                        $ug2 = $ug2 . $ug->name;
                    }
                }
                echo $ug2 . "\t";
                if (isset($option_text)) {
                    echo format_string($option_text, true);
                }
                echo "\n";
            }
        }
    }
    exit;
}
// Show those who haven't answered the question.
Esempio n. 22
0
function print_log_selector_form($course, $selecteduser = 0, $selecteddate = 'today', $modname = "", $modid = 0, $modaction = '', $selectedgroup = -1, $showcourses = 0, $showusers = 0, $logformat = 'showashtml')
{
    global $USER, $CFG;
    // first check to see if we can override showcourses and showusers
    $numcourses = count_records_select("course", "", "COUNT(id)");
    if ($numcourses < COURSE_MAX_COURSES_PER_DROPDOWN && !$showcourses) {
        $showcourses = 1;
    }
    $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    /// Setup for group handling.
    if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
        $selectedgroup = get_current_group($course->id);
        $showgroups = false;
    } else {
        if ($course->groupmode) {
            $selectedgroup = $selectedgroup == -1 ? get_current_group($course->id) : $selectedgroup;
            $showgroups = true;
        } else {
            $selectedgroup = 0;
            $showgroups = false;
        }
    }
    // Get all the possible users
    $users = array();
    if ($course->id != SITEID) {
        if ($selectedgroup) {
            // If using a group, only get users in that group.
            $courseusers = get_group_users($selectedgroup, 'u.lastname ASC', '', 'u.id, u.firstname, u.lastname, u.idnumber');
        } else {
            $courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname, u.idnumber');
        }
    } else {
        $courseusers = get_site_users("u.lastaccess DESC", "u.id, u.firstname, u.lastname, u.idnumber");
    }
    if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) {
        $showusers = 1;
    }
    if ($showusers) {
        if ($courseusers) {
            foreach ($courseusers as $courseuser) {
                $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', $context));
            }
        }
        if ($guest = get_guest()) {
            $users[$guest->id] = fullname($guest);
        }
    }
    if (has_capability('moodle/site:viewreports', $sitecontext) && $showcourses) {
        if ($ccc = get_records("course", "", "", "fullname", "id,fullname,category")) {
            foreach ($ccc as $cc) {
                if ($cc->category) {
                    $courses["{$cc->id}"] = format_string($cc->fullname);
                } else {
                    $courses["{$cc->id}"] = format_string($cc->fullname) . ' (Site)';
                }
            }
        }
        asort($courses);
    }
    $activities = array();
    $selectedactivity = "";
    /// Casting $course->modinfo to string prevents one notice when the field is null
    if ($modinfo = unserialize((string) $course->modinfo)) {
        $section = 0;
        if ($course->format == 'weeks') {
            // Bodgy
            $strsection = get_string("week");
        } else {
            $strsection = get_string("topic");
        }
        foreach ($modinfo as $mod) {
            if ($mod->mod == "label") {
                continue;
            }
            if ($mod->section > 0 and $section != $mod->section) {
                $activities["section/{$mod->section}"] = "-------------- {$strsection} {$mod->section} --------------";
            }
            $section = $mod->section;
            $mod->name = strip_tags(format_string(urldecode($mod->name), true));
            if (strlen($mod->name) > 55) {
                $mod->name = substr($mod->name, 0, 50) . "...";
            }
            if (!$mod->visible) {
                $mod->name = "(" . $mod->name . ")";
            }
            $activities["{$mod->cm}"] = $mod->name;
            if ($mod->cm == $modid) {
                $selectedactivity = "{$mod->cm}";
            }
        }
    }
    if (has_capability('moodle/site:viewreports', $sitecontext) && $course->id == SITEID) {
        $activities["site_errors"] = get_string("siteerrors");
        if ($modid === "site_errors") {
            $selectedactivity = "site_errors";
        }
    }
    $strftimedate = get_string("strftimedate");
    $strftimedaydate = get_string("strftimedaydate");
    asort($users);
    // Prepare the list of action options.
    $actions = array('view' => get_string('view'), 'add' => get_string('add'), 'update' => get_string('update'), 'delete' => get_string('delete'), '-view' => get_string('allchanges'));
    // Get all the possible dates
    // Note that we are keeping track of real (GMT) time and user time
    // User time is only used in displays - all calcs and passing is GMT
    $timenow = time();
    // GMT
    // What day is it now for the user, and when is midnight that day (in GMT).
    $timemidnight = $today = usergetmidnight($timenow);
    // Put today up the top of the list
    $dates = array("{$timemidnight}" => get_string("today") . ", " . userdate($timenow, $strftimedate));
    if (!$course->startdate or $course->startdate > $timenow) {
        $course->startdate = $course->timecreated;
    }
    $numdates = 1;
    while ($timemidnight > $course->startdate and $numdates < 365) {
        $timemidnight = $timemidnight - 86400;
        $timenow = $timenow - 86400;
        $dates["{$timemidnight}"] = userdate($timenow, $strftimedaydate);
        $numdates++;
    }
    if ($selecteddate == "today") {
        $selecteddate = $today;
    }
    echo "<form class=\"logselectform\" action=\"{$CFG->wwwroot}/course/report/log/index.php\" method=\"get\">\n";
    echo "<div>\n";
    echo "<input type=\"hidden\" name=\"chooselog\" value=\"1\" />\n";
    echo "<input type=\"hidden\" name=\"showusers\" value=\"{$showusers}\" />\n";
    echo "<input type=\"hidden\" name=\"showcourses\" value=\"{$showcourses}\" />\n";
    if (has_capability('moodle/site:viewreports', $sitecontext) && $showcourses) {
        choose_from_menu($courses, "id", $course->id, "");
    } else {
        //        echo '<input type="hidden" name="id" value="'.$course->id.'" />';
        $courses = array();
        $courses[$course->id] = $course->fullname . ($course->id == SITEID ? ' (' . get_string('site') . ') ' : '');
        choose_from_menu($courses, "id", $course->id, false);
        if (has_capability('moodle/site:viewreports', $sitecontext)) {
            $a = new object();
            $a->url = "{$CFG->wwwroot}/course/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showcourses=1&showusers={$showusers}";
            print_string('logtoomanycourses', 'moodle', $a);
        }
    }
    if ($showgroups) {
        if ($cgroups = groups_get_all_groups($course->id)) {
            foreach ($cgroups as $cgroup) {
                $groups[$cgroup->id] = $cgroup->name;
            }
        } else {
            $groups = array();
        }
        choose_from_menu($groups, "group", $selectedgroup, get_string("allgroups"));
    }
    if ($showusers) {
        choose_from_menu($users, "user", $selecteduser, get_string("allparticipants"));
    } else {
        $users = array();
        if (!empty($selecteduser)) {
            $user = get_record('user', 'id', $selecteduser);
            $users[$selecteduser] = fullname($user);
        } else {
            $users[0] = get_string('allparticipants');
        }
        choose_from_menu($users, 'user', $selecteduser, false);
        $a = new object();
        $a->url = "{$CFG->wwwroot}/course/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showusers=1&showcourses={$showcourses}";
        print_string('logtoomanyusers', 'moodle', $a);
    }
    choose_from_menu($dates, "date", $selecteddate, get_string("alldays"));
    choose_from_menu($activities, "modid", $selectedactivity, get_string("allactivities"), "", "");
    choose_from_menu($actions, 'modaction', $modaction, get_string("allactions"));
    $logformats = array('showashtml' => get_string('displayonpage'), 'downloadascsv' => get_string('downloadtext'), 'downloadasods' => get_string('downloadods'), 'downloadasexcel' => get_string('downloadexcel'));
    choose_from_menu($logformats, 'logformat', $logformat, false);
    echo '<input type="submit" value="' . get_string('gettheselogs') . '" />';
    echo '</div>';
    echo '</form>';
}
Esempio n. 23
0
 function definition()
 {
     global $CFG, $COURSE, $USER;
     $mform =& $this->_form;
     $context = context_course::instance($COURSE->id);
     $modinfo = get_fast_modinfo($COURSE);
     $sections = get_all_sections($COURSE->id);
     $mform->addElement('header', 'filters', get_string('managefilters'));
     //TODO: add better string
     $groupoptions = array();
     if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
         // limited group access
         $groups = groups_get_user_groups($COURSE->id);
         $allgroups = groups_get_all_groups($COURSE->id);
         if (!empty($groups[$COURSE->defaultgroupingid])) {
             foreach ($groups[$COURSE->defaultgroupingid] as $groupid) {
                 $groupoptions[$groupid] = format_string($allgroups[$groupid]->name, true, array('context' => $context));
             }
         }
     } else {
         $groupoptions = array('0' => get_string('allgroups'));
         if (has_capability('moodle/site:accessallgroups', $context)) {
             // user can see all groups
             $allgroups = groups_get_all_groups($COURSE->id);
         } else {
             // user can see course level groups
             $allgroups = groups_get_all_groups($COURSE->id, 0, $COURSE->defaultgroupingid);
         }
         foreach ($allgroups as $group) {
             $groupoptions[$group->id] = format_string($group->name, true, array('context' => $context));
         }
     }
     if ($COURSE->id == SITEID) {
         $viewparticipants = has_capability('moodle/site:viewparticipants', context_system::instance());
     } else {
         $viewparticipants = has_capability('moodle/course:viewparticipants', $context);
     }
     if ($viewparticipants) {
         $viewfullnames = has_capability('moodle/site:viewfullnames', context_course::instance($COURSE->id));
         $options = array();
         $options[0] = get_string('allparticipants');
         $options[$CFG->siteguest] = get_string('guestuser');
         if (isset($groupoptions[0])) {
             // can see all enrolled users
             if ($enrolled = get_enrolled_users($context, null, 0, user_picture::fields('u'))) {
                 foreach ($enrolled as $euser) {
                     $options[$euser->id] = fullname($euser, $viewfullnames);
                 }
             }
         } else {
             // can see users from some groups only
             foreach ($groupoptions as $groupid => $unused) {
                 if ($enrolled = get_enrolled_users($context, null, $groupid, user_picture::fields('u'))) {
                     foreach ($enrolled as $euser) {
                         if (!array_key_exists($euser->id, $options)) {
                             $options[$euser->id] = fullname($euser, $viewfullnames);
                         }
                     }
                 }
             }
         }
         $mform->addElement('select', 'user', get_string('participants'), $options);
         $mform->setAdvanced('user');
     }
     $sectiontitle = get_string('sectionname', 'format_' . $COURSE->format);
     $options = array('' => get_string('allactivities'));
     $modsused = array();
     foreach ($modinfo->cms as $cm) {
         if (!$cm->uservisible) {
             continue;
         }
         $modsused[$cm->modname] = true;
     }
     foreach ($modsused as $modname => $unused) {
         $libfile = "{$CFG->dirroot}/mod/{$modname}/lib.php";
         if (!file_exists($libfile)) {
             unset($modsused[$modname]);
             continue;
         }
         include_once $libfile;
         $libfunction = $modname . "_get_recent_mod_activity";
         if (!function_exists($libfunction)) {
             unset($modsused[$modname]);
             continue;
         }
         $options["mod/{$modname}"] = get_string('allmods', '', get_string('modulenameplural', $modname));
     }
     foreach ($modinfo->sections as $section => $cmids) {
         $options["section/{$section}"] = "-- " . get_section_name($COURSE, $sections[$section]) . " --";
         foreach ($cmids as $cmid) {
             $cm = $modinfo->cms[$cmid];
             if (empty($modsused[$cm->modname]) or !$cm->uservisible) {
                 continue;
             }
             $options[$cm->id] = format_string($cm->name);
         }
     }
     $mform->addElement('select', 'modid', get_string('activities'), $options);
     $mform->setAdvanced('modid');
     if ($groupoptions) {
         $mform->addElement('select', 'group', get_string('groups'), $groupoptions);
         $mform->setAdvanced('group');
     } else {
         // no access to groups in separate mode
         $mform->addElement('hidden', 'group');
         $mform->setType('group', PARAM_INT);
         $mform->setConstants(array('group' => -1));
     }
     $options = array('default' => get_string('bycourseorder'), 'dateasc' => get_string('datemostrecentlast'), 'datedesc' => get_string('datemostrecentfirst'));
     $mform->addElement('select', 'sortby', get_string('sortby'), $options);
     $mform->setAdvanced('sortby');
     $mform->addElement('date_time_selector', 'date', get_string('since'), array('optional' => true));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setType('courseid', PARAM_INT);
     $this->add_action_buttons(false, get_string('showrecent'));
 }
Esempio n. 24
0
 /**
  * Is the current user allowed to review this attempt. This applies when
  * {@link is_own_attempt()} returns false.
  * @return bool whether the review should be allowed.
  */
 public function is_review_allowed()
 {
     if (!$this->has_capability('mod/quiz:viewreports')) {
         return false;
     }
     $cm = $this->get_cm();
     if ($this->has_capability('moodle/site:accessallgroups') || groups_get_activity_groupmode($cm) != SEPARATEGROUPS) {
         return true;
     }
     // Check the users have at least one group in common.
     $teachersgroups = groups_get_activity_allowed_groups($cm);
     $studentsgroups = groups_get_all_groups($cm->course, $this->attempt->userid, $cm->groupingid);
     return $teachersgroups && $studentsgroups && array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
 }
Esempio n. 25
0
/**
 * Returns posts made by the selected user in the requested courses.
 *
 * This method can be used to return all of the posts made by the requested user
 * within the given courses.
 * For each course the access of the current user and requested user is checked
 * and then for each post access to the post and forum is checked as well.
 *
 * This function is safe to use with usercapabilities.
 *
 * @global moodle_database $DB
 * @param stdClass $user The user whose posts we want to get
 * @param array $courses The courses to search
 * @param bool $musthaveaccess If set to true errors will be thrown if the user
 *                             cannot access one or more of the courses to search
 * @param bool $discussionsonly If set to true only discussion starting posts
 *                              will be returned.
 * @param int $limitfrom The offset of records to return
 * @param int $limitnum The number of records to return
 * @return stdClass An object the following properties
 *               ->totalcount: the total number of posts made by the requested user
 *                             that the current user can see.
 *               ->courses: An array of courses the current user can see that the
 *                          requested user has posted in.
 *               ->forums: An array of forums relating to the posts returned in the
 *                         property below.
 *               ->posts: An array containing the posts to show for this request.
 */
function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
    global $DB, $USER, $CFG;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                }

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

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

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

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

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

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

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

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

    return $return;
}
Esempio n. 26
0
function calendar_get_allowed_types(&$allowed)
{
    global $USER, $CFG, $SESSION;
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
    $allowed->groups = false;
    // This may change just below
    $allowed->courses = false;
    // This may change just below
    $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
    if (!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
        $course = get_record('course', 'id', $SESSION->cal_course_referer);
        $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
        if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
            $allowed->courses = array($course->id => 1);
            if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
                $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
            }
        } else {
            if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
                if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
                    $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
                }
            }
        }
    }
}
 /**
  *
  * @uses $CFG
  * @uses $USER
  */
 function display_filemanager_link()
 {
     global $CFG, $USER;
     if (!($course = get_record('course', 'id', $this->instance->pageid))) {
         error("Course ID is incorrect");
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
     $canmanagegroups = has_capability('block/file_manager:canmanagegroups', $coursecontext);
     $this->content->items[] = "<a title=\"" . get_string('msgfilemanager', 'block_file_manager') . "\" href=\"{$CFG->wwwroot}/blocks/file_manager/view.php?id={$this->instance->pageid}&groupid=0\">" . get_string('myfiles', 'block_file_manager') . "</a>";
     $this->content->icons[] = "<img src=\"{$CFG->pixpath}/i/files.gif\" alt=\"\" />";
     // If the user is member of any group of this course, links for each group in which he belongs must be displayed
     $groupmode = groups_get_course_groupmode($course);
     $groupsarray = array();
     switch ($groupmode) {
         case NOGROUPS:
             // Nothing to display
             break;
         case SEPARATEGROUPS:
             if ($canmanagegroups) {
                 // Displays all groups because of super rights
                 $groupsarray = groups_get_all_groups($this->instance->pageid);
             } else {
                 // Display only links for groups in which the user is member
                 $groupsarray = groups_get_all_groups($this->instance->pageid, $USER->id);
             }
             break;
         case VISIBLEGROUPS:
             // Display a link for all groups
             $groupsarray = groups_get_all_groups($this->instance->pageid);
             break;
     }
     // Displays group links if user in a group.
     if (is_array($groupsarray)) {
         foreach ($groupsarray as $groupid => $value) {
             $this->content->items[] = "<a title=\"" . get_string('msgfilemanagergroup', 'block_file_manager') . "\" href=\"{$CFG->wwwroot}/blocks/file_manager/view.php?id={$this->instance->pageid}&groupid={$groupid}\">" . groups_get_group_name($groupid) . "</a>";
             $this->content->icons[] = "<img src=\"{$CFG->pixpath}/i/files.gif\" alt=\"\" />";
         }
     }
 }
Esempio n. 28
0
/**
 * 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;
}
Esempio n. 29
0
$isreviewer = !empty($userassessment);
$editable = ($cansubmit and $ownsubmission);
$ispublished = ($workshop->phase == workshop::PHASE_CLOSED and $submission->published == 1 and has_capability('mod/workshop:viewpublishedsubmissions', $workshop->context));
if (empty($submission->id) and !$workshop->creating_submission_allowed($USER->id)) {
    $editable = false;
}
if ($submission->id and !$workshop->modifying_submission_allowed($USER->id)) {
    $editable = false;
}
if ($canviewall) {
    // check this flag against the group membership yet
    if (groups_get_activity_groupmode($workshop->cm) == SEPARATEGROUPS) {
        // user must have accessallgroups or share at least one group with the submission author
        if (!has_capability('moodle/site:accessallgroups', $workshop->context)) {
            $usersgroups = groups_get_activity_allowed_groups($workshop->cm);
            $authorsgroups = groups_get_all_groups($workshop->course->id, $submission->authorid, $workshop->cm->groupingid, 'g.id');
            $sharedgroups = array_intersect_key($usersgroups, $authorsgroups);
            if (empty($sharedgroups)) {
                $canviewall = false;
            }
        }
    }
}
if ($editable and $workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION and !has_capability('mod/workshop:manageexamples', $workshop->context)) {
    // check that all required examples have been assessed by the user
    $examples = $workshop->get_examples_for_reviewer($USER->id);
    foreach ($examples as $exampleid => $example) {
        if (is_null($example->grade)) {
            $editable = false;
            break;
        }
Esempio n. 30
0
    /**
     * Groups the given users by the group membership
     *
     * This takes the module grouping settings into account. If "Available for group members only"
     * is set, returns only groups withing the course module grouping. Always returns group [0] with
     * all the given users.
     *
     * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
     * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
     */
    public function get_grouped($users) {
        global $DB;
        global $CFG;

        $grouped = array();  // grouped users to be returned
        if (empty($users)) {
            return $grouped;
        }
        if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
            // Available for group members only - the workshop is available only
            // to users assigned to groups within the selected grouping, or to
            // any group if no grouping is selected.
            $groupingid = $this->cm->groupingid;
            // All users that are members of at least one group will be
            // added into a virtual group id 0
            $grouped[0] = array();
        } else {
            $groupingid = 0;
            // there is no need to be member of a group so $grouped[0] will contain
            // all users
            $grouped[0] = $users;
        }
        $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
                            'gm.id,gm.groupid,gm.userid');
        foreach ($gmemberships as $gmembership) {
            if (!isset($grouped[$gmembership->groupid])) {
                $grouped[$gmembership->groupid] = array();
            }
            $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
            $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
        }
        return $grouped;
    }