function definition() { global $CFG, $USER; $mform =& $this->_form; $course = $this->_customdata['course']; $cm = $this->_customdata['cm']; $modcontext = $this->_customdata['modcontext']; $mform->addElement('header', 'general', get_string('export', 'quiz')); $mform->setHelpButton('general', array('export', get_string('export', 'quiz'), 'attforblock')); $groupmode = groups_get_activity_groupmode($cm); $groups = groups_get_activity_allowed_groups($cm, $USER->id); if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) { $grouplist[0] = get_string('allparticipants'); } if ($groups) { foreach ($groups as $group) { $grouplist[$group->id] = $group->name; } } $mform->addElement('select', 'group', get_string('group'), $grouplist); $ident = array(); $ident[] =& MoodleQuickForm::createElement('checkbox', 'id', '', get_string('studentid', 'attforblock')); $ident[] =& MoodleQuickForm::createElement('checkbox', 'uname', '', get_string('username')); $mform->addGroup($ident, 'ident', get_string('identifyby', 'attforblock'), array('<br />'), true); $mform->setDefaults(array('ident[id]' => true, 'ident[uname]' => true)); $mform->addElement('checkbox', 'includenottaken', get_string('includenottaken', 'attforblock'), get_string('yes')); $mform->addElement('date_selector', 'sessionenddate', get_string('endofperiod', 'attforblock')); $mform->disabledIf('sessionenddate', 'includenottaken', 'notchecked'); $mform->addElement('select', 'format', get_string('format'), array('excel' => get_string('downloadexcel', 'attforblock'), 'ooo' => get_string('downloadooo', 'attforblock'), 'text' => get_string('downloadtext', 'attforblock'))); // buttons $submit_string = get_string('ok'); $this->add_action_buttons(false, $submit_string); $mform->addElement('hidden', 'id', $cm->id); // $mform->addElement('hidden', 'action', 'add'); }
/** * Create a scheduler instance from the database. */ protected static function load_from_record($id, stdClass $coursemodule) { $scheduler = new scheduler_instance(); $scheduler->load($id); $scheduler->cm = $coursemodule; $scheduler->groupmode = groups_get_activity_groupmode($coursemodule); return $scheduler; }
/** * Get the current group for the user user looking at the report. * * @param object $cm the course_module information. * @param object $coures the course settings. * @param context $context the quiz context. * @return int the current group id, if applicable. 0 for all users, * NO_GROUPS_ALLOWED if the user cannot see any group. */ public function get_current_group($cm, $course, $context) { $groupmode = groups_get_activity_groupmode($cm, $course); $currentgroup = groups_get_activity_group($cm, true); if ($groupmode == SEPARATEGROUPS && !$currentgroup && !has_capability('moodle/site:accessallgroups', $context)) { $currentgroup = self::NO_GROUPS_ALLOWED; } return $currentgroup; }
/** * Definition of the setting form elements */ public function definition() { $mform = $this->_form; $workshop = $this->_customdata['workshop']; $plugindefaults = get_config('workshopallocation_random'); $mform->addElement('header', 'randomallocationsettings', get_string('allocationsettings', 'workshopallocation_random')); $gmode = groups_get_activity_groupmode($workshop->cm, $workshop->course); switch ($gmode) { case NOGROUPS: $grouplabel = get_string('groupsnone', 'group'); break; case VISIBLEGROUPS: $grouplabel = get_string('groupsvisible', 'group'); break; case SEPARATEGROUPS: $grouplabel = get_string('groupsseparate', 'group'); break; } $mform->addElement('static', 'groupmode', get_string('groupmode', 'group'), $grouplabel); $options_numper = array( workshop_random_allocator_setting::NUMPER_SUBMISSION => get_string('numperauthor', 'workshopallocation_random'), workshop_random_allocator_setting::NUMPER_REVIEWER => get_string('numperreviewer', 'workshopallocation_random') ); $grpnumofreviews = array(); $grpnumofreviews[] = $mform->createElement('select', 'numofreviews', '', workshop_random_allocator::available_numofreviews_list()); $mform->setDefault('numofreviews', $plugindefaults->numofreviews); $grpnumofreviews[] = $mform->createElement('select', 'numper', '', $options_numper); $mform->setDefault('numper', workshop_random_allocator_setting::NUMPER_SUBMISSION); $mform->addGroup($grpnumofreviews, 'grpnumofreviews', get_string('numofreviews', 'workshopallocation_random'), array(' '), false); if (VISIBLEGROUPS == $gmode) { $mform->addElement('checkbox', 'excludesamegroup', get_string('excludesamegroup', 'workshopallocation_random')); $mform->setDefault('excludesamegroup', 0); } else { $mform->addElement('hidden', 'excludesamegroup', 0); } $mform->addElement('checkbox', 'removecurrent', get_string('removecurrentallocations', 'workshopallocation_random')); $mform->setDefault('removecurrent', 0); $mform->addElement('checkbox', 'assesswosubmission', get_string('assesswosubmission', 'workshopallocation_random')); $mform->setDefault('assesswosubmission', 0); if (empty($workshop->useselfassessment)) { $mform->addElement('static', 'addselfassessment', get_string('addselfassessment', 'workshopallocation_random'), get_string('selfassessmentdisabled', 'workshop')); } else { $mform->addElement('checkbox', 'addselfassessment', get_string('addselfassessment', 'workshopallocation_random')); } $this->add_action_buttons(); }
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); } }
/** * Returns a list of teachers by group * for sending email alerts to teachers * * @param stdClass $certificate * @param stdClass $user * @param stdClass $course * @param stdClass $cm * @return array the teacher array */ function certificate_get_teachers($certificate, $user, $course, $cm) { global $USER; $context = context_module::instance($cm->id); $potteachers = get_users_by_capability($context, 'mod/certificate:manage', '', '', '', '', '', '', false, false); if (empty($potteachers)) { return array(); } $teachers = array(); if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS) { // Separate groups are being used if ($groups = groups_get_all_groups($course->id, $user->id)) { // Try to find all groups foreach ($groups as $group) { foreach ($potteachers as $t) { if ($t->id == $user->id) { continue; // do not send self } if (groups_is_member($group->id, $t->id)) { $teachers[$t->id] = $t; } } } } else { // user not in group, try to find teachers without group foreach ($potteachers as $t) { if ($t->id == $USER->id) { continue; // do not send self } if (!groups_get_all_groups($course->id, $t->id)) { //ugly hack $teachers[$t->id] = $t; } } } } else { foreach ($potteachers as $t) { if ($t->id == $USER->id) { continue; // do not send self } $teachers[$t->id] = $t; } } return $teachers; }
function scheduler_migrate_groupmode($sid) { global $DB; $globalenable = (bool) get_config('mod_scheduler', 'groupscheduling'); $cm = get_coursemodule_from_instance('scheduler', $sid, 0, false, IGNORE_MISSING); if ($cm) { if (groups_get_activity_groupmode($cm) > 0 && $globalenable) { $g = $cm->groupingid; } else { $g = -1; } $DB->set_field('scheduler', 'bookingrouping', $g, array('id' => $sid)); $DB->set_field('course_modules', 'groupmode', 0, array('id' => $cm->id)); $DB->set_field('course_modules', 'groupingid', 0, array('id' => $cm->id)); } }
/** * Called to define this moodle form * * @return void */ public function definition() { global $USER; $mform =& $this->_form; $course = $this->_customdata['course']; $cm = $this->_customdata['cm']; $modcontext = $this->_customdata['modcontext']; $mform->addElement('header', 'general', get_string('export', 'attendance')); $groupmode = groups_get_activity_groupmode($cm, $course); $groups = groups_get_activity_allowed_groups($cm, $USER->id); if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) { $grouplist[0] = get_string('allparticipants'); } if ($groups) { foreach ($groups as $group) { $grouplist[$group->id] = $group->name; } } $mform->addElement('select', 'group', get_string('group'), $grouplist); $ident = array(); $ident[] =& $mform->createElement('checkbox', 'id', '', get_string('studentid', 'attendance')); $ident[] =& $mform->createElement('checkbox', 'uname', '', get_string('username')); $optional = array('idnumber', 'institution', 'department'); foreach ($optional as $opt) { $ident[] =& $mform->createElement('checkbox', $opt, '', get_string($opt)); $mform->setType($opt, PARAM_NOTAGS); } $mform->addGroup($ident, 'ident', get_string('identifyby', 'attendance'), array('<br />'), true); $mform->setDefaults(array('ident[id]' => true, 'ident[uname]' => true)); $mform->setType('id', PARAM_INT); $mform->setType('uname', PARAM_INT); $mform->addElement('checkbox', 'includeallsessions', get_string('includeall', 'attendance'), get_string('yes')); $mform->setDefault('includeallsessions', true); $mform->addElement('checkbox', 'includenottaken', get_string('includenottaken', 'attendance'), get_string('yes')); $mform->addElement('checkbox', 'includeremarks', get_string('includeremarks', 'attendance'), get_string('yes')); $mform->addElement('date_selector', 'sessionstartdate', get_string('startofperiod', 'attendance')); $mform->setDefault('sessionstartdate', $course->startdate); $mform->disabledIf('sessionstartdate', 'includeallsessions', 'checked'); $mform->addElement('date_selector', 'sessionenddate', get_string('endofperiod', 'attendance')); $mform->disabledIf('sessionenddate', 'includeallsessions', 'checked'); $mform->addElement('select', 'format', get_string('format'), array('excel' => get_string('downloadexcel', 'attendance'), 'ooo' => get_string('downloadooo', 'attendance'), 'text' => get_string('downloadtext', 'attendance'))); $submit_string = get_string('ok'); $this->add_action_buttons(false, $submit_string); $mform->addElement('hidden', 'id', $cm->id); }
/** * Displays the full report * * @param \stdClass $scorm full SCORM object * @param \stdClass $cm - full course_module object * @param \stdClass $course - full course object * @param string $download - type of download being requested */ public function display($scorm, $cm, $course, $download) { global $DB, $OUTPUT, $PAGE; if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used. groups_print_activity_menu($cm, new \moodle_url($PAGE->url)); } if ($scoes = $DB->get_records('scorm_scoes', array("scorm" => $scorm->id), 'sortorder, id')) { foreach ($scoes as $sco) { if ($sco->launch != '') { $imageurl = new \moodle_url('/mod/scorm/report/graphs/graph.php', array('scoid' => $sco->id)); $graphname = $sco->title; echo $OUTPUT->heading($graphname, 3); echo \html_writer::tag('div', \html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $graphname)), array('class' => 'graph')); } } } }
/** * Log the current user into a chat room in the given chat. * * @param int $chatid the chat instance id * @param int $groupid the user group id * @return array of warnings and the chat unique session id * @since Moodle 3.0 * @throws moodle_exception */ public static function login_user($chatid, $groupid = 0) { global $DB; $params = self::validate_parameters(self::login_user_parameters(), array('chatid' => $chatid, 'groupid' => $groupid)); $warnings = array(); // Request and permission validation. $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST); list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat'); $context = context_module::instance($cm->id); self::validate_context($context); require_capability('mod/chat:chat', $context); if (!empty($params['groupid'])) { $groupid = $params['groupid']; // Determine is the group is visible to user. if (!groups_group_visible($groupid, $course, $cm)) { throw new moodle_exception('notingroup'); } } else { // Check to see if groups are being used here. if ($groupmode = groups_get_activity_groupmode($cm)) { $groupid = groups_get_activity_group($cm); // Determine is the group is visible to user (this is particullary for the group 0). if (!groups_group_visible($groupid, $course, $cm)) { throw new moodle_exception('notingroup'); } } else { $groupid = 0; } } // Get the unique chat session id. // Since we are going to use the chat via Web Service requests we set the ajax version (since it's the most similar). if (!($chatsid = chat_login_user($chat->id, 'ajax', $groupid, $course))) { throw moodle_exception('cantlogin', 'chat'); } $result = array(); $result['chatsid'] = $chatsid; $result['warnings'] = $warnings; return $result; }
public function display($quiz, $cm, $course) { global $CFG, $COURSE, $DB, $OUTPUT; $this->context = get_context_instance(CONTEXT_MODULE, $cm->id); $download = optional_param('download', '', PARAM_ALPHA); list($currentgroup, $students, $groupstudents, $allowed) = $this->load_relevant_students($cm); $pageoptions = array(); $pageoptions['id'] = $cm->id; $pageoptions['mode'] = 'overview'; $reporturl = new moodle_url('/mod/quiz/report.php', $pageoptions); $qmsubselect = quiz_report_qm_filter_select($quiz); $mform = new mod_quiz_report_overview_settings($reporturl, array('qmsubselect' => $qmsubselect, 'quiz' => $quiz, 'currentgroup' => $currentgroup, 'context' => $this->context)); if ($fromform = $mform->get_data()) { $regradeall = false; $regradealldry = false; $regradealldrydo = false; $attemptsmode = $fromform->attemptsmode; if ($qmsubselect) { $qmfilter = $fromform->qmfilter; } else { $qmfilter = 0; } $regradefilter = !empty($fromform->regradefilter); set_user_preference('quiz_report_overview_detailedmarks', $fromform->detailedmarks); set_user_preference('quiz_report_pagesize', $fromform->pagesize); $detailedmarks = $fromform->detailedmarks; $pagesize = $fromform->pagesize; } else { $regradeall = optional_param('regradeall', 0, PARAM_BOOL); $regradealldry = optional_param('regradealldry', 0, PARAM_BOOL); $regradealldrydo = optional_param('regradealldrydo', 0, PARAM_BOOL); $attemptsmode = optional_param('attemptsmode', null, PARAM_INT); if ($qmsubselect) { $qmfilter = optional_param('qmfilter', 0, PARAM_INT); } else { $qmfilter = 0; } $regradefilter = optional_param('regradefilter', 0, PARAM_INT); $detailedmarks = get_user_preferences('quiz_report_overview_detailedmarks', 1); $pagesize = get_user_preferences('quiz_report_pagesize', 0); } $this->validate_common_options($attemptsmode, $pagesize, $course, $currentgroup); $displayoptions = array(); $displayoptions['attemptsmode'] = $attemptsmode; $displayoptions['qmfilter'] = $qmfilter; $displayoptions['regradefilter'] = $regradefilter; $mform->set_data($displayoptions + array('detailedmarks' => $detailedmarks, 'pagesize' => $pagesize)); if (!$this->should_show_grades($quiz)) { $detailedmarks = 0; } // We only want to show the checkbox to delete attempts // if the user has permissions and if the report mode is showing attempts. $candelete = has_capability('mod/quiz:deleteattempts', $this->context) && $attemptsmode != QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO; if ($attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL) { // This option is only available to users who can access all groups in // groups mode, so setting allowed to empty (which means all quiz attempts // are accessible, is not a security porblem. $allowed = array(); } $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext)); $displaycoursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id); $displaycourseshortname = format_string($COURSE->shortname, true, array('context' => $displaycoursecontext)); // Load the required questions. $questions = quiz_report_get_significant_questions($quiz); $table = new quiz_report_overview_table($quiz, $this->context, $qmsubselect, $groupstudents, $students, $detailedmarks, $questions, $candelete, $reporturl, $displayoptions); $filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'), $courseshortname, $quiz->name); $table->is_downloading($download, $filename, $displaycourseshortname . ' ' . format_string($quiz->name, true)); if ($table->is_downloading()) { raise_memory_limit(MEMORY_EXTRA); } // Process actions. if (empty($currentgroup) || $groupstudents) { if (optional_param('delete', 0, PARAM_BOOL) && confirm_sesskey()) { if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) { require_capability('mod/quiz:deleteattempts', $this->context); $this->delete_selected_attempts($quiz, $cm, $attemptids, $allowed); redirect($reporturl->out(false, $displayoptions)); } } else { if (optional_param('regrade', 0, PARAM_BOOL) && confirm_sesskey()) { if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) { require_capability('mod/quiz:regrade', $this->context); $this->regrade_attempts($quiz, false, $groupstudents, $attemptids); redirect($reporturl->out(false, $displayoptions)); } } } } if ($regradeall && confirm_sesskey()) { require_capability('mod/quiz:regrade', $this->context); $this->regrade_attempts($quiz, false, $groupstudents); redirect($reporturl->out(false, $displayoptions), '', 5); } else { if ($regradealldry && confirm_sesskey()) { require_capability('mod/quiz:regrade', $this->context); $this->regrade_attempts($quiz, true, $groupstudents); redirect($reporturl->out(false, $displayoptions), '', 5); } else { if ($regradealldrydo && confirm_sesskey()) { require_capability('mod/quiz:regrade', $this->context); $this->regrade_attempts_needing_it($quiz, $groupstudents); redirect($reporturl->out(false, $displayoptions), '', 5); } } } // Start output. if (!$table->is_downloading()) { // Only print headers if not asked to download data $this->print_header_and_tabs($cm, $course, $quiz, 'overview'); } if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used if (!$table->is_downloading()) { groups_print_activity_menu($cm, $reporturl->out(true, $displayoptions)); } } // Print information on the number of existing attempts if (!$table->is_downloading()) { //do not print notices when downloading if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) { echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>'; } } $hasquestions = quiz_questions_in_quiz($quiz->questions); if (!$table->is_downloading()) { if (!$hasquestions) { echo quiz_no_questions_message($quiz, $cm, $this->context); } else { if (!$students) { echo $OUTPUT->notification(get_string('nostudentsyet')); } else { if ($currentgroup && !$groupstudents) { echo $OUTPUT->notification(get_string('nostudentsingroup')); } } } // Print display options $mform->display(); } $hasstudents = $students && (!$currentgroup || $groupstudents); if ($hasquestions && ($hasstudents || $attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL)) { // Construct the SQL $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid, '; if ($qmsubselect) { $fields .= "(CASE " . " WHEN {$qmsubselect} THEN 1" . " ELSE 0 " . "END) AS gradedattempt, "; } list($fields, $from, $where, $params) = $this->base_sql($quiz, $qmsubselect, $qmfilter, $attemptsmode, $allowed); $table->set_count_sql("SELECT COUNT(1) FROM {$from} WHERE {$where}", $params); // Test to see if there are any regraded attempts to be listed. $fields .= ", COALESCE((\n SELECT MAX(qqr.regraded)\n FROM {quiz_overview_regrades} qqr\n WHERE qqr.questionusageid = quiza.uniqueid\n ), -1) AS regraded"; if ($regradefilter) { $where .= " AND COALESCE((\n SELECT MAX(qqr.regraded)\n FROM {quiz_overview_regrades} qqr\n WHERE qqr.questionusageid = quiza.uniqueid\n ), -1) <> -1"; } $table->set_sql($fields, $from, $where, $params); if (!$table->is_downloading()) { // Regrade buttons if (has_capability('mod/quiz:regrade', $this->context)) { $regradesneeded = $this->count_question_attempts_needing_regrade($quiz, $groupstudents); if ($currentgroup) { $a = new stdClass(); $a->groupname = groups_get_group_name($currentgroup); $a->coursestudents = get_string('participants'); $a->countregradeneeded = $regradesneeded; $regradealldrydolabel = get_string('regradealldrydogroup', 'quiz_overview', $a); $regradealldrylabel = get_string('regradealldrygroup', 'quiz_overview', $a); $regradealllabel = get_string('regradeallgroup', 'quiz_overview', $a); } else { $regradealldrydolabel = get_string('regradealldrydo', 'quiz_overview', $regradesneeded); $regradealldrylabel = get_string('regradealldry', 'quiz_overview'); $regradealllabel = get_string('regradeall', 'quiz_overview'); } $displayurl = new moodle_url($reporturl, $displayoptions + array('sesskey' => sesskey())); echo '<div class="mdl-align">'; echo '<form action="' . $displayurl->out_omit_querystring() . '">'; echo '<div>'; echo html_writer::input_hidden_params($displayurl); echo '<input type="submit" name="regradeall" value="' . $regradealllabel . '"/>'; echo '<input type="submit" name="regradealldry" value="' . $regradealldrylabel . '"/>'; if ($regradesneeded) { echo '<input type="submit" name="regradealldrydo" value="' . $regradealldrydolabel . '"/>'; } echo '</div>'; echo '</form>'; echo '</div>'; } // Print information on the grading method if ($strattempthighlight = quiz_report_highlighting_grading_method($quiz, $qmsubselect, $qmfilter)) { echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>'; } } // Define table columns $columns = array(); $headers = array(); if (!$table->is_downloading() && $candelete) { $columns[] = 'checkbox'; $headers[] = null; } $this->add_user_columns($table, $columns, $headers); $this->add_time_columns($columns, $headers); if ($detailedmarks) { foreach ($questions as $slot => $question) { // Ignore questions of zero length $columns[] = 'qsgrade' . $slot; $header = get_string('qbrief', 'quiz', $question->number); if (!$table->is_downloading()) { $header .= '<br />'; } else { $header .= ' '; } $header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question'); $headers[] = $header; } } if (!$table->is_downloading() && has_capability('mod/quiz:regrade', $this->context) && $this->has_regraded_questions($from, $where, $params)) { $columns[] = 'regraded'; $headers[] = get_string('regrade', 'quiz_overview'); } $this->add_grade_columns($quiz, $columns, $headers); $this->set_up_table_columns($table, $columns, $headers, $reporturl, $displayoptions, false); $table->set_attribute('class', 'generaltable generalbox grades'); $table->out($pagesize, true); } if (!$table->is_downloading() && $this->should_show_grades($quiz)) { if ($currentgroup && $groupstudents) { list($usql, $params) = $DB->get_in_or_equal($groupstudents); $params[] = $quiz->id; if ($DB->record_exists_select('quiz_grades', "userid {$usql} AND quiz = ?", $params)) { $imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php', array('id' => $quiz->id, 'groupid' => $currentgroup)); $graphname = get_string('overviewreportgraphgroup', 'quiz_overview', groups_get_group_name($currentgroup)); echo $OUTPUT->heading($graphname); echo html_writer::tag('div', html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $graphname)), array('class' => 'graph')); } } if ($DB->record_exists('quiz_grades', array('quiz' => $quiz->id))) { $graphname = get_string('overviewreportgraph', 'quiz_overview'); $imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php', array('id' => $quiz->id)); echo $OUTPUT->heading($graphname); echo html_writer::tag('div', html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $graphname)), array('class' => 'graph')); } } return true; }
$canallocate = has_capability('mod/workshop:allocate', $workshop->context); $canpublish = has_capability('mod/workshop:publishsubmissions', $workshop->context); $canoverride = ($workshop->phase == workshop::PHASE_EVALUATION and has_capability('mod/workshop:overridegrades', $workshop->context)); $userassessment = $workshop->get_assessment_of_submission_by_user($submission->id, $USER->id); $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) {
/** * 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; }
/** * 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; }
/** * 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']; }
/** * Returns a list of teachers that should be grading given submission. * * @param int $userid The submission to grade * @return array */ protected function get_graders($userid) { // Potential graders should be active users only. $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade", null, 'u.*', null, null, null, true); $graders = array(); if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { foreach ($groups as $group) { foreach ($potentialgraders as $grader) { if ($grader->id == $userid) { // Do not send self. continue; } if (groups_is_member($group->id, $grader->id)) { $graders[$grader->id] = $grader; } } } } else { // User not in group, try to find graders without group. foreach ($potentialgraders as $grader) { if ($grader->id == $userid) { // Do not send self. continue; } if (!groups_has_membership($this->get_course_module(), $grader->id)) { $graders[$grader->id] = $grader; } } } } else { foreach ($potentialgraders as $grader) { if ($grader->id == $userid) { // Do not send self. continue; } // Must be enrolled. if (is_enrolled($this->get_course_context(), $grader->id)) { $graders[$grader->id] = $grader; } } } return $graders; }
/** * 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; }
/** * Returns all assignments since a given time * * @param array $activities The activity information is returned in this array * @param int $index The current index in the activities array * @param int $timestart The earliest activity to show * @param int $courseid Limit the search to this course * @param int $cmid The course module id * @param int $userid Optional user id * @param int $groupid Optional group id * @return void */ function assign_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); // no need pass this by reference as the return object already being cached $cm = $modinfo->get_cm($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,\n {$userfields}\n FROM {assign_submission} asb\n JOIN {assign} a ON a.id = asb.assignment\n JOIN {user} u ON u.id = asb.userid\n {$groupjoin}\n WHERE asb.timemodified > :timestart AND a.id = :cminstance\n {$userselect} {$groupselect}\n ORDER BY asb.timemodified ASC", $params))) { return; } $groupmode = groups_get_activity_groupmode($cm, $course); $cm_context = context_module::instance($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->get_groups())) { $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo } $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions'); $show = array(); $usersgroups = groups_get_all_groups($course->id, $USER->id, $cm->groupingid); if (is_array($usersgroups)) { $usersgroups = array_keys($usersgroups); } 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($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; } if (is_array($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', 'assign', $cm->instance, $userids); } $aname = format_string($cm->name, true); foreach ($show as $submission) { $activity = new stdClass(); $activity->type = 'assign'; $activity->cmid = $cm->id; $activity->name = $aname; $activity->sectionnum = $cm->sectionnum; $activity->timestamp = $submission->timemodified; $activity->user = new stdClass(); if ($grader) { $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade; } $userfields = explode(',', user_picture::fields()); foreach ($userfields as $userfield) { if ($userfield == 'id') { $activity->user->{$userfield} = $submission->userid; // aliased in SQL above } else { $activity->user->{$userfield} = $submission->{$userfield}; } } $activity->user->fullname = fullname($submission, $viewfullnames); $activities[$index++] = $activity; } return; }
/** * Setup page tabs, if options is empty, will set up active tab automatically * @param array $options, tabs options */ protected function setup_tabs($options = array()) { global $CFG, $PAGE; $groupmode = groups_get_activity_groupmode($PAGE->cm); if (empty($CFG->usecomments) || !has_capability('mod/wiki:viewcomment', $PAGE->context)){ unset($this->tabs['comments']); } if (!has_capability('mod/wiki:editpage', $PAGE->context)){ unset($this->tabs['edit']); } if ($groupmode and $groupmode == VISIBLEGROUPS) { $currentgroup = groups_get_activity_group($PAGE->cm); $manage = has_capability('mod/wiki:managewiki', $PAGE->cm->context); $edit = has_capability('mod/wiki:editpage', $PAGE->context); if (!$manage and !($edit and groups_is_member($currentgroup))) { unset($this->tabs['edit']); } } if (empty($options)) { $this->tabs_options = array('activetab' => substr(get_class($this), 10)); } else { $this->tabs_options = $options; } }
/** * Display the report. */ function display($quiz, $cm, $course) { global $CFG, $COURSE, $DB, $PAGE, $OUTPUT; $context = get_context_instance(CONTEXT_MODULE, $cm->id); // Work out some display options - whether there is feedback, and whether scores should be shown. $hasfeedback = quiz_has_feedback($quiz); $fakeattempt = new stdClass(); $fakeattempt->preview = false; $fakeattempt->timefinish = $quiz->timeopen; $fakeattempt->userid = 0; $reviewoptions = quiz_get_reviewoptions($quiz, $fakeattempt, $context); $showgrades = quiz_has_grades($quiz) && $reviewoptions->scores; $download = optional_param('download', '', PARAM_ALPHA); if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) { //attempts need to be deleted require_capability('mod/quiz:deleteattempts', $context); $attemptids = optional_param('attemptid', array(), PARAM_INT); foreach ($attemptids as $attemptid) { add_to_log($course->id, 'quiz', 'delete attempt', 'report.php?id=' . $cm->id, $attemptid, $cm->id); quiz_delete_attempt($attemptid, $quiz); } //No need for a redirect, any attemptids that do not exist are ignored. //So no problem if the user refreshes and tries to delete the same attempts //twice. } $pageoptions = array(); $pageoptions['id'] = $cm->id; $pageoptions['q'] = $quiz->id; $pageoptions['mode'] = 'responses'; $reporturl = new moodle_url($CFG->wwwroot . '/mod/quiz/report.php', $pageoptions); $qmsubselect = quiz_report_qm_filter_select($quiz); /// find out current groups mode $currentgroup = groups_get_activity_group($cm, true); $mform = new mod_quiz_report_responses_settings($reporturl, array('qmsubselect' => $qmsubselect, 'quiz' => $quiz, 'currentgroup' => $currentgroup)); if ($fromform = $mform->get_data()) { $attemptsmode = $fromform->attemptsmode; if ($qmsubselect) { //control is not on the form if //the grading method is not set //to grade one attempt per user eg. for average attempt grade. $qmfilter = $fromform->qmfilter; } else { $qmfilter = 0; } set_user_preference('quiz_report_pagesize', $fromform->pagesize); $pagesize = $fromform->pagesize; } else { $qmfilter = optional_param('qmfilter', 0, PARAM_INT); $attemptsmode = optional_param('attemptsmode', null, PARAM_INT); if ($attemptsmode === null) { //default $attemptsmode = QUIZ_REPORT_ATTEMPTS_ALL; } else { if ($currentgroup) { //default for when a group is selected if ($attemptsmode === null || $attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL) { $attemptsmode = QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH; } } else { if (!$currentgroup && $course->id == SITEID) { //force report on front page to show all, unless a group is selected. $attemptsmode = QUIZ_REPORT_ATTEMPTS_ALL; } } } $pagesize = get_user_preferences('quiz_report_pagesize', 0); } if ($pagesize < 1) { $pagesize = QUIZ_REPORT_DEFAULT_PAGE_SIZE; } // We only want to show the checkbox to delete attempts // if the user has permissions and if the report mode is showing attempts. $candelete = has_capability('mod/quiz:deleteattempts', $context) && $attemptsmode != QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO; $displayoptions = array(); $displayoptions['attemptsmode'] = $attemptsmode; $displayoptions['qmfilter'] = $qmfilter; //work out the sql for this table. if (!($students = get_users_by_capability($context, array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), '', '', '', '', '', '', false))) { $students = array(); } else { $students = array_keys($students); } if (empty($currentgroup)) { // all users who can attempt quizzes $allowed = $students; $groupstudents = array(); } else { // all users who can attempt quizzes and who are in the currently selected group if (!($groupstudents = get_users_by_capability($context, array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), '', '', '', '', $currentgroup, '', false))) { $groupstudents = array(); } else { $groupstudents = array_keys($groupstudents); } $allowed = $groupstudents; } $questions = quiz_report_load_questions($quiz); $table = new quiz_report_responses_table($quiz, $qmsubselect, $groupstudents, $students, $questions, $candelete, $reporturl, $displayoptions); $table->is_downloading($download, get_string('reportresponses', 'quiz_responses'), "{$COURSE->shortname} " . format_string($quiz->name, true)); if (!$table->is_downloading()) { // Only print headers if not asked to download data $PAGE->requires->css('mod/quiz/report/responses/styles.css'); $this->print_header_and_tabs($cm, $course, $quiz, 'responses', ''); } if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used if (!$table->is_downloading()) { groups_print_activity_menu($cm, $reporturl->out(false, $displayoptions)); } } // Print information on the number of existing attempts if (!$table->is_downloading()) { //do not print notices when downloading if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) { echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>'; } } $nostudents = false; if (!$students) { echo $OUTPUT->notification(get_string('nostudentsyet')); $nostudents = true; } else { if ($currentgroup && !$groupstudents) { echo $OUTPUT->notification(get_string('nostudentsingroup')); $nostudents = true; } } if (!$table->is_downloading()) { // Print display options $mform->set_data($displayoptions + compact('pagesize')); $mform->display(); } if (!$nostudents || $attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL) { // Print information on the grading method and whether we are displaying // if (!$table->is_downloading()) { //do not print notices when downloading if ($strattempthighlight = quiz_report_highlighting_grading_method($quiz, $qmsubselect, $qmfilter)) { echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>'; } } $showgrades = quiz_has_grades($quiz) && $reviewoptions->scores; $hasfeedback = quiz_has_feedback($quiz); // Construct the SQL $fields = $DB->sql_concat('u.id', '\'#\'', 'COALESCE(qa.attempt, \'0\')') . ' AS concattedid, '; if ($qmsubselect) { $fields .= "(CASE " . " WHEN {$qmsubselect} THEN 1" . " ELSE 0 " . "END) AS gradedattempt, "; } $fields .= 'qa.uniqueid, qa.id AS attempt, u.id AS userid, u.idnumber, u.firstname,' . ' u.lastname, u.institution, u.department, u.email, u.picture, u.imagealt, ' . 'qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration, ' . 'qa.layout '; // This part is the same for all cases - join users and quiz_attempts tables $from = '{user} u '; $from .= 'LEFT JOIN {quiz_attempts} qa ON qa.userid = u.id AND qa.quiz = :quizid'; $params = array('quizid' => $quiz->id); if ($qmsubselect && $qmfilter) { $from .= ' AND ' . $qmsubselect; } switch ($attemptsmode) { case QUIZ_REPORT_ATTEMPTS_ALL: // Show all attempts, including students who are no longer in the course $where = 'qa.id IS NOT NULL AND qa.preview = 0'; break; case QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH: // Show only students with attempts list($allowed_usql, $allowed_params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED, 'u0000'); $params += $allowed_params; $where = "u.id {$allowed_usql} AND qa.preview = 0 AND qa.id IS NOT NULL"; break; case QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO: // Show only students without attempts list($allowed_usql, $allowed_params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED, 'u0000'); $params += $allowed_params; $where = "u.id {$allowed_usql} AND qa.id IS NULL"; break; case QUIZ_REPORT_ATTEMPTS_ALL_STUDENTS: // Show all students with or without attempts list($allowed_usql, $allowed_params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED, 'u0000'); $params += $allowed_params; $where = "u.id {$allowed_usql} AND (qa.preview = 0 OR qa.preview IS NULL)"; break; } $table->set_count_sql("SELECT COUNT(1) FROM {$from} WHERE {$where}", $params); $table->set_sql($fields, $from, $where, $params); // Define table columns $columns = array(); $headers = array(); if (!$table->is_downloading() && $candelete) { $columns[] = 'checkbox'; $headers[] = NULL; } if (!$table->is_downloading() && $CFG->grade_report_showuserimage) { $columns[] = 'picture'; $headers[] = ''; } if (!$table->is_downloading()) { $columns[] = 'fullname'; $headers[] = get_string('name'); } else { $columns[] = 'lastname'; $headers[] = get_string('lastname'); $columns[] = 'firstname'; $headers[] = get_string('firstname'); } if ($CFG->grade_report_showuseridnumber) { $columns[] = 'idnumber'; $headers[] = get_string('idnumber'); } if ($table->is_downloading()) { $columns[] = 'institution'; $headers[] = get_string('institution'); $columns[] = 'department'; $headers[] = get_string('department'); $columns[] = 'email'; $headers[] = get_string('email'); $columns[] = 'timestart'; $headers[] = get_string('startedon', 'quiz'); $columns[] = 'timefinish'; $headers[] = get_string('timecompleted', 'quiz'); $columns[] = 'duration'; $headers[] = get_string('attemptduration', 'quiz'); } if ($showgrades) { $columns[] = 'sumgrades'; $headers[] = get_string('grade', 'quiz') . '/' . quiz_format_grade($quiz, $quiz->grade); } if ($hasfeedback) { $columns[] = 'feedbacktext'; $headers[] = get_string('feedback', 'quiz'); } // we want to display responses for all questions foreach ($questions as $id => $question) { // Ignore questions of zero length $columns[] = 'qsanswer' . $id; $headers[] = '#' . $question->number; $question->formattedname = strip_tags(format_string($question->name)); } // Load the question type specific information if (!get_question_options($questions)) { print_error('cannotloadoptions', 'quiz_responses'); } $table->define_columns($columns); $table->define_headers($headers); $table->sortable(true, 'concattedid'); // Set up the table $table->define_baseurl($reporturl->out(false, $displayoptions)); $table->collapsible(true); $table->column_suppress('picture'); $table->column_suppress('fullname'); $table->column_suppress('idnumber'); $table->no_sorting('feedbacktext'); $table->column_class('picture', 'picture'); $table->column_class('lastname', 'bold'); $table->column_class('firstname', 'bold'); $table->column_class('fullname', 'bold'); $table->column_class('sumgrades', 'bold'); $table->set_attribute('id', 'attempts'); $table->out($pagesize, true); } return true; }
/** * Validate comment parameter before perform other comments actions * * @param stdClass $comment_param { * context => context the context object * courseid => int course id * cm => stdClass course module object * commentarea => string comment area * itemid => int itemid * } * * @package mod_wiki * @category comment * * @return boolean */ function wiki_comment_validate($comment_param) { global $DB, $CFG; require_once $CFG->dirroot . '/mod/wiki/locallib.php'; // validate comment area if ($comment_param->commentarea != 'wiki_page') { throw new comment_exception('invalidcommentarea'); } // validate itemid if (!($record = $DB->get_record('wiki_pages', array('id' => $comment_param->itemid)))) { throw new comment_exception('invalidcommentitemid'); } if (!($subwiki = wiki_get_subwiki($record->subwikiid))) { throw new comment_exception('invalidsubwikiid'); } if (!($wiki = wiki_get_wiki_from_pageid($comment_param->itemid))) { throw new comment_exception('invalidid', 'data'); } if (!($course = $DB->get_record('course', array('id' => $wiki->course)))) { throw new comment_exception('coursemisconf'); } if (!($cm = get_coursemodule_from_instance('wiki', $wiki->id, $course->id))) { throw new comment_exception('invalidcoursemodule'); } $context = context_module::instance($cm->id); // group access if ($subwiki->groupid) { $groupmode = groups_get_activity_groupmode($cm, $course); if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { if (!groups_is_member($subwiki->groupid)) { throw new comment_exception('notmemberofgroup'); } } } // validate context id if ($context->id != $comment_param->context->id) { throw new comment_exception('invalidcontext'); } // validation for comment deletion if (!empty($comment_param->commentid)) { if ($comment = $DB->get_record('comments', array('id' => $comment_param->commentid))) { if ($comment->commentarea != 'wiki_page') { throw new comment_exception('invalidcommentarea'); } if ($comment->contextid != $context->id) { throw new comment_exception('invalidcontext'); } if ($comment->itemid != $comment_param->itemid) { throw new comment_exception('invalidcommentitemid'); } } else { throw new comment_exception('invalidcommentid'); } } return true; }
public function get_group_mode() { if (is_null($this->groupmode)) { $this->groupmode = groups_get_activity_groupmode($this->cm, $this->course); } return $this->groupmode; }
/** * 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)); }
/** * 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', get_context_instance(CONTEXT_MODULE, $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); }
/** * Adds module specific settings to the settings block * * @param settings_navigation $settings The settings navigation object * @param navigation_node $questionnairenode The node to add module settings to */ function questionnaire_extend_settings_navigation(settings_navigation $settings, navigation_node $questionnairenode) { global $PAGE, $DB, $USER, $CFG; $individualresponse = optional_param('individualresponse', false, PARAM_INT); $rid = optional_param('rid', false, PARAM_INT); // Response id. $currentgroupid = optional_param('group', 0, PARAM_INT); // Group id. require_once $CFG->dirroot . '/mod/questionnaire/questionnaire.class.php'; $context = $PAGE->cm->context; $cmid = $PAGE->cm->id; $cm = $PAGE->cm; $course = $PAGE->course; if (!($questionnaire = $DB->get_record("questionnaire", array("id" => $cm->instance)))) { print_error('invalidcoursemodule'); } $courseid = $course->id; $questionnaire = new questionnaire(0, $questionnaire, $course, $cm); if ($survey = $DB->get_record('questionnaire_survey', array('id' => $questionnaire->sid))) { $owner = trim($survey->owner) == trim($courseid); } else { $survey = false; $owner = true; } // We want to add these new nodes after the Edit settings node, and before the // Locally assigned roles node. Of course, both of those are controlled by capabilities. $keys = $questionnairenode->get_children_key_list(); $beforekey = null; $i = array_search('modedit', $keys); if ($i === false and array_key_exists(0, $keys)) { $beforekey = $keys[0]; } else { if (array_key_exists($i + 1, $keys)) { $beforekey = $keys[$i + 1]; } } if (has_capability('mod/questionnaire:manage', $context) && $owner) { $url = '/mod/questionnaire/qsettings.php'; $node = navigation_node::create(get_string('advancedsettings'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'advancedsettings', new pix_icon('t/edit', '')); $questionnairenode->add_node($node, $beforekey); } if (has_capability('mod/questionnaire:editquestions', $context) && $owner) { $url = '/mod/questionnaire/questions.php'; $node = navigation_node::create(get_string('questions', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'questions', new pix_icon('t/edit', '')); $questionnairenode->add_node($node, $beforekey); } if (has_capability('mod/questionnaire:preview', $context) && $owner) { $url = '/mod/questionnaire/preview.php'; $node = navigation_node::create(get_string('preview_label', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'preview', new pix_icon('t/preview', '')); $questionnairenode->add_node($node, $beforekey); } if ($questionnaire->user_can_take($USER->id)) { $url = '/mod/questionnaire/complete.php'; $node = navigation_node::create(get_string('answerquestions', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, '', new pix_icon('i/info', 'answerquestions')); $questionnairenode->add_node($node, $beforekey); } $usernumresp = $questionnaire->count_submissions($USER->id); if ($questionnaire->capabilities->readownresponses && $usernumresp > 0) { $url = '/mod/questionnaire/myreport.php'; $node = navigation_node::create(get_string('yourresponses', 'questionnaire'), new moodle_url($url, array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary')), navigation_node::TYPE_SETTING, null, 'yourresponses'); $myreportnode = $questionnairenode->add_node($node, $beforekey); $summary = $myreportnode->add(get_string('summary', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary'))); $byresponsenode = $myreportnode->add(get_string('viewbyresponse', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 1, 'action' => 'vresp'))); $allmyresponsesnode = $myreportnode->add(get_string('myresponses', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'vall'))); if ($questionnaire->capabilities->downloadresponses) { $downloadmyresponsesnode = $myreportnode->add(get_string('downloadtext'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'user' => $USER->id, 'action' => 'dwnpg', 'group' => $currentgroupid))); } } $numresp = $questionnaire->count_submissions(); // Number of responses in currently selected group (or all participants etc.). if (isset($SESSION->questionnaire->numselectedresps)) { $numselectedresps = $SESSION->questionnaire->numselectedresps; } else { $numselectedresps = $numresp; } // If questionnaire is set to separate groups, prevent user who is not member of any group // to view All responses. $canviewgroups = true; $groupmode = groups_get_activity_groupmode($cm, $course); if ($groupmode == 1) { $canviewgroups = groups_has_membership($cm, $USER->id); } if ($questionnaire->capabilities->readallresponseanytime && $numresp > 0 && $owner && $numselectedresps > 0 || $questionnaire->capabilities->readallresponses && $numresp > 0 && $canviewgroups && ($questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $questionnaire->is_closed() || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $usernumresp > 0) && $questionnaire->is_survey_owner()) { $url = '/mod/questionnaire/report.php'; $node = navigation_node::create(get_string('viewallresponses', 'questionnaire'), new moodle_url($url, array('instance' => $questionnaire->id, 'action' => 'vall')), navigation_node::TYPE_SETTING, null, 'vall'); $reportnode = $questionnairenode->add_node($node, $beforekey); if ($questionnaire->capabilities->viewsingleresponse) { $summarynode = $reportnode->add(get_string('summary', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall'))); } else { $summarynode = $reportnode; } $defaultordernode = $summarynode->add(get_string('order_default', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall', 'group' => $currentgroupid))); $ascendingordernode = $summarynode->add(get_string('order_ascending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallasort', 'group' => $currentgroupid))); $descendingordernode = $summarynode->add(get_string('order_descending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallarsort', 'group' => $currentgroupid))); if ($questionnaire->capabilities->deleteresponses) { $deleteallnode = $summarynode->add(get_string('deleteallresponses', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'delallresp', 'group' => $currentgroupid))); } if ($questionnaire->capabilities->downloadresponses) { $downloadresponsesnode = $summarynode->add(get_string('downloadtextformat', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dwnpg', 'group' => $currentgroupid))); } if ($questionnaire->capabilities->viewsingleresponse && $questionnaire->respondenttype != 'anonymous') { $byresponsenode = $reportnode->add(get_string('viewbyresponse', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid))); $viewindividualresponsenode = $byresponsenode->add(get_string('view', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid))); if ($individualresponse) { $deleteindividualresponsenode = $byresponsenode->add(get_string('deleteresp', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dresp', 'byresponse' => 1, 'rid' => $rid, 'group' => $currentgroupid, 'individualresponse' => 1))); } } } if ($questionnaire->capabilities->viewsingleresponse) { $url = '/mod/questionnaire/show_nonrespondents.php'; $node = navigation_node::create(get_string('show_nonrespondents', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'nonrespondents'); $nonrespondentsnode = $questionnairenode->add_node($node, $beforekey); } }
/** * Returns a list of teachers that should be grading given submission * * @param object $user * @return array */ function get_graders($user) { //potential graders $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false); $graders = array(); if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups foreach ($groups as $group) { foreach ($potgraders as $t) { if ($t->id == $user->id) { continue; // do not send self } if (groups_is_member($group->id, $t->id)) { $graders[$t->id] = $t; } } } } else { // user not in group, try to find graders without group foreach ($potgraders as $t) { if ($t->id == $user->id) { continue; // do not send self } if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack $graders[$t->id] = $t; } } } } else { foreach ($potgraders as $t) { if ($t->id == $user->id) { continue; // do not send self } $graders[$t->id] = $t; } } return $graders; }
require_course_login($course, true, $cm); $context = get_context_instance(CONTEXT_MODULE, $cm->id); /// Print header. $navigation = build_navigation('', $cm); print_header_simple(format_string($forum->name), "", $navigation, "", "", true, $buttontext, user_login_string($course) . '<hr style="width:95%">' . navmenu($course, $cm)); /// Some capability checks. if (empty($cm->visible) and !has_capability('moodle/course:viewhiddenactivities', $context)) { notice(get_string("activityiscurrentlyhidden")); } if (!has_capability('mod/forum:viewdiscussion', $context)) { notice(get_string('noviewdiscussionspermission', 'forum')); } /// find out current groups mode groups_print_activity_menu($cm, 'view.php?id=' . $cm->id); $currentgroup = groups_get_activity_group($cm); $groupmode = groups_get_activity_groupmode($cm); /// Okay, we can show the discussions. Log the forum view. if ($cm->id) { add_to_log($course->id, "forum", "view forum", "view.php?id={$cm->id}", "{$forum->id}", $cm->id); } else { add_to_log($course->id, "forum", "view forum", "view.php?f={$forum->id}", "{$forum->id}"); } /// Print settings and things across the top // If it's a simple single discussion forum, we need to print the display // mode control. if ($forum->type == 'single') { if (!($discussion = get_record("forum_discussions", "forum", $forum->id))) { if ($discussions = get_records("forum_discussions", "forum", $forum->id, "timemodified ASC")) { $discussion = array_pop($discussions); } }
if ($reportdata->users) { $filename = clean_filename($course->shortname . '_Attendances_' . userdate(time(), '%Y%m%d-%H%M')); $group = $formdata->group ? $reportdata->groups[$formdata->group] : 0; $data = new stdClass(); $data->tabhead = array(); $data->course = $att->course->fullname; $data->group = $group ? $group->name : get_string('allparticipants'); if (isset($formdata->ident['id'])) { $data->tabhead[] = get_string('studentid', 'attendance'); } if (isset($formdata->ident['uname'])) { $data->tabhead[] = get_string('username'); } $data->tabhead[] = get_string('lastname'); $data->tabhead[] = get_string('firstname'); $groupmode = groups_get_activity_groupmode($cm, $course); if (!empty($groupmode)) { $data->tabhead[] = get_string('groups'); } if (count($reportdata->sessions) > 0) { foreach ($reportdata->sessions as $sess) { $text = userdate($sess->sessdate, get_string('strftimedmyhm', 'attendance')); $text .= ' '; $text .= $sess->groupid ? $reportdata->groups[$sess->groupid]->name : get_string('commonsession', 'attendance'); $data->tabhead[] = $text; if (isset($formdata->includeremarks)) { $data->tabhead[] = get_string('remark', 'attendance', $text); } } } else { print_error('sessionsnotfound', 'attendance', $att->url_manage());
/** * Checks if current user can edit a subwiki * * @param $subwiki */ function wiki_user_can_edit($subwiki) { global $USER; $wiki = wiki_get_wiki($subwiki->wikiid); $cm = get_coursemodule_from_instance('wiki', $wiki->id); $context = get_context_instance(CONTEXT_MODULE, $cm->id); // Working depending on activity groupmode switch (groups_get_activity_groupmode($cm)) { case NOGROUPS: if ($wiki->wikimode == 'collaborative') { // Collaborative Mode: // There is a wiki for all the class. // // Only edit capbility needed return has_capability('mod/wiki:editpage', $context); } else { if ($wiki->wikimode == 'individual') { // Individual Mode // There is a wiki per user // Only the owner of that wiki can edit it if ($subwiki->userid == $USER->id) { return has_capability('mod/wiki:editpage', $context); } else { // Current user is not the owner of that wiki. // User must have: // mod/wiki:editpage capability // and // mod/wiki:managewiki capability $edit = has_capability('mod/wiki:editpage', $context); $manage = has_capability('mod/wiki:managewiki', $context); return $edit && $manage; } } else { //Error return false; } } case SEPARATEGROUPS: if ($wiki->wikimode == 'collaborative') { // Collaborative Mode: // There is one wiki per group. // // Only members of subwiki group could edit that wiki if ($subwiki->groupid == groups_get_activity_group($cm)) { // Only edit capability needed return has_capability('mod/wiki:editpage', $context); } else { // User is not part of that group // User must have: // mod/wiki:managewiki capability // and // moodle/site:accessallgroups capability // and // mod/wiki:editpage capability $manage = has_capability('mod/wiki:managewiki', $context); $access = has_capability('moodle/site:accessallgroups', $context); $edit = has_capability('mod/wiki:editpage', $context); return $manage && $access && $edit; } } else { if ($wiki->wikimode == 'individual') { // Individual Mode: // Each person owns a wiki. // // Only the owner of that wiki can edit it if ($subwiki->userid == $USER->id) { return has_capability('mod/wiki:editpage', $context); } else { // Current user is not the owner of that wiki. // User must have: // mod/wiki:managewiki capability // and // moodle/site:accessallgroups capability // and // mod/wiki:editpage capability $manage = has_capability('mod/wiki:managewiki', $context); $access = has_capability('moodle/site:accessallgroups', $context); $edit = has_capability('mod/wiki:editpage', $context); return $manage && $access && $edit; } } else { //Error return false; } } case VISIBLEGROUPS: if ($wiki->wikimode == 'collaborative') { // Collaborative Mode: // There is one wiki per group. // // Only members of subwiki group could edit that wiki if (groups_is_member($subwiki->groupid)) { // Only edit capability needed return has_capability('mod/wiki:editpage', $context); } else { // User is not part of that group // User must have: // mod/wiki:managewiki capability // and // mod/wiki:editpage capability $manage = has_capability('mod/wiki:managewiki', $context); $edit = has_capability('mod/wiki:editpage', $context); return $manage && $edit; } } else { if ($wiki->wikimode == 'individual') { // Individual Mode: // Each person owns a wiki. // // Only the owner of that wiki can edit it if ($subwiki->userid == $USER->id) { return has_capability('mod/wiki:editpage', $context); } else { // Current user is not the owner of that wiki. // User must have: // mod/wiki:managewiki capability // and // mod/wiki:editpage capability $manage = has_capability('mod/wiki:managewiki', $context); $edit = has_capability('mod/wiki:editpage', $context); return $manage && $edit; } } else { //Error return false; } } default: // Error return false; } }
/** * Determine if a given group is visible to user or not in a given context. * * @since Moodle 2.6 * @param int $groupid Group id to test. 0 for all groups. * @param stdClass $course Course object. * @param stdClass $cm Course module object. * @param int $userid user id to test against. Defaults to $USER. * @return boolean true if visible, false otherwise */ function groups_group_visible($groupid, $course, $cm = null, $userid = null) { global $USER; if (empty($userid)) { $userid = $USER->id; } $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course); if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) { // Groups are not used, or everything is visible, no need to go any further. return true; } $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id); if (has_capability('moodle/site:accessallgroups', $context, $userid)) { // User can see everything. Groupid = 0 is handled here as well. return true; } else { if ($groupid != 0) { // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group. $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid); if (array_key_exists($groupid, $groups)) { // User can see the group. return true; } } } return false; }