public function report_data($visualreport) { $data = array(); $data['header'] = array(); $data['header']['student'] = 'student'; $data['header']['grade'] = 'grade'; $data['header']['item'] = 'item'; $data['header']['group'] = 'group'; foreach ($visualreport->grades as $itemkey => $itemgrades) { foreach ($itemgrades as $studentkey => $studentdata) { if ($studentdata != null && $studentdata->finalgrade != null) { foreach (groups_get_user_groups($visualreport->courseid, $studentkey) as $grouping) { if (count($grouping) > 0) { foreach ($grouping as $group) { $data[$studentkey . '-' . $itemkey . '-' . $group]['student'] = $visualreport->users[$studentkey]->firstname . ' ' . $visualreport->users[$studentkey]->lastname; $data[$studentkey . '-' . $itemkey . '-' . $group]['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $data[$studentkey . '-' . $itemkey . '-' . $group]['item'] = $visualreport->gtree->items[$itemkey]->get_name(); $data[$studentkey . '-' . $itemkey . '-' . $group]['group'] = groups_get_group_name($group); } } else { $data[$studentkey . '-' . $itemkey . '-ng']['student'] = $visualreport->users[$studentkey]->firstname . ' ' . $visualreport->users[$studentkey]->lastname; $data[$studentkey . '-' . $itemkey . '-ng']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $data[$studentkey . '-' . $itemkey . '-ng']['item'] = $visualreport->gtree->items[$itemkey]->get_name(); $data[$studentkey . '-' . $itemkey . '-ng']['group'] = get_string('nogroup', 'gradereport_visual'); } } } } } return $data; }
/** * Returns the display name of a group - the group name followed by * the number of members in brackets. * @param int $groupid The group ID. * @return string The display name of the group */ function groups_get_group_displayname($groupid) { if ($groupname = groups_get_group_name($groupid)) { $count = groups_count_group_members($groupid); return "{$groupname} ({$count})"; } return false; }
public function report_data($visualreport) { $data = array(); $data['header'] = array(); $data['header']['grade'] = 'grade'; $data['header']['item'] = 'item'; $data['header']['group'] = 'group'; $count = array(); foreach ($visualreport->grades as $itemkey => $itemgrades) { foreach ($itemgrades as $studentkey => $studentdata) { if ($studentdata != null && $studentdata->finalgrade != null) { foreach (groups_get_user_groups($visualreport->courseid, $studentkey) as $grouping) { if (count($grouping) > 0) { foreach ($grouping as $group) { if (!isset($data[$itemkey . '-' . $group])) { $data[$itemkey . '-' . $group] = array(); $data[$itemkey . '-' . $group]['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $data[$itemkey . '-' . $group]['item'] = $visualreport->gtree->items[$itemkey]->get_name(); $data[$itemkey . '-' . $group]['group'] = groups_get_group_name($group); $count[$itemkey . '-' . $group] = 1; } else { $data[$itemkey . '-' . $group]['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $count[$itemkey . '-' . $group]++; } } } else { if (!isset($data[$itemkey . '-ng'])) { $data[$itemkey . '-ng'] = array(); $data[$itemkey . '-ng']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $data[$itemkey . '-ng']['item'] = $visualreport->gtree->items[$itemkey]->get_name(); $data[$itemkey . '-ng']['group'] = get_string('nogroup', 'gradereport_visual'); $count[$itemkey . '-ng'] = 1; } else { $data[$itemkey . '-ng']['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $count[$itemkey . '-ng']++; } } if (!isset($data[$itemkey . '-ag'])) { $data[$itemkey . '-ag'] = array(); $data[$itemkey . '-ag']['grade'] = $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $data[$itemkey . '-ag']['item'] = $visualreport->gtree->items[$itemkey]->get_name(); $data[$itemkey . '-ag']['group'] = get_string('allgroups', 'gradereport_visual'); $count[$itemkey . '-ag'] = 1; } else { $data[$itemkey . '-ag']['grade'] += $studentdata->standardise_score($studentdata->finalgrade, $visualreport->gtree->items[$itemkey]->grademin, $visualreport->gtree->items[$itemkey]->grademax, 0, 100); $count[$itemkey . '-ag']++; } } } } } foreach ($data as $key => $row) { if ($key != 'header') { $data[$key]['grade'] /= $count[$key]; } } return $data; }
function test_create_group() { $this->assertTrue($this->groupid = groups_create_group($this->courseid)); $this->assertTrue(groups_group_exists($this->groupid)); $this->assertTrue(groups_group_belongs_to_course($this->groupid, $this->courseid)); $this->assertTrue($groupids = groups_get_groups($this->courseid)); //array... $this->assertTrue($groupinfo = groups_set_default_group_settings()); $groupinfo->name = 'Group ' . $this->getLabel(); //'Temporary Group Name' $this->assertTrue(groups_set_group_settings($this->groupid, $groupinfo)); $this->assertTrue($groupinfo->name == groups_get_group_name($this->groupid)); $this->assertTrue($this->courseid == groups_get_course($this->groupid)); }
function definition() { global $COURSE; $mform =& $this->_form; //------------------------------------------------------------------------------- $mform->addElement('header', 'preferencespage', get_string('preferencespage', 'quiz_overview')); if (!$this->_customdata['currentgroup']) { $studentsstring = get_string('participants'); } else { $a = new stdClass(); $a->coursestudent = get_string('participants'); $a->groupname = groups_get_group_name($this->_customdata['currentgroup']); if (20 < strlen($a->groupname)) { $studentsstring = get_string('studentingrouplong', 'quiz_overview', $a); } else { $studentsstring = get_string('studentingroup', 'quiz_overview', $a); } } $options = array(); if (!$this->_customdata['currentgroup']) { $options[QUIZ_REPORT_ATTEMPTS_ALL] = get_string('optallattempts', 'quiz_overview'); } if ($this->_customdata['currentgroup'] || $COURSE->id != SITEID) { $options[QUIZ_REPORT_ATTEMPTS_ALL_STUDENTS] = get_string('optallstudents', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH] = get_string('optattemptsonly', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO] = get_string('optnoattemptsonly', 'quiz_overview', $studentsstring); } $mform->addElement('select', 'attemptsmode', get_string('show', 'quiz_overview'), $options); $showattemptsgrp = array(); if ($this->_customdata['qmsubselect']) { $gm = '<span class="highlight">' . quiz_get_grading_option_name($this->_customdata['quiz']->grademethod) . '</span>'; $showattemptsgrp[] =& $mform->createElement('advcheckbox', 'qmfilter', get_string('showattempts', 'quiz_overview'), get_string('optonlygradedattempts', 'quiz_overview', $gm), null, array(0, 1)); } if (has_capability('mod/quiz:regrade', $this->_customdata['context'])) { $showattemptsgrp[] =& $mform->createElement('advcheckbox', 'regradefilter', get_string('showattempts', 'quiz_overview'), get_string('optonlyregradedattempts', 'quiz_overview'), null, array(0, 1)); } if ($showattemptsgrp) { $mform->addGroup($showattemptsgrp, null, get_string('showattempts', 'quiz_overview'), '<br />', false); } //------------------------------------------------------------------------------- $mform->addElement('header', 'preferencesuser', get_string('preferencesuser', 'quiz_overview')); $mform->addElement('text', 'pagesize', get_string('pagesize', 'quiz_overview')); $mform->setType('pagesize', PARAM_INT); $mform->addElement('selectyesno', 'detailedmarks', get_string('showdetailedmarks', 'quiz_overview')); $mform->addElement('submit', 'submitbutton', get_string('preferencessave', 'quiz_overview')); }
protected function definition() { $mform = $this->_form; $mform->addElement('header', 'preferencespage', get_string('preferencespage', 'quiz_overview')); if (!$this->_customdata['currentgroup']) { $studentsstring = get_string('participants'); } else { $a = new stdClass(); $a->coursestudent = get_string('participants'); $a->groupname = groups_get_group_name($this->_customdata['currentgroup']); if (20 < strlen($a->groupname)) { $studentsstring = get_string('studentingrouplong', 'quiz_overview', $a); } else { $studentsstring = get_string('studentingroup', 'quiz_overview', $a); } } $options = array(); if (!$this->_customdata['currentgroup']) { $options[quiz_attempts_report::ALL_ATTEMPTS] = get_string('optallattempts', 'quiz_overview'); } if ($this->_customdata['currentgroup'] || !is_inside_frontpage($this->_customdata['context'])) { $options[quiz_attempts_report::ALL_STUDENTS] = get_string('optallstudents', 'quiz_overview', $studentsstring); $options[quiz_attempts_report::STUDENTS_WITH] = get_string('optattemptsonly', 'quiz_overview', $studentsstring); $options[quiz_attempts_report::STUDENTS_WITH_NO] = get_string('optnoattemptsonly', 'quiz_overview', $studentsstring); } $mform->addElement('select', 'attemptsmode', get_string('show', 'quiz_overview'), $options); $this->definition_inner($mform); $mform->addElement('header', 'preferencesuser', get_string('preferencesuser', 'quiz_overview')); $mform->addElement('text', 'pagesize', get_string('pagesize', 'quiz_overview')); $mform->setType('pagesize', PARAM_INT); $mform->addElement('submit', 'submitbutton', get_string('preferencessave', 'quiz_overview')); }
protected function definition() { $mform = $this->_form; $mform->addElement('header', 'preferencespage', get_string('preferencespage', 'quiz_overview')); if (!$this->_customdata['currentgroup']) { $studentsstring = get_string('participants'); } else { $a = new stdClass(); $a->coursestudent = get_string('participants'); $a->groupname = groups_get_group_name($this->_customdata['currentgroup']); if (20 < strlen($a->groupname)) { $studentsstring = get_string('studentingrouplong', 'quiz_overview', $a); } else { $studentsstring = get_string('studentingroup', 'quiz_overview', $a); } } $options = array(); if (!$this->_customdata['currentgroup']) { $options[QUIZ_REPORT_ATTEMPTS_ALL] = get_string('optallattempts', 'quiz_overview'); } if ($this->_customdata['currentgroup'] || !is_inside_frontpage($this->_customdata['context'])) { $options[QUIZ_REPORT_ATTEMPTS_ALL_STUDENTS] = get_string('optallstudents', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH] = get_string('optattemptsonly', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO] = get_string('optnoattemptsonly', 'quiz_overview', $studentsstring); } $mform->addElement('select', 'attemptsmode', get_string('show', 'quiz_overview'), $options); if ($this->_customdata['qmsubselect']) { $gm = '<span class="gradedattempt">' . quiz_get_grading_option_name($this->_customdata['quiz']->grademethod) . '</span>'; $mform->addElement('advcheckbox', 'qmfilter', get_string('showattempts', 'quiz_overview'), get_string('optonlygradedattempts', 'quiz_overview', $gm), null, array(0, 1)); } $colsgroup = array(); $colsgroup[] = $mform->createElement('advcheckbox', 'qtext', '', get_string('summaryofquestiontext', 'quiz_responses')); $colsgroup[] = $mform->createElement('advcheckbox', 'resp', '', get_string('summaryofresponse', 'quiz_responses')); $colsgroup[] = $mform->createElement('advcheckbox', 'right', '', get_string('summaryofrightanswer', 'quiz_responses')); $mform->addGroup($colsgroup, null, get_string('include', 'quiz_responses'), '<br />', false); $mform->addElement('header', 'preferencesuser', get_string('preferencesuser', 'quiz_overview')); $mform->addElement('text', 'pagesize', get_string('pagesize', 'quiz_overview')); $mform->setType('pagesize', PARAM_INT); $mform->addElement('submit', 'submitbutton', get_string('preferencessave', 'quiz_overview')); }
function definition() { global $COURSE; $mform =& $this->_form; //------------------------------------------------------------------------------- $mform->addElement('header', 'preferencespage', get_string('preferencespage', 'quiz_overview')); if (!$this->_customdata['currentgroup']) { $studentsstring = get_string('participants'); } else { $a = new object(); $a->coursestudent = get_string('participants'); $a->groupname = groups_get_group_name($this->_customdata['currentgroup']); if (20 < strlen($a->groupname)) { $studentsstring = get_string('studentingrouplong', 'quiz_overview', $a); } else { $studentsstring = get_string('studentingroup', 'quiz_overview', $a); } } $options = array(); if (!$this->_customdata['currentgroup']) { $options[QUIZ_REPORT_ATTEMPTS_ALL] = get_string('optallattempts', 'quiz_overview'); } if ($this->_customdata['currentgroup'] || $COURSE->id != SITEID) { $options[QUIZ_REPORT_ATTEMPTS_ALL_STUDENTS] = get_string('optallstudents', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH] = get_string('optattemptsonly', 'quiz_overview', $studentsstring); $options[QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO] = get_string('optnoattemptsonly', 'quiz_overview', $studentsstring); } $mform->addElement('select', 'attemptsmode', get_string('show', 'quiz_overview'), $options); if ($this->_customdata['qmsubselect']) { $gm = '<span class="highlight">' . quiz_get_grading_option_name($this->_customdata['quiz']->grademethod) . '</span>'; $mform->addElement('advcheckbox', 'qmfilter', get_string('show', 'quiz_overview'), get_string('optonlygradedattempts', 'quiz_overview', $gm), null, array(0, 1)); } //------------------------------------------------------------------------------- $mform->addElement('header', 'preferencesuser', get_string('preferencesuser', 'quiz_overview')); $mform->addElement('text', 'pagesize', get_string('pagesize', 'quiz_overview')); $mform->setType('pagesize', PARAM_INT); $this->add_action_buttons(false, get_string('preferencessave', 'quiz_overview')); }
$course = get_record('course', 'id', $filterselect); $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); print_heading(format_string($course->fullname)); $toprow[] = new tabobject('participants', $CFG->wwwroot . '/user/index.php?id=' . $filterselect, get_string('participants')); if ($CFG->bloglevel >= 3) { $toprow[] = new tabobject('blogs', $CFG->wwwroot . '/blog/index.php?filtertype=course&filterselect=' . $filterselect, get_string('blogs', 'blog')); } if (has_capability('moodle/notes:manage', $coursecontext) || has_capability('moodle/notes:view', $coursecontext)) { $toprow[] = new tabobject('notes', $CFG->wwwroot . '/notes/index.php?filtertype=course&filterselect=' . $filterselect, get_string('notes', 'notes')); } /************************************** * Group Level participation or Blogs * **************************************/ } else { if ($filtertype == 'group' && $filterselect) { $group_name = groups_get_group_name($filterselect); print_heading($group_name); if ($CFG->bloglevel >= 2) { $toprow[] = new tabobject('participants', $CFG->wwwroot . '/user/index.php?id=' . $course->id . '&group=' . $filterselect, get_string('participants')); $toprow[] = new tabobject('blogs', $CFG->wwwroot . '/blog/index.php?filtertype=group&filterselect=' . $filterselect, get_string('blogs', 'blog')); } /************************************** * User Level participation or Blogs * **************************************/ } else { if (isset($userid)) { $user = get_record('user', 'id', $userid); } print_heading(fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)))); $toprow[] = new tabobject('profile', $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&course=' . $course->id, get_string('profile')); $systemcontext = get_context_instance(CONTEXT_SYSTEM);
/** * Performs the report function. * * @param array $formdata the form data * @param int $type the report type * @param string $saveto File to save the pdf report to. * @return bool False on failure * @uses $CFG, $DB */ function report_ncccscensus_generate_report($formdata, $type = REPORT_NCCCSCENSUS_ACTION_VIEW, $saveto = false) { global $CFG, $DB; require_once $CFG->libdir . '/moodlelib.php'; $reportname = 'report_ncccscensus'; $cid = $formdata->id; // In case the form is hacked, set a default startdate to today at midnight. if (empty($formdata->startdate)) { $formdata->startdate = usergetmidnight(time(), get_user_timezone()); } // In case the form is hacked, set a default enddate to today at midnight. if (empty($formdata->enddate)) { $formdata->enddate = $formdata->startdate; } // Advance enddate to tomorrow's midnight. $formdata->enddate += DAYSECS - 1; // This flag determines if we should display grouped users or not. $nogroups = isset($formdata->disablegroups) ? true : false; if ($nogroups) { $group = false; } else { // If group specified, do some validation. $group = isset($formdata->group) ? $formdata->group : false; // In case the form is hacked, the group could be invalid. if ($group === false || $group < 0) { throw new report_ncccscensus_exception('cannotfindgroup'); } if ($group > 0) { // Validate the group ID. if (!groups_group_exists($group)) { throw new report_ncccscensus_exception('cannotfindgroup'); } // Validate the group ID with respect to the course ID. $groupdata = groups_get_course_data($cid); $groupfound = false; foreach ($groupdata->groups as $groupobject) { if ($groupobject->id == $group) { $groupfound = true; break; } } if (!$groupfound) { throw new report_ncccscensus_exception('invalidgroupid'); } // User could still hack form to view a group that they don't have the capability to see. $context = context_course::instance($cid); if (has_capability('moodle/site:accessallgroups', $context)) { $userid = 0; } else { if (has_capability('moodle/course:managegroups', $context)) { $userid = $USER->id; } else { $userid = false; } } if ($userid === false) { throw new report_ncccscensus_exception('invalidgroupid'); } if ($userid != 0) { $grouprecs = groups_get_all_groups($course->id, $userid, 0, 'g.id, g.name'); $groupnotfound = true; foreach ($grouprecs as $grouprec) { if ($grouprec->id == $group) { $groupnotfound = false; break; } } if ($groupnotfound) { throw new report_ncccscensus_exception('invalidgroupid'); } } } } $users = array(); if ($nogroups) { $users = report_ncccscensus_get_users($cid, REPORT_NCCCSCENSUS_EXCLUDE_GROUP_MEMBERS); } else { if ($group > 0) { $users = report_ncccscensus_get_users($cid, $group); } else { $users = report_ncccscensus_get_users($cid); } } $results = report_ncccscensus_build_grades_array($cid, $users, $formdata->startdate, $formdata->enddate); if (empty($results)) { return false; } if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) { $headers = array('student' => get_string('studentfullnamehtml', $reportname)); $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'html'); } else { if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) { $headers = array('student' => get_string('studentfullnamecsv', $reportname)); $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'csv'); } else { $headers = array('student' => get_string('studentfullnamepdf', $reportname)); $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf'); } } if ($showstudentid) { $headers['studentid'] = get_string('studentid', $reportname); } $headers['activity'] = get_string('activityname', $reportname); $headers['module'] = get_string('activitymodule', $reportname); $headers['status'] = get_string('submissionstatus', $reportname); $headers['datesubmitted'] = get_string('submissiondate', $reportname); $headers['grade'] = get_string('grade', $reportname); $headers['gradedate'] = get_string('gradedate', $reportname); $context = context_course::instance($cid); $namesarrayview = array(); $namesarraypdf = array(); $instructors = ' - '; $viewlink = ': <a href="' . $CFG->wwwroot . '/user/view.php?id='; if (!empty($CFG->coursecontact)) { $coursecontactroles = explode(',', $CFG->coursecontact); sort($coursecontactroles); // If a user has multiple roles, we do not want to show user multiple times as a contact. $teachers = array(); foreach ($coursecontactroles as $roleid) { $roleid = (int) $roleid; if ($users = get_role_users($roleid, $context, true)) { $role = $DB->get_record('role', array('id' => $roleid)); $rolename = format_string(role_get_name($role, $context)); foreach ($users as $teacher) { // The $teachers array tracks whether a user is already a course contact. if (!isset($teachers[$teacher->id])) { $teachers[$teacher->id] = true; $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context)); $namesarrayview[] = $rolename . $viewlink . $teacher->id . '&course=' . SITEID . '">' . $fullname . '</a>'; $namesarraycsv[] = $rolename . ': ' . $fullname; $namesarraypdf[] = $rolename . ': ' . $fullname; } } } } } if ($type != REPORT_NCCCSCENSUS_ACTION_PDF) { if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) { // Create legend for HTML view. $legend = new html_table(); $legend->head = array(get_string('legend', $reportname)); $legend->headspan = array(2); $legendrow1colour = new html_table_cell(); $legendrow1colour->style = 'width: 50px; background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour'); $legendrow1[] = $legendrow1colour; $legendrow1[] = get_string('legendgradeoverride', $reportname); $legendrow2colour = new html_table_cell(); $legendrow2colour->style = 'width: 50px; background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour'); $legendrow2[] = $legendrow2colour; $legendrow2[] = get_string('legendnograde', $reportname); $legend->data = array($legendrow1, $legendrow2); $legendalign = array('center', 'left'); $legend->align = $legendalign; } $table = new html_table(); $table->head = $headers; $align = array('left'); $numheaders = count($headers); for ($i = 1; $i < $numheaders; $i++) { $align[] = 'center'; } $table->align = $align; $table->data = array(); foreach ($results as $result) { $datum = array(); $datum[] = $result->student; if ($showstudentid) { $datum[] = $result->studentid; } $datum[] = $result->activity; $datum[] = $result->module; $status = $result->status; $grade = $result->grade; if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) { $specialstatus = new html_table_cell($status); $specialstatus->style = 'background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour'); $status = $specialstatus; } else { if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) { $specialstatus = new html_table_cell($status); $specialstatus->style = 'background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour'); $status = $specialstatus; } } $datum[] = $status; $datum[] = $result->submitdate; if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) { $nograde = new html_table_cell($grade); $nograde->style = 'background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour'); $grade = $nograde; } else { if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) { $overriddengrade = new html_table_cell($grade); $overriddengrade->style = 'background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour'); $grade = $overriddengrade; } } $datum[] = $grade; $datum[] = $result->date; $table->data[] = $datum; } } $course = $DB->get_record('course', array('id' => $cid)); if ($group > 0) { $groupname = groups_get_group_name($group); } $datestring = 'n/j/y'; $reportrange = date($datestring, $formdata->startdate) . ' - ' . date($datestring, $formdata->enddate); if ($type != REPORT_NCCCSCENSUS_ACTION_VIEW) { $date = usergetdate(time(), get_user_timezone()); $filename = 'CensusRpt2_'; $filename .= date('MdY_Hi', mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year'])); } if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) { if (report_ncccscensus_check_field_status('showcoursename', 'html')) { echo '<b>' . get_string('coursetitle', $reportname) . ':</b> ' . $course->fullname . '<br>'; } if (report_ncccscensus_check_field_status('showcoursecode', 'html')) { echo '<b>' . get_string('coursecode', $reportname) . ':</b> ' . $course->shortname . '<br>'; } // Only show course ID if present. if (report_ncccscensus_check_field_status('showcourseid', 'html') && $course->idnumber !== '') { echo '<b>' . get_string('courseid', $reportname) . ':</b> ' . $course->idnumber . '<br>'; } if (report_ncccscensus_check_field_status('showteachername', 'html')) { if (!empty($namesarrayview)) { $instructors = implode(', ', $namesarrayview); echo '<b>' . get_string('instructor', $reportname) . ':</b> ' . $instructors . '<br>'; } } echo '<b>' . get_string('reportrange', $reportname) . ':</b> ' . $reportrange . '<br>'; if (isset($groupname)) { echo '<b>' . get_string('section', $reportname) . ':</b> ' . $groupname . '<br>'; } else { echo '<b>' . get_string('section', $reportname) . ':</b> ' . get_string('allgroupspdf', $reportname) . '<br>'; } echo '<br>'; echo html_writer::table($table); echo '<div id="studentfootnote" style="font-size:10px;">' . get_string('studentfootnote', $reportname) . '</div>'; echo '<br>'; echo html_writer::table($legend); echo '<br><div align="center"><a href="' . $CFG->wwwroot . '/report/ncccscensus/index.php?id=' . $formdata->id . '">'; echo get_string('backtoreport', 'report_ncccscensus') . '</a></div>'; } else { if ($type == REPORT_NCCCSCENSUS_ACTION_PDF) { $topheaders = array(); $topheaders['student'] = get_string('student', $reportname); $topheaders['activity'] = get_string('activity', $reportname); $topheaders['submission'] = get_string('submission', $reportname); $topheaders['grade'] = get_string('grade', $reportname); $bottomheaders = array(); $bottomheaders['student'] = array('fullname' => get_string('studentfullnamepdf', $reportname)); $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf'); if ($showstudentid) { $bottomheaders['student']['id'] = get_string('studentidpdf', $reportname); } $bottomheaders['activity'] = array('name' => get_string('activityname', $reportname), 'module' => get_string('activitymodule', $reportname)); $bottomheaders['submission'] = array('status' => get_string('submissionstatus', $reportname), 'date' => get_string('submissiondate', $reportname)); $bottomheaders['grade'] = array('grade' => get_string('grade', $reportname), 'date' => get_string('gradedatepdf', $reportname)); require_once 'report.class.php'; $censusreport = new report(); $censusreport->topheaders = $topheaders; $censusreport->bottomheaders = $bottomheaders; $censusreport->data = array(); foreach ($results as $result) { $fieldarray = array(); $fieldarray['studentfullname'] = $result->student; if ($showstudentid) { $fieldarray['studentid'] = $result->studentid; } $fieldarray['activityname'] = $result->activity; $fieldarray['activitymodule'] = $result->module; $fieldarray['submissionstatus'] = $result->status; $fieldarray['submissiondate'] = $result->submitdate; $fieldarray['gradegrade'] = $result->grade; $fieldarray['gradedate'] = $result->date; $censusreport->data[] = array('data' => $fieldarray, 'override' => $result->overridden != 0 ? true : false, 'nograde' => $result->grade == get_string('nograde', $reportname) ? true : false); } $censusreport->filename = $filename . '.pdf'; if (report_ncccscensus_check_field_status('showcoursename', 'pdf')) { $censusreport->top[] = array(get_string('coursetitlepdf', $reportname) . ':', $course->fullname); } if (report_ncccscensus_check_field_status('showcoursecode', 'pdf')) { $censusreport->top[] = array(get_string('coursecodepdf', $reportname) . ':', $course->shortname); } if (report_ncccscensus_check_field_status('showcourseid', 'pdf') && $course->idnumber !== '') { $censusreport->top[] = array(get_string('courseid', $reportname) . ':', $course->idnumber); } if (report_ncccscensus_check_field_status('showteachername', 'pdf')) { if (!empty($namesarrayview)) { $instructors = implode(', ', $namesarrayview); } $censusreport->top[] = array(get_string('instructor', $reportname) . ':', strip_tags($instructors)); } $censusreport->top[] = array(get_string('reportrangepdf', $reportname) . ':', $reportrange); if (isset($groupname)) { $censusreport->top[] = array(get_string('group', $reportname) . ':', $groupname); } else { if ($group !== false) { $censusreport->top[] = array(get_string('group', $reportname) . ':', get_string('allgroupspdf', $reportname)); } } if (report_ncccscensus_check_field_status('showsignatureline', 'pdf')) { $censusreport->signatureline = true; } if (report_ncccscensus_check_field_status('showdateline', 'pdf')) { $censusreport->dateline = true; } if ($footermessage = get_config('report_ncccscensus', 'footermessage')) { $censusreport->bottom .= $footermessage; } $censusreport->download($saveto); return true; } else { if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) { if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { header('Expires: 0'); header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, must-revalidate'); header('Connection: Keep-Alive'); header('Content-Language: ' . current_language()); header('Keep-Alive: timeout=5, max=100'); header('Pragma: no-cache'); header('Pragma: expires'); header('Expires: Mon, 20 Aug 1969 09:23:00 GMT'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); } header('Content-Transfer-Encoding: ascii'); header('Content-Disposition: attachment; filename=' . $filename . '.csv'); header('Content-Type: text/comma-separated-values'); $output = fopen('php://output', 'w'); fputcsv($output, array(get_string('ncccscensusreport_title', 'report_ncccscensus'))); fputcsv($output, array()); if (report_ncccscensus_check_field_status('showcoursename', 'csv')) { fputcsv($output, array(get_string('coursetitle', $reportname), $course->fullname)); } if (report_ncccscensus_check_field_status('showcoursecode', 'csv')) { fputcsv($output, array(get_string('coursecode', $reportname), $course->shortname)); } if (report_ncccscensus_check_field_status('showcourseid', 'csv') && $course->idnumber !== '') { fputcsv($output, array(get_string('courseid', $reportname), $course->idnumber)); } if (!empty($namesarrayview) && report_ncccscensus_check_field_status('showteachername', 'csv')) { fputcsv($output, array_merge(array(get_string('instructor', $reportname)), $namesarraycsv)); } fputcsv($output, array(get_string('reportrange', $reportname), $reportrange)); if (isset($groupname)) { fputcsv($output, array(get_string('section', $reportname), $groupname)); } else { fputcsv($output, array(get_string('section', $reportname), get_string('allgroups', $reportname))); } fputcsv($output, array()); fputcsv($output, $table->head); foreach ($table->data as $row) { fputcsv($output, $row); } $showsignatureline = report_ncccscensus_check_field_status('showsignatureline', 'csv'); $showdateline = report_ncccscensus_check_field_status('showdateline', 'csv'); if ($showsignatureline || $showdateline) { fputcsv($output, array()); if ($showsignatureline) { fputcsv($output, array(get_string('certified', $reportname))); fputcsv($output, array(get_string('signature', $reportname) . get_string('underscores', $reportname))); } if ($showdateline) { fputcsv($output, array(get_string('date') . get_string('underscores', 'report_ncccscensus'))); } } fclose($output); } } } }
/** * Download a zip file of all assignment submissions * * @return void */ private function download_submissions() { global $CFG,$DB; // More efficient to load this here. require_once($CFG->libdir.'/filelib.php'); // Load all users with submit. $students = get_enrolled_users($this->context, "mod/assign:submit"); // Build a list of files to zip. $filesforzipping = array(); $fs = get_file_storage(); $groupmode = groups_get_activity_groupmode($this->get_course_module()); // All users. $groupid = 0; $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->get_course_module(), true); $groupname = groups_get_group_name($groupid).'-'; } // Construct the zip file name. $filename = clean_filename($this->get_course()->shortname.'-'. $this->get_instance()->name.'-'. $groupname.$this->get_course_module()->id.".zip"); // Get all the files for each student. foreach ($students as $student) { $userid = $student->id; if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) { // Get the plugins to add their own files to the zip. $submissiongroup = false; $groupname = ''; if ($this->get_instance()->teamsubmission) { $submission = $this->get_group_submission($userid, 0, false); $submissiongroup = $this->get_submission_group($userid); $groupname = '-' . $submissiongroup->name; } else { $submission = $this->get_user_submission($userid, false); } if ($this->is_blind_marking()) { $prefix = clean_filename(str_replace('_', ' ', get_string('participant', 'assign') . $groupname) . "_" . $this->get_uniqueid_for_user($userid) . "_"); } else { $prefix = clean_filename(str_replace('_', ' ', fullname($student) . $groupname) . "_" . $this->get_uniqueid_for_user($userid) . "_"); } if ($submission) { foreach ($this->submissionplugins as $plugin) { if ($plugin->is_enabled() && $plugin->is_visible()) { $pluginfiles = $plugin->get_files($submission); foreach ($pluginfiles as $zipfilename => $file) { $subtype = $plugin->get_subtype(); $type = $plugin->get_type(); $prefixedfilename = $prefix . $subtype . '_' . $type . '_' . $zipfilename; $filesforzipping[$prefixedfilename] = $file; } } } } } } if ($zipfile = $this->pack_files($filesforzipping)) { $this->add_to_log('download all submissions', get_string('downloadall', 'assign')); // Send file and delete after sending. send_temp_file($zipfile, $filename); } }
if ($id == $groupid) { $grouplist = get_string('subscribedthisgroup', 'forumng'); break; } } } else { $numberofdiscussions = count($user->discussionids); if ($numberofdiscussions > 0) { $numberofdiscussions = ($numberofdiscussions == 1 ? get_string("numberofdiscussion", "forumng", $numberofdiscussions) : get_string("numberofdiscussions", "forumng", $numberofdiscussions)) . '<br />'; } else { $numberofdiscussions = ''; } $grouplist = ''; if (count($user->groupids)) { foreach ($user->groupids as $id) { $grouplist .= groups_get_group_name($id) . '<br />'; } } } $row[] = $numberofdiscussions . $grouplist; } if ($user->link) { $table->data[] = $row; } } print html_writer::table($table); if ($canmanage) { if ($gotsome) { print '<div id="forumng-buttons"><input type="submit" ' . 'name="unsubscribe" value="' . get_string('unsubscribeselected', 'forumng') . '" /></div>'; } print '</div></form>';
/** * * @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=\"\" />"; } } }
$PAGE->set_heading(format_string($course->fullname)); echo $questionnaire->renderer->header(); // Print the tabs. if ($byresponse) { $SESSION->questionnaire->current_tab = 'vrespsummary'; } if ($individualresponse) { $SESSION->questionnaire->current_tab = 'individualresp'; } include 'tabs.php'; // Print the main part of the page. // TODO provide option to select how many columns and/or responses per page. if ($noresponses) { $questionnaire->page->add_to_page('respondentinfo', get_string('group') . ' <strong>' . groups_get_group_name($currentgroupid) . '</strong>: ' . get_string('noresponses', 'questionnaire')); } else { $groupname = get_string('group') . ': <strong>' . groups_get_group_name($currentgroupid) . '</strong>'; if ($currentgroupid == 0) { $groupname = get_string('allparticipants'); } if ($byresponse) { $respinfo = ''; $respinfo .= $questionnaire->renderer->box_start(); $respinfo .= $questionnaire->renderer->help_icon('viewindividualresponse', 'questionnaire') . ' '; $respinfo .= get_string('viewindividualresponse', 'questionnaire') . ' <strong> : ' . $groupname . '</strong>'; $respinfo .= $questionnaire->renderer->box_end(); $questionnaire->page->add_to_page('respondentinfo', $respinfo); } $questionnaire->survey_results_navbar_alpha($rid, $currentgroupid, $cm, $byresponse); if (!$byresponse) { // Show respondents individual responses. $questionnaire->view_response($rid, $referer = '', $blankquestionnaire = false, $resps, $compare = true, $isgroupmember = true, $allresponses = false, $currentgroupid);
/** * This function returns sensible filename for a feedback file. * @param int|\assign $assignment * @param int $userid * @param int $attemptnumber (-1 means latest attempt) * @return string */ protected static function get_downloadable_feedback_filename($assignment, $userid, $attemptnumber) { global $DB; $assignment = self::get_assignment_from_param($assignment); $groupmode = groups_get_activity_groupmode($assignment->get_course_module()); $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($assignment->get_course_module(), true); $groupname = groups_get_group_name($groupid) . '-'; } if ($groupname == '-') { $groupname = ''; } $grade = $assignment->get_user_grade($userid, true, $attemptnumber); $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST); if ($assignment->is_blind_marking()) { $prefix = $groupname . get_string('participant', 'assign'); $prefix = str_replace('_', ' ', $prefix); $prefix = clean_filename($prefix . '_' . $assignment->get_uniqueid_for_user($userid) . '_'); } else { $prefix = $groupname . fullname($user); $prefix = str_replace('_', ' ', $prefix); $prefix = clean_filename($prefix . '_' . $assignment->get_uniqueid_for_user($userid) . '_'); } $prefix .= $grade->attemptnumber; return $prefix . '.pdf'; }
/** * Update workshopplus grades in the gradebook * * Needed by grade_update_mod_grades() in lib/gradelib.php * * @category grade * @param stdClass $workshopplus instance object with extra cmidnumber and modname property * @param int $userid update grade of specific user only, 0 means all participants * @return void */ function workshopplus_update_grades(stdclass $workshopplus, $userid = 0) { global $CFG, $DB; require_once $CFG->libdir . '/gradelib.php'; $whereuser = $userid ? ' AND authorid = :userid' : ''; $params = array('workshopplusid' => $workshopplus->id, 'userid' => $userid); $sql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded FROM {workshopplus_submissions} WHERE workshopplusid = :workshopplusid AND example=0' . $whereuser; $records = $DB->get_records_sql($sql, $params); $submissiongrades = array(); foreach ($records as $record) { $grade = new stdclass(); $grade->userid = $record->authorid; if (!is_null($record->gradeover)) { $grade->rawgrade = grade_floatval($workshopplus->grade * $record->gradeover / 100); $grade->usermodified = $record->gradeoverby; } else { $grade->rawgrade = grade_floatval($workshopplus->grade * $record->grade / 100); } $grade->feedback = $record->feedbackauthor; $grade->feedbackformat = $record->feedbackauthorformat; $grade->datesubmitted = $record->timemodified; $grade->dategraded = $record->timegraded; $submissiongrades[$record->authorid] = $grade; ////// Find the groupmates and also update their records ////////////By Morteza /// find the group id of the current user $usergroups = groups_get_user_groups($workshopplus->course, $grade->userid); $currentgroupid = $usergroups[0][0]; // Get the current group name from the group id. $currentgroupname = groups_get_group_name($currentgroupid); // loop over members of that group $groupmembers = groups_get_members($currentgroupid, $fields = 'u.*'); /* Commenting out section for blind copy of grades * -- Sayantan - 28.04.2015 foreach ($groupmembers as $memberid=>$member){ if ($memberid != $grade->userid) { $newgrade = clone $grade; $newgrade->userid = $memberid; $submissiongrades[$memberid] = $newgrade; } } */ //////////end by Morteza /* * Begin: Change by Sayantan * Date: 28.04.2015 */ // Also think of scenario where author belonged to another group - Not possible unless students are // allowed to resubmit their solutions - have to think about this one // Check if this assignment has been graded previously (entry exists in grade_grades) // no -> this is a new grading, simply copy grade of author to the group members // yes -> this is a regrading $params = array('workshopplusid' => $workshopplus->id, 'userid' => $grade->userid); $sql = 'SELECT COUNT(1) AS cnt FROM moodle_grade_grades grades ' . 'INNER JOIN moodle_grade_items items ' . 'WHERE items.id = grades.itemid AND items.iteminstance = :workshopplusid AND grades.userid=:userid'; $records = $DB->get_records_sql($sql, $params); $flag_re_grading = 0; foreach ($records as $record) { if ($record->cnt > 0) { // Check if records exist in grade_grades $flag_re_grading = 1; // If records exist in grade_grades then this is a regrading } } if ($flag_re_grading == 0) { // This is a new grading, hence copy grades foreach ($groupmembers as $memberid => $member) { if ($memberid != $grade->userid) { $newgrade = clone $grade; $newgrade->userid = $memberid; $submissiongrades[$memberid] = $newgrade; } } } else { // This is a re grading, hence existing grades should not be overwritten // + Check the time in which each member joined the group // + If the time of joining group is later than time of previous grading then member was in a // separate group when the initial grading was done and should get the grades he/she received // in that group // + If the member has no previous records - assign zero grade since this assignment was not // done by that member (as he was not part of any group when the assignment was first graded) // foreach ($groupmembers as $memberid => $member) { if ($memberid != $grade->userid) { // Check time at which $memberid joined the group $joining_time = 0; $params = array('userid' => $memberid); $sql = 'SELECT timeadded FROM moodle_groups_members WHERE userid=:userid'; $records = $DB->get_records_sql($sql, $params); foreach ($records as $record) { $joining_time = $record->timeadded; } // Check time of previous grading $grading_modified_time = 0; $params = array('workshopplusid' => $workshopplus->id, 'userid' => $memberid); $sql = 'SELECT grades.timemodified FROM moodle_grade_grades grades INNER JOIN moodle_grade_items items WHERE items.id = grades.itemid AND items.iteminstance=:workshopplusid AND grades.userid=:userid'; $records = $DB->get_records_sql($sql, $params); // If no records are fetched then for the particular group member there exist no records in grades // This means that when the previous grading was done this member was not part of any group // and the grade assigned should be 0 if (sizeof($records) == 0) { $newgrade = clone $grade; $newgrade->userid = $memberid; $grade->rawgrade = 0; // Grade assigned to zero since this member was not present when previous grading was done $submissiongrades[$memberid] = $newgrade; } else { foreach ($records as $record) { $grading_modified_time = $record->timemodified; } } // If records exist for the member in grades, and time of joining group is before time of previous grading // then a simple copy of grades from the author's grades is okay if (sizeof($records) < 0 && $grading_modified_time > $joining_time) { $newgrade = clone $grade; // Copy grade since member was in authors group earlier also $newgrade->userid = $memberid; $submissiongrades[$memberid] = $newgrade; } // If record exists for the member in grade but time of joining group is after time of last grading // then we need to restore the previous grade that this member achieved if (sizeof($records) < 0 && $grading_modified_time < $joining_time) { // This member has already received a grade for this assignment // but the member was in another group // hence leave the previous grade untouched // do not add this grade in the array $submissiongrades // Thus in the grades table, the old grade for this member will remain unchanged // Need to recalculate grades from the workshopplus submission of previous group // the member belonged to // Check the group history table // Find a group with max(timeadded) < $grading_modified_time $params = array('grading_modified_time' => $grading_modified_time, 'userid' => $memberid); $sql = 'SELECT groupid FROM moodle_groups_members_history a WHERE userid=:userid AND timeadded=(SELECT MAX(timeadded) FROM moodle_groups_members_history b WHERE a.userid=b.userid AND a.groupid=b.groupid AND b.timeadded<:grading_modified_time)'; $records = $DB->get_records_sql($sql, $params); // Find members of this group foreach ($records as $record) { $groupid = $records->groupid; } // loop over members of that group $groupmembers = groups_get_members($groupid, $fields = 'u.*'); // Iterate over members to find submission for the given workshopplus id foreach ($groupmembers as $oldmemberid => $oldmember) { // Find submission for this group in workshopplus_submissions $oldparams = array('workshopplusid' => $workshopplus->id, 'userid' => $oldmemberid); $oldsql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded FROM {workshopplus_submissions} WHERE workshopplusid = :workshopplusid AND example=0 AND authorid=:userid ORDER BY timemodified DESC'; $oldrecords = $DB->get_records_sql($oldsql, $oldparams); // Break whenever a submission is found for a member if (sizeof($records != 0)) { // Copy grade for this user $oldgrade = new stdclass(); $oldgrade->userid = $memberid; if (!is_null($oldrecords->gradeover)) { $oldgrade->rawgrade = grade_floatval($workshopplus->grade * $oldrecords->gradeover / 100); $oldgrade->usermodified = $oldrecords->gradeoverby; } else { $oldgrade->rawgrade = grade_floatval($workshopplus->grade * $oldrecords->grade / 100); } $oldgrade->feedback = $oldrecords->feedbackauthor; $oldgrade->feedbackformat = $oldrecords->feedbackauthorformat; $oldgrade->datesubmitted = $oldrecords->timemodified; $oldgrade->dategraded = $oldrecords->timegraded; $submissiongrades[$memberid] = $oldgrade; break; } } } } } } /* * End: Change by Sayantan * Date: 28.04.2015 */ } // Updating assessment grades -- only comment added -- no change to code $whereuser = $userid ? ' AND userid = :userid' : ''; $params = array('workshopplusid' => $workshopplus->id, 'userid' => $userid); $sql = 'SELECT userid, gradinggrade, timegraded FROM {workshopplus_aggregations} WHERE workshopplusid = :workshopplusid' . $whereuser; $records = $DB->get_records_sql($sql, $params); $assessmentgrades = array(); foreach ($records as $record) { $grade = new stdclass(); $grade->userid = $record->userid; $grade->rawgrade = grade_floatval($workshopplus->gradinggrade * $record->gradinggrade / 100); $grade->dategraded = $record->timegraded; $assessmentgrades[$record->userid] = $grade; } workshopplus_grade_item_update($workshopplus, $submissiongrades, $assessmentgrades); }
echo json_encode($editable); die; } // Use an array to wrap the response data. $response = array(); $response[] = $editable; // Create a new object to store the annotation data. $annotation = new stdClass(); $annotation->id = 0; // This will be changed by the DB. $annotation->userid = $USER->id; $annotation->annotation = htmlentities($_POST['text']); $annotation->shapes = json_encode($_POST['shapes']); $annotation->url = $_POST['url']; $annotation->timecreated = time(); $annotation->tags = htmlentities($_POST['tags']); $annotation->group_id = $group; $table = "annotation_image"; // Insert into DB and get the id. $lastinsertid = $DB->insert_record($table, $annotation); $annotation->id = $lastinsertid; $annotation->username = $USER->firstname . " " . $USER->lastname; $annotation->groupname = groups_get_group_name($group); // Returns the data to the client for processing. // TODO waste of data transfer, only return what is required. // E.g. id, username, timecreated... $response[] = $annotation; echo json_encode($response); } else { http_response_code(400); }
/** * Download a zip file of all assignment submissions. * * @param array $userids Array of user ids to download assignment submissions in a zip file * @return string - If an error occurs, this will contain the error page. */ protected function download_submissions($userids = false) { global $CFG, $DB; // More efficient to load this here. require_once($CFG->libdir.'/filelib.php'); // Increase the server timeout to handle the creation and sending of large zip files. core_php_time_limit::raise(); $this->require_view_grades(); // Load all users with submit. $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null, $this->show_only_active_users()); // Build a list of files to zip. $filesforzipping = array(); $fs = get_file_storage(); $groupmode = groups_get_activity_groupmode($this->get_course_module()); // All users. $groupid = 0; $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->get_course_module(), true); $groupname = groups_get_group_name($groupid).'-'; } // Construct the zip file name. $filename = clean_filename($this->get_course()->shortname . '-' . $this->get_instance()->name . '-' . $groupname.$this->get_course_module()->id . '.zip'); // Get all the files for each student. foreach ($students as $student) { $userid = $student->id; // Download all assigments submission or only selected users. if ($userids and !in_array($userid, $userids)) { continue; } if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) { // Get the plugins to add their own files to the zip. $submissiongroup = false; $groupname = ''; if ($this->get_instance()->teamsubmission) { $submission = $this->get_group_submission($userid, 0, false); $submissiongroup = $this->get_submission_group($userid); if ($submissiongroup) { $groupname = $submissiongroup->name . '-'; } else { $groupname = get_string('defaultteam', 'assign') . '-'; } } else { $submission = $this->get_user_submission($userid, false); } if ($this->is_blind_marking()) { $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign')); $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid)); } else { $prefix = str_replace('_', ' ', $groupname . fullname($student)); $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid)); } if ($submission) { $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1); foreach ($this->submissionplugins as $plugin) { if ($plugin->is_enabled() && $plugin->is_visible()) { if ($downloadasfolders) { // Create a folder for each user for each assignment plugin. // This is the default behavior for version of Moodle >= 3.1. $submission->exportfullpath = true; $pluginfiles = $plugin->get_files($submission, $student); foreach ($pluginfiles as $zipfilepath => $file) { $subtype = $plugin->get_subtype(); $type = $plugin->get_type(); $zipfilename = basename($zipfilepath); $prefixedfilename = clean_filename($prefix . '_' . $subtype . '_' . $type . '_'); if ($type == 'file') { $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename; } else if ($type == 'onlinetext') { $pathfilename = $prefixedfilename . '/' . $zipfilename; } else { $pathfilename = $prefixedfilename . '/' . $zipfilename; } $pathfilename = clean_param($pathfilename, PARAM_PATH); $filesforzipping[$pathfilename] = $file; } } else { // Create a single folder for all users of all assignment plugins. // This was the default behavior for version of Moodle < 3.1. $submission->exportfullpath = false; $pluginfiles = $plugin->get_files($submission, $student); foreach ($pluginfiles as $zipfilename => $file) { $subtype = $plugin->get_subtype(); $type = $plugin->get_type(); $prefixedfilename = clean_filename($prefix . '_' . $subtype . '_' . $type . '_' . $zipfilename); $filesforzipping[$prefixedfilename] = $file; } } } } } } } $result = ''; if (count($filesforzipping) == 0) { $header = new assign_header($this->get_instance(), $this->get_context(), '', $this->get_course_module()->id, get_string('downloadall', 'assign')); $result .= $this->get_renderer()->render($header); $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign')); $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'grading')); $result .= $this->get_renderer()->continue_button($url); $result .= $this->view_footer(); } else if ($zipfile = $this->pack_files($filesforzipping)) { \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger(); // Send file and delete after sending. send_temp_file($zipfile, $filename); // We will not get here - send_temp_file calls exit. } return $result; }
} if ($signout and $hasgroup) { require_once 'signout_form.php'; $mform = new signout_form(null, $groupselect); $data = array('id' => $id, 'signout' => $signout); $mform->set_data($data); if ($mform->is_cancelled()) { //nothing } else { if ($mform->get_data(false)) { require_once "{$CFG->dirroot}/group/lib.php"; if (!isset($groups[$signout])) { print_error("Incorrect group id!"); } groups_remove_member($signout, $USER->id); add_to_log($course->id, 'groupselect', 'signout', "view.php?id={$cm->id}", groups_get_group_name($signout), $cm->id, $USER->id); redirect("{$CFG->wwwroot}/mod/groupselect/view.php?id={$cm->id}"); } else { echo $OUTPUT->header(); echo $OUTPUT->box(get_string('signoutconfirm', 'groupselect', format_string($groups[$signout]->name))); $mform->display(); echo $OUTPUT->footer(); die; } } } echo $OUTPUT->header(); if ($manage) { echo '<div class="managelink"><a href="' . "{$CFG->wwwroot}/group/index.php?id={$course->id}" . '">' . get_string('managegroups', 'groupselect') . '</a></div>'; $currenttab = 'view'; include $CFG->dirroot . '/mod/groupselect/tabs.php';
/** * creates a zip of all assignment submissions and sends a zip to the browser */ public function download_submissions() { global $CFG,$DB; require_once($CFG->libdir.'/filelib.php'); $submissions = $this->get_submissions('',''); if (empty($submissions)) { print_error('errornosubmissions', 'assignment', new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id))); } $filesforzipping = array(); $fs = get_file_storage(); $groupmode = groups_get_activity_groupmode($this->cm); $groupid = 0; // All users $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->cm, true); $groupname = groups_get_group_name($groupid).'-'; } $filename = str_replace(' ', '_', clean_filename($this->course->shortname.'-'.$this->assignment->name.'-'.$groupname.$this->assignment->id.".zip")); //name of new zip file. foreach ($submissions as $submission) { // If assignment is open and submission is not finalized then don't add it to zip. $submissionstatus = $this->is_finalized($submission); if ($this->isopen() && empty($submissionstatus)) { continue; } $a_userid = $submission->userid; //get userid if ((groups_is_member($groupid,$a_userid)or !$groupmode or !$groupid)) { $a_assignid = $submission->assignment; //get name of this assignment for use in the file names. $a_user = $DB->get_record("user", array("id"=>$a_userid),'id,username,firstname,lastname'); //get user firstname/lastname $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false); foreach ($files as $file) { //get files new name. $fileext = strstr($file->get_filename(), '.'); $fileoriginal = str_replace($fileext, '', $file->get_filename()); $fileforzipname = clean_filename(fullname($a_user) . "_" . $fileoriginal."_".$a_userid.$fileext); //save file name to array for zipping. $filesforzipping[$fileforzipname] = $file; } } } // end of foreach loop // Throw error if no files are added. if (empty($filesforzipping)) { print_error('errornosubmissions', 'assignment', new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id))); } if ($zipfile = assignment_pack_files($filesforzipping)) { send_temp_file($zipfile, $filename); //send file and delete after sending. } }
function referentiel_print_graph_certificats($referentiel_instance, $referentiel_referentiel, $gusers, $currentgroup = 0) { global $DB; global $CFG; global $USER; // contexte $cm = get_coursemodule_from_instance('referentiel', $referentiel_instance->id); $course = $DB->get_record('course', array('id' => $cm->course)); if (empty($cm) or empty($course)) { print_error('REFERENTIEL_ERROR 5 :: print_lib_certificat.php :: You cannot call this script in that way'); } $context = context_module::instance($cm->id); $roles = referentiel_roles_in_instance($referentiel_instance->id); $iseditor = $roles->is_editor; $isadmin = $roles->is_admin; $isteacher = $roles->is_teacher; $istutor = $roles->is_tutor; $isstudent = $roles->is_student; $isguest = $roles->is_guest; // codes item $liste_codes = referentiel_purge_dernier_separateur($referentiel_referentiel->liste_codes_competence, '/'); // empreintes $liste_empreintes = referentiel_purge_dernier_separateur($referentiel_referentiel->liste_empreintes_competence, '/'); // poids $liste_poids = referentiel_purge_dernier_separateur($referentiel_referentiel->liste_poids_competence, '/'); // cours ? if (!empty($course)) { $course_name = $course->shortname; } else { $course_name = ""; } // groupes ? if (!empty($currentgroup)) { $group_name = groups_get_group_name($currentgroup); } else { $group_name = ""; } $titre = get_string('certification_etat', 'referentiel'); if (!empty($course_name)) { $titre .= ' (' . $course_name; if (!empty($group_name)) { $titre .= ' - ' . $group_name; } $titre .= ')'; } $titre = str_replace(' ', '_', $titre); // utilisateurs $record_id_users = referentiel_get_students_course($course->id, 0, 0); //seulement les stagiaires // groupes ? if ($gusers && $record_id_users) { $record_users = array_intersect($gusers, array_keys($record_id_users)); // recopier $record_id_users = array(); foreach ($record_users as $record_id) { $a_obj = new stdClass(); $a_obj->userid = $record_id; $record_id_users[] = $a_obj; } } if ($record_id_users) { // Afficher foreach ($record_id_users as $record_id) { // afficher la liste d'users // recupere les enregistrements de certificats ou les cree si necessaire $records_c[] = referentiel_certificat_user($record_id->userid, $referentiel_referentiel->id); } if ($records_c) { // Let's get the datas $separateur1 = '/'; $separateur2 = ':'; $separateur3 = '|'; $t_user = array(); // tableau des userid $t_code = explode($separateur1, $liste_codes); $t_empreinte = explode($separateur1, $liste_empreintes); $t_poids = explode($separateur1, $liste_poids); $moyennes = array(); $t_valides = array(array()); // $t_declarees = array(array()); $user_name_souligne = ""; foreach ($records_c as $record_c) { // pour tous les certificats if ($record_c) { $certificat_id = $record_c->id; $commentaire_certificat = stripslashes($record_c->commentaire_certificat); $synthese_certificat = stripslashes($record_c->synthese_certificat); $competences_certificat = $record_c->competences_certificat; $competences_activites = $record_c->competences_activite; $decision_jury = stripslashes($record_c->decision_jury); $date_decision = $record_c->date_decision; $ref_referentiel = $record_c->ref_referentiel; $user_id = $record_c->userid; $teacherid = $record_c->teacherid; $verrou = $record_c->verrou; $dossier_ferme = $record_c->valide; $evaluation = $record_c->evaluation; $user_name = referentiel_get_user_nom($user_id) . ' ' . referentiel_get_user_prenom($user_id); $user_info = referentiel_get_user_info($user_id); $teacher_info = referentiel_get_user_info($teacherid); // dates $date_decision_info = userdate($date_decision); //$t_user[]=$user_name; $t_user[] = $user_id; // competences validees dans le certificat $tc = array(); $lcc = referentiel_purge_dernier_separateur($competences_certificat, $separateur1); if (!empty($lcc)) { $tc = explode($separateur1, $lcc); // A.1.1:1 A.1.2:1 A.1.3:1 A.1.4:0/A.1.5:0/A.2.1:1/A.2.2:0/A.2.3:0/A.3.1:0/A.3.2:0/A.3.3:0/A.3.4:0/B.1.1:0/B.1.2:0/B.1.3:0/B.2.1:1/B.2.2:1/B.2.3:0/B.2.4:0/B.3.1:0/B.3.2:0/B.3.3:0/B.3.4:0/B.3.5:0/B.4.1:0/B.4.2:0/B.4.3:0/ $i = 0; while ($i < count($tc)) { // CODE1:N1 // DEBUG // echo "<br />".$tc[$i]." <br />\n"; if ($tc[$i] != '') { $tcc = explode($separateur2, $tc[$i]); // A.1.1 1 if (isset($tcc[1])) { // $t_valides[$userid][]=$tcc[1]; //$t_valides[$user_name][]=min($tcc[1], $t_empreinte[$i]) ; $t_valides[$user_id][] = min($tcc[1], $t_empreinte[$i]); } } $i++; } } /* // competences declarees dans les activites $tc=array(); $lcd=referentiel_purge_dernier_separateur($competences_activites, $separateur1); if (!empty($lcd)){ $tc = explode ($separateur1, $lcd); // A.1.1:1 A.1.2:1 A.1.3:1 A.1.4:0/A.1.5:0/A.2.1:1/A.2.2:0/A.2.3:0/A.3.1:0/A.3.2:0/A.3.3:0/A.3.4:0/B.1.1:0/B.1.2:0/B.1.3:0/B.2.1:1/B.2.2:1/B.2.3:0/B.2.4:0/B.3.1:0/B.3.2:0/B.3.3:0/B.3.4:0/B.3.5:0/B.4.1:0/B.4.2:0/B.4.3:0/ $i=0; while ($i<count($tc)){ // CODE1:N1 // DEBUG // echo "<br />".$tc[$i]." <br />\n"; // exit; if ($tc[$i]!=''){ $tcc=explode($separateur2, $tc[$i]); // A.1.1 1 if (isset($tcc[1])){ $t_declarees[$user_name][]=$tcc[1]; } } $i++; } } */ } } // calculer la moyenne $n = 0; for ($i = 0; $i < count($t_user); $i++) { //$valeurs=$t_valides[$t_user[$i]]; // moyenne $n++; $moyennes = referentiel_somme_valeur($moyennes, $t_valides[$t_user[$i]]); } $moyennes = referentiel_quotient_valeur($moyennes, $n); $lmoyennes = implode("/", $moyennes); // Distribuer les data sur plusieurs images // pagination $page0 = 0; $page1 = 0; $nbuser = count($t_user); $page = 0; $pagemax = min($nbuser, MAXLIGNEGRAPH); $npages = (int) ($nbuser / $pagemax); $reste = (int) ($nbuser % $pagemax); if ($reste) { $npages++; } /* // DEBUG echo "<br />DEBUG :: 1858 :: CODE<br />\n"; print_r($t_code); echo "<br /> EMPREINTES<br />\n"; print_r($t_empreinte); echo "<br /> POIDS<br />\n"; print_r($t_poids); echo "<br />DEBUG :: 1858 :: USERS<br />\n"; print_r($t_user); echo "<br />COMPETENCES VALIDES<br />\n"; for ($i=0; $i<$nbuser; $i++){ echo "<br />User:"******" <br />\n"; print_r($t_valides[$t_user[$i]]); } */ // echo "<br />NBUSER: $nbuser NBPAGES: $npages PAGEMAX: $pagemax\n"; for ($page = 0; $page < $npages; $page++) { // preparer les donnees $t_data = array(array()); $j = 0; for ($j = 0; $j < $pagemax; $j++) { if (isset($t_user[$page * $pagemax + $j])) { $user_name = referentiel_get_user_nom($t_user[$page * $pagemax + $j]) . ' ' . referentiel_get_user_prenom($t_user[$page * $pagemax + $j]); $t_data[$user_name] = $t_valides[$t_user[$page * $pagemax + $j]]; } } // DEBUG //echo "<br />DEBUG :: 1876 :: DATA<br />\n"; //print_r($t_data); //echo "<br />DEBUG :: 1885 :: DATA<br />\n"; $ltdata = ""; foreach ($t_data as $key => $data) { if ($data) { //echo "<br />$key<br />\n"; //print_r($data); $ldata = implode("/", $data); $ltdata .= "{$key}:{$ldata}|"; } } // Afficher //echo '<br />DATA ->'.$ltdata."\n"; $num_page = $page + 1; if ($isteacher || $istutor || $isadmin) { $affichage_complet = 1; } else { $affichage_complet = 0; } //echo "<br />AFFCOMPLET : $affichage_complet\n"; //redirect ($CFG->wwwroot.'/mod/referentiel/graph_certificats.php?d='.$referentiel_instance->id.'&ltdata='.$ltdata.'&lmoyennes='.$lmoyennes.'&lcode='.$liste_codes.'&lempreinte='.$liste_empreintes.'&lpoids='.$liste_poids.'&affcomplet='.$affichage_complet.'&titre='.$titre.'&page='.$num_page.'&npages='.$npages); echo '<div align="center"><img src="' . $CFG->wwwroot . '/mod/referentiel/graph_certificats.php?d=' . $referentiel_instance->id . '&ltdata=' . $ltdata . '&lmoyennes=' . $lmoyennes . '&lcode=' . $liste_codes . '&lempreinte=' . $liste_empreintes . '&lpoids=' . $liste_poids . '&affcomplet=' . $affichage_complet . '&titre=' . $titre . '&page=' . $num_page . '&npages=' . $npages . '" border="0" title="' . get_string('statcertif', 'referentiel') . '" /></div>' . "\n"; echo '<br />' . "\n"; } } } }
/** * Download a marking worksheet * * @return string The response html */ public function download_grades() { global $CFG; require_capability('mod/assign:grade', $this->assignment->get_context()); require_once $CFG->dirroot . '/mod/assign/gradingtable.php'; $groupmode = groups_get_activity_groupmode($this->assignment->get_course_module()); // All users. $groupid = 0; $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->assignment->get_course_module(), true); $groupname = groups_get_group_name($groupid) . '-'; } $filename = clean_filename(get_string('offlinegradingworksheet', 'assignfeedback_offline') . '-' . $this->assignment->get_course()->shortname . '-' . $this->assignment->get_instance()->name . '-' . $groupname . $this->assignment->get_course_module()->id); $table = new assign_grading_table($this->assignment, 0, '', 0, false, $filename); $table->out(0, false); return; }
public function response_analysis($rid, $resps, $compare, $isgroupmember, $allresponses, $currentgroupid) { global $DB, $CFG, $OUTPUT, $SESSION, $USER; $action = optional_param('action', 'vall', PARAM_ALPHA); require_once $CFG->libdir . '/tablelib.php'; require_once $CFG->dirroot . '/mod/questionnaire/drawchart.php'; if ($resp = $DB->get_record('questionnaire_response', array('id' => $rid))) { $userid = $resp->username; if ($user = $DB->get_record('user', array('id' => $userid))) { $ruser = fullname($user); } } // Available group modes (0 = no groups; 1 = separate groups; 2 = visible groups). $groupmode = groups_get_activity_groupmode($this->cm, $this->course); $groupname = get_string('allparticipants'); if ($groupmode > 0) { if ($currentgroupid > 0) { $groupname = groups_get_group_name($currentgroupid); } else { $groupname = get_string('allparticipants'); } } if ($this->survey->feedbackscores) { $table = new html_table(); $table->size = array(null, null); $table->align = array('left', 'right', 'right'); $table->head = array(); $table->wrap = array(); if ($compare) { $table->head = array(get_string('feedbacksection', 'questionnaire'), $ruser, $groupname); } else { $table->head = array(get_string('feedbacksection', 'questionnaire'), $groupname); } } $feedbacksections = $this->survey->feedbacksections; $feedbackscores = $this->survey->feedbackscores; $sid = $this->survey->id; $questions = $this->questions; // Find if there are any feedbacks in this questionnaire. $sql = "SELECT * FROM {questionnaire_fb_sections} WHERE survey_id = {$sid} AND section IS NOT NULL"; if (!($fbsections = $DB->get_records_sql($sql))) { return null; } $fbsectionsnb = array_keys($fbsections); // Calculate max score per question in questionnaire. $qmax = array(); $totalscore = 0; $maxtotalscore = 0; foreach ($questions as $question) { $qid = $question->id; $qtype = $question->type_id; $required = $question->required; if (($qtype == QUESRADIO || $qtype == QUESDROP || $qtype == QUESRATE) && $required == 'y') { if (!isset($qmax[$qid])) { $qmax[$qid] = 0; } $nbchoices = 1; if ($qtype == QUESRATE) { $nbchoices = 0; } foreach ($question->choices as $choice) { // Testing NULL and 'NULL' because I changed the automatic null value, must be fixed later... TODO. if (isset($choice->value) && $choice->value != null && $choice->value != 'NULL') { if ($choice->value > $qmax[$qid]) { $qmax[$qid] = $choice->value; } } else { $nbchoices++; } } $qmax[$qid] = $qmax[$qid] * $nbchoices; $maxtotalscore += $qmax[$qid]; } if ($qtype == QUESYESNO && $required == 'y') { $qmax[$qid] = 1; $maxtotalscore += 1; } } // Just in case no values have been entered in the various questions possible answers field. if ($maxtotalscore === 0) { return; } $feedbackmessages = array(); // Get individual scores for each question in this responses set. $qscore = array(); $allqscore = array(); // Get all response ids for all respondents. $castsql = $DB->sql_cast_char2int('r.username'); $rids = array(); foreach ($resps as $key => $resp) { $rids[] = $key; } $nbparticipants = count($rids); if (!$allresponses && $groupmode != 0) { $nbparticipants = max(1, $nbparticipants - !$isgroupmember); } foreach ($rids as $rrid) { // Get responses for bool (Yes/No). $sql = 'SELECT q.id, q.type_id as q_type, a.choice_id as cid ' . 'FROM {questionnaire_response_bool} a, {questionnaire_question} q ' . 'WHERE a.response_id = ? AND a.question_id=q.id '; if ($responses = $DB->get_records_sql($sql, array($rrid))) { foreach ($responses as $qid => $response) { $responsescore = $response->cid == 'y' ? 1 : 0; // Individual score. // If this is current user's response OR if current user is viewing another group's results. if ($rrid == $rid || $allresponses) { if (!isset($qscore[$qid])) { $qscore[$qid] = 0; } $qscore[$qid] = $responsescore; } // Course score. if (!isset($allqscore[$qid])) { $allqscore[$qid] = 0; } // Only add current score if conditions below are met. if ($groupmode == 0 || $isgroupmember || !$isgroupmember && $rrid != $rid || $allresponses) { $allqscore[$qid] += $responsescore; } } } // Get responses for single (Radio or Dropbox). $sql = 'SELECT q.id, q.type_id as q_type, c.content as ccontent,c.id as cid, c.value as score ' . 'FROM {questionnaire_resp_single} a, {questionnaire_question} q, {questionnaire_quest_choice} c ' . 'WHERE a.response_id = ? AND a.question_id=q.id AND a.choice_id=c.id '; if ($responses = $DB->get_records_sql($sql, array($rrid))) { foreach ($responses as $qid => $response) { // Individual score. // If this is current user's response OR if current user is viewing another group's results. if ($rrid == $rid || $allresponses) { if (!isset($qscore[$qid])) { $qscore[$qid] = 0; } $qscore[$qid] = $response->score; } // Course score. if (!isset($allqscore[$qid])) { $allqscore[$qid] = 0; } // Only add current score if conditions below are met. if ($groupmode == 0 || $isgroupmember || !$isgroupmember && $rrid != $rid || $allresponses) { $allqscore[$qid] += $response->score; } } } // Get responses for response_rank (Rate). $sql = 'SELECT a.id as aid, q.id AS qid, c.id AS cid, a.rank as arank ' . 'FROM {questionnaire_response_rank} a, {questionnaire_question} q, {questionnaire_quest_choice} c ' . 'WHERE a.response_id= ? AND a.question_id=q.id AND a.choice_id=c.id ' . 'ORDER BY aid, a.question_id,c.id'; if ($responses = $DB->get_records_sql($sql, array($rrid))) { // We need to store the number of sub-questions for each rate questions. $rank = array(); $firstcid = array(); foreach ($responses as $response) { $qid = $response->qid; $rank = $response->arank; if (!isset($qscore[$qid])) { $qscore[$qid] = 0; $allqscore[$qid] = 0; } $firstcid[$qid] = $DB->get_record('questionnaire_quest_choice', array('question_id' => $qid), 'id', IGNORE_MULTIPLE); $firstcidid = $firstcid[$qid]->id; $cidvalue = $firstcidid + $rank; $sql = "SELECT * FROM {questionnaire_quest_choice} WHERE id = {$cidvalue}"; if ($value = $DB->get_record_sql($sql)) { // Individual score. // If this is current user's response OR if current user is viewing another group's results. if ($rrid == $rid || $allresponses) { $qscore[$qid] += $value->value; } // Only add current score if conditions below are met. if ($groupmode == 0 || $isgroupmember || !$isgroupmember && $rrid != $rid || $allresponses) { $allqscore[$qid] += $value->value; } } } } } $totalscore = array_sum($qscore); $scorepercent = round($totalscore / $maxtotalscore * 100); $oppositescorepercent = 100 - $scorepercent; $alltotalscore = array_sum($allqscore); $allscorepercent = round($alltotalscore / $nbparticipants / $maxtotalscore * 100); // No need to go further if feedback is global, i.e. only relying on total score. if ($feedbacksections == 1) { $sectionid = $fbsectionsnb[0]; $sectionlabel = $fbsections[$sectionid]->sectionlabel; $sectionheading = $fbsections[$sectionid]->sectionheading; $feedbacks = $DB->get_records('questionnaire_feedback', array('section_id' => $sectionid)); $labels = array(); foreach ($feedbacks as $feedback) { if ($feedback->feedbacklabel != '') { $labels[] = $feedback->feedbacklabel; } } $feedback = $DB->get_record_select('questionnaire_feedback', 'section_id = ? AND minscore <= ? AND ? < maxscore', array($sectionid, $scorepercent, $scorepercent)); // To eliminate all potential % chars in heading text (might interfere with the sprintf function). $sectionheading = str_replace('%', '', $sectionheading); // Replace section heading placeholders with their actual value (if any). $original = array('$scorepercent', '$oppositescorepercent'); $result = array('%s%%', '%s%%'); $sectionheading = str_replace($original, $result, $sectionheading); $sectionheading = sprintf($sectionheading, $scorepercent, $oppositescorepercent); $sectionheading = file_rewrite_pluginfile_urls($sectionheading, 'pluginfile.php', $this->context->id, 'mod_questionnaire', 'sectionheading', $sectionid); $feedbackmessages[] = $OUTPUT->box_start(); $feedbackmessages[] = format_text($sectionheading, FORMAT_HTML); $feedbackmessages[] = $OUTPUT->box_end(); if (!empty($feedback->feedbacktext)) { // Clean the text, ready for display. $formatoptions = new stdClass(); $formatoptions->noclean = true; $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php', $this->context->id, 'mod_questionnaire', 'feedback', $feedback->id); $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions); $feedbackmessages[] = $OUTPUT->box_start(); $feedbackmessages[] = $feedbacktext; $feedbackmessages[] = $OUTPUT->box_end(); } $score = array($scorepercent, 100 - $scorepercent); $allscore = null; if ($compare || $allresponses) { $allscore = array($allscorepercent, 100 - $allscorepercent); } $usergraph = get_config('questionnaire', 'usergraph'); if ($usergraph && $this->survey->chart_type) { draw_chart($feedbacktype = 'global', $this->survey->chart_type, $labels, $score, $allscore, $sectionlabel, $groupname, $allresponses); } // Display class or group score. Pending chart library decision to display? // Find out if this feedback sectionlabel has a pipe separator. $lb = explode("|", $sectionlabel); $oppositescore = ''; $oppositeallscore = ''; if (count($lb) > 1) { $sectionlabel = $lb[0] . ' | ' . $lb[1]; $oppositescore = ' | ' . $score[1] . '%'; $oppositeallscore = ' | ' . $allscore[1] . '%'; } if ($this->survey->feedbackscores) { if ($compare) { $table->data[] = array($sectionlabel, $score[0] . '%' . $oppositescore, $allscore[0] . '%' . $oppositeallscore); } else { $table->data[] = array($sectionlabel, $allscore[0] . '%' . $oppositeallscore); } echo html_writer::table($table); } return $feedbackmessages; } // Now process scores for more than one section. // Initialize scores and maxscores to 0. $score = array(); $allscore = array(); $maxscore = array(); $scorepercent = array(); $allscorepercent = array(); $oppositescorepercent = array(); $alloppositescorepercent = array(); $chartlabels = array(); $chartscore = array(); for ($i = 1; $i <= $feedbacksections; $i++) { $score[$i] = 0; $allscore[$i] = 0; $maxscore[$i] = 0; $scorepercent[$i] = 0; } for ($section = 1; $section <= $feedbacksections; $section++) { foreach ($fbsections as $key => $fbsection) { if ($fbsection->section == $section) { $feedbacksectionid = $key; $scorecalculation = unserialize($fbsection->scorecalculation); $sectionheading = $fbsection->sectionheading; $imageid = $fbsection->id; $chartlabels[$section] = $fbsection->sectionlabel; } } foreach ($scorecalculation as $qid => $key) { // Just in case a question pertaining to a section has been deleted or made not required // after being included in scorecalculation. if (isset($qscore[$qid])) { $score[$section] += $qscore[$qid]; $maxscore[$section] += $qmax[$qid]; if ($compare || $allresponses) { $allscore[$section] += $allqscore[$qid]; } } } $scorepercent[$section] = round($score[$section] / $maxscore[$section] * 100); $oppositescorepercent[$section] = 100 - $scorepercent[$section]; if (($compare || $allresponses) && $nbparticipants != 0) { $allscorepercent[$section] = round($allscore[$section] / $nbparticipants / $maxscore[$section] * 100); $alloppositescorepercent[$section] = 100 - $allscorepercent[$section]; } if (!$allresponses) { // To eliminate all potential % chars in heading text (might interfere with the sprintf function). $sectionheading = str_replace('%', '', $sectionheading); // Replace section heading placeholders with their actual value (if any). $original = array('$scorepercent', '$oppositescorepercent'); $result = array("{$scorepercent[$section]}%", "{$oppositescorepercent[$section]}%"); $sectionheading = str_replace($original, $result, $sectionheading); $formatoptions = new stdClass(); $formatoptions->noclean = true; $sectionheading = file_rewrite_pluginfile_urls($sectionheading, 'pluginfile.php', $this->context->id, 'mod_questionnaire', 'sectionheading', $imageid); $sectionheading = format_text($sectionheading, 1, $formatoptions); $feedbackmessages[] = $OUTPUT->box_start('reportQuestionTitle'); $feedbackmessages[] = format_text($sectionheading, FORMAT_HTML); $feedback = $DB->get_record_select('questionnaire_feedback', 'section_id = ? AND minscore <= ? AND ? < maxscore', array($feedbacksectionid, $scorepercent[$section], $scorepercent[$section]), 'id,feedbacktext,feedbacktextformat'); $feedbackmessages[] = $OUTPUT->box_end(); if (!empty($feedback->feedbacktext)) { // Clean the text, ready for display. $formatoptions = new stdClass(); $formatoptions->noclean = true; $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php', $this->context->id, 'mod_questionnaire', 'feedback', $feedback->id); $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions); $feedbackmessages[] = $OUTPUT->box_start('feedbacktext'); $feedbackmessages[] = $feedbacktext; $feedbackmessages[] = $OUTPUT->box_end(); } } } // Display class or group score. switch ($action) { case 'vallasort': asort($allscore); break; case 'vallarsort': arsort($allscore); break; default: } foreach ($allscore as $key => $sc) { $lb = explode("|", $chartlabels[$key]); $oppositescore = ''; $oppositeallscore = ''; if (count($lb) > 1) { $sectionlabel = $lb[0] . ' | ' . $lb[1]; $oppositescore = ' | ' . $oppositescorepercent[$key] . '%'; $oppositeallscore = ' | ' . $alloppositescorepercent[$key] . '%'; } else { $sectionlabel = $chartlabels[$key]; } if ($compare) { $table->data[] = array($sectionlabel, $scorepercent[$key] . '%' . $oppositescore, $allscorepercent[$key] . '%' . $oppositeallscore); } else { $table->data[] = array($sectionlabel, $allscorepercent[$key] . '%' . $oppositeallscore); } } $usergraph = get_config('questionnaire', 'usergraph'); if ($usergraph && $this->survey->chart_type) { draw_chart($feedbacktype = 'sections', $this->survey->chart_type, array_values($chartlabels), array_values($scorepercent), array_values($allscorepercent), $sectionlabel, $groupname, $allresponses); } if ($this->survey->feedbackscores) { echo html_writer::table($table); } return $feedbackmessages; }
/** * creates a zip of all assignment submissions and sends a zip to the browser */ public function download_submissions() { global $CFG, $DB; raise_memory_limit(MEMORY_EXTRA); $submissions = $this->get_submissions('', ''); if (empty($submissions)) { print_error('errornosubmissions', 'assignment'); } $filesforzipping = array(); //NOTE: do not create any stuff in temp directories, we now support unicode file names and that would not work, sorry //online assignment can use html $filextn = ".html"; $groupmode = groups_get_activity_groupmode($this->cm); $groupid = 0; // All users $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->cm, true); $groupname = groups_get_group_name($groupid) . '-'; } $filename = str_replace(' ', '_', clean_filename($this->course->shortname . '-' . $this->assignment->name . '-' . $groupname . $this->assignment->id . ".zip")); //name of new zip file. foreach ($submissions as $submission) { $a_userid = $submission->userid; //get userid if (groups_is_member($groupid, $a_userid) or !$groupmode or !$groupid) { $a_assignid = $submission->assignment; //get name of this assignment for use in the file names. $a_user = $DB->get_record("user", array("id" => $a_userid), 'id,username,firstname,lastname'); //get user firstname/lastname $submissioncontent = "<html><body>" . format_text($submission->data1, $submission->data2) . "</body></html>"; //fetched from database //get file name.html $fileforzipname = clean_filename(fullname($a_user) . "_" . $a_userid . $filextn); $filesforzipping[$fileforzipname] = array($submissioncontent); } } //end of foreach if ($zipfile = assignment_pack_files($filesforzipping)) { send_temp_file($zipfile, $filename); //send file and delete after sending. } }
$sql = "SELECT DISTINCT {$ufields}\n FROM {user} u\n JOIN {lesson_attempts} a ON u.id = a.userid\n JOIN ({$esql}) ue ON ue.id = a.userid\n WHERE a.lessonid = :lessonid\n ORDER BY {$sort}"; if (!($users = $DB->get_records_sql($sql, $params))) { $mode = 'none'; // not displaying anything if (!empty($currentgroup)) { $groupname = groups_get_group_name($currentgroup); $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname)); } else { $lesson->add_message(get_string('noonehasanswered', 'lesson')); } } } else { $mode = 'none'; // not displaying anything if (!empty($currentgroup)) { $groupname = groups_get_group_name($currentgroup); $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname)); } else { $lesson->add_message(get_string('noonehasanswered', 'lesson')); } } } else { $mode = 'none'; // not displaying anything $lesson->add_message(get_string('noessayquestionsfound', 'lesson')); } break; } $lessonoutput = $PAGE->get_renderer('mod_lesson'); echo $lessonoutput->header($lesson, $cm, 'essay', false, null, get_string('manualgrading', 'lesson')); switch ($mode) {
public function recipientsform($courseid, $userid) { global $COURSE, $DB; $options = array(); $owngroups = groups_get_user_groups($courseid, $userid); $content = html_writer::start_tag('div', array('id' => 'local_mail_recipients_form', 'class' => 'local_mail_form mail_hidden')); if ($COURSE->groupmode == SEPARATEGROUPS and empty($owngroups[0])) { return ''; } $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_toolbar')); // Roles $context = context_course::instance($courseid); $roles = role_get_names($context); $userroles = local_mail_get_user_roleids($userid, $context); $mailsamerole = has_capability('local/mail:mailsamerole', $context); foreach ($roles as $key => $role) { $count = $DB->count_records_select('role_assignments', "contextid = :contextid AND roleid = :roleid AND userid <> :userid", array('contextid' => $context->id, 'roleid' => $role->id, 'userid' => $userid)); if (($count && $mailsamerole) || ($count && !$mailsamerole && !in_array($role->id, $userroles))) { $options[$key] = $role->localname; } } $text = get_string('role', 'moodle'); $content .= html_writer::start_tag('span', array('class' => 'roleselector')); $content .= html_writer::label($text, 'local_mail_roles'); $text = get_string('all', 'local_mail'); $content .= html_writer::select($options, 'local_mail_roles', '', array('' => $text), array('id' => 'local_mail_recipients_roles', 'class' => '')); $content .= html_writer::end_tag('span'); // Groups $groups = groups_get_all_groups($courseid); if ($COURSE->groupmode == NOGROUPS or ($COURSE->groupmode == VISIBLEGROUPS and empty($groups))) { $content .= html_writer::tag('span', get_string('allparticipants', 'moodle'), array('class' => 'groupselector groupname')); } else { if ($COURSE->groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) { unset($options); foreach ($groups as $key => $group) { $options[$key] = $group->name; } $text = get_string('group', 'moodle'); $content .= html_writer::start_tag('span', array('class' => 'groupselector')); $content .= html_writer::label($text, 'local_mail_recipients_groups'); $text = get_string('allparticipants', 'moodle'); $content .= html_writer::select($options, 'local_mail_recipients_groups', '', array('' => $text), array('id' => 'local_mail_recipients_groups', 'class' => '')); $content .= html_writer::end_tag('span'); } else if (count($owngroups[0]) == 1) {// SEPARATEGROUPS and user in only one group $text = get_string('group', 'moodle'); $content .= html_writer::start_tag('span', array('class' => 'groupselector')); $content .= html_writer::label("$text: ", null); $content .= html_writer::tag('span', groups_get_group_name($owngroups[0][0]), array('class' => 'groupname')); $content .= html_writer::end_tag('span'); } else if (count($owngroups[0]) > 1) {// SEPARATEGROUPS and user in several groups unset($options); foreach ($owngroups[0] as $key => $group) { $options[$group] = groups_get_group_name($group); } $text = get_string('group', 'moodle'); $content .= html_writer::start_tag('span', array('class' => 'groupselector')); $content .= html_writer::label($text, 'local_mail_recipients_groups'); $text = get_string('allparticipants', 'moodle'); $content .= html_writer::select($options, 'local_mail_recipients_groups', '', array(key($options) => current($options)), array('id' => 'local_mail_recipients_groups', 'class' => '')); $content .= html_writer::end_tag('span'); } } $content .= html_writer::tag('div', '', array('class' => 'mail_separator')); // Search $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_search')); $attributes = array( 'type' => 'text', 'name' => 'recipients_search', 'value' => '', 'maxlength' => '100', 'class' => 'mail_search' ); $text = get_string('search', 'local_mail'); $content .= html_writer::label($text, 'recipients_search'); $content .= html_writer::empty_tag('input', $attributes); // Select all recipients $content .= html_writer::start_tag('span', array('class' => 'mail_all_recipients_actions')); $attributes = array( 'type' => 'button', 'name' => "to_all", 'value' => get_string('to', 'local_mail') ); $content .= html_writer::empty_tag('input', $attributes); $attributes = array( 'type' => 'button', 'name' => "cc_all", 'value' => get_string('cc', 'local_mail') ); $content .= html_writer::empty_tag('input', $attributes); $attributes = array( 'type' => 'button', 'name' => "bcc_all", 'value' => get_string('bcc', 'local_mail') ); $content .= html_writer::empty_tag('input', $attributes); $attributes = array('type' => 'image', 'name' => "remove_all", 'src' => $this->output->pix_url('t/delete'), 'alt' => get_string('remove')); $content .= html_writer::empty_tag('input', $attributes); $content .= html_writer::end_tag('span'); $content .= html_writer::end_tag('div'); $content .= html_writer::end_tag('div'); $content .= html_writer::tag('div', '', array('id' => 'local_mail_recipients_list', 'class' => 'mail_form_recipients')); $content .= html_writer::start_tag('div', array('class' => 'mail_recipients_loading')); $content .= $this->output->pix_icon('i/loading', get_string('actions'), 'moodle', array('class' => 'loading_icon')); $content .= html_writer::end_tag('div'); $content .= html_writer::end_tag('div'); return $content; }
/** * Download a zip file of all assignment submissions. * * @return string - If an error occurs, this will contain the error page. */ protected function download_submissions() { global $CFG, $DB; // More efficient to load this here. require_once $CFG->libdir . '/filelib.php'; require_capability('mod/assign:grade', $this->context); // Load all users with submit. $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null, $this->show_only_active_users()); // Build a list of files to zip. $filesforzipping = array(); $fs = get_file_storage(); $groupmode = groups_get_activity_groupmode($this->get_course_module()); // All users. $groupid = 0; $groupname = ''; if ($groupmode) { $groupid = groups_get_activity_group($this->get_course_module(), true); $groupname = groups_get_group_name($groupid) . '-'; } // Construct the zip file name. $filename = clean_filename($this->get_course()->shortname . '-' . $this->get_instance()->name . '-' . $groupname . $this->get_course_module()->id . '.zip'); // Get all the files for each student. foreach ($students as $student) { $userid = $student->id; if (groups_is_member($groupid, $userid) or !$groupmode or !$groupid) { // Get the plugins to add their own files to the zip. $submissiongroup = false; $groupname = ''; if ($this->get_instance()->teamsubmission) { $submission = $this->get_group_submission($userid, 0, false); $submissiongroup = $this->get_submission_group($userid); if ($submissiongroup) { $groupname = $submissiongroup->name . '-'; } else { $groupname = get_string('defaultteam', 'assign') . '-'; } } else { $submission = $this->get_user_submission($userid, false); } if ($this->is_blind_marking()) { $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign')); $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_'); } else { $prefix = str_replace('_', ' ', $groupname . fullname($student)); $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_'); } if ($submission) { foreach ($this->submissionplugins as $plugin) { if ($plugin->is_enabled() && $plugin->is_visible()) { $pluginfiles = $plugin->get_files($submission, $student); foreach ($pluginfiles as $zipfilename => $file) { $subtype = $plugin->get_subtype(); $type = $plugin->get_type(); $prefixedfilename = clean_filename($prefix . $subtype . '_' . $type . '_' . $zipfilename); $filesforzipping[$prefixedfilename] = $file; } } } } } } $result = ''; if (count($filesforzipping) == 0) { $header = new assign_header($this->get_instance(), $this->get_context(), '', $this->get_course_module()->id, get_string('downloadall', 'assign')); $result .= $this->get_renderer()->render($header); $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign')); $url = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id, 'action' => 'grading')); $result .= $this->get_renderer()->continue_button($url); $result .= $this->view_footer(); } else { if ($zipfile = $this->pack_files($filesforzipping)) { $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true); $params = array('context' => $this->context, 'objectid' => $this->get_instance()->id); $event = \mod_assign\event\all_submissions_downloaded::create($params); $event->set_legacy_logdata($addtolog); $event->trigger(); // Send file and delete after sending. send_temp_file($zipfile, $filename); // We will not get here - send_temp_file calls exit. } } return $result; }
$checked = 'checked="checked"'; } else { $checked = ''; } $cells[] = "<input type=\"checkbox\" {$checked} id=\"mailto{$t}\" value=\"{$user->id}\" name=\"mailto[{$user->id}]\" />" . "<label for=\"mailto{$t}\">" . fullname($user, true) . '</label>'; $t++; } } $end = $t; // cell1 has the group picture, name and check button $cell1 = ''; if ($group) { $cell1 .= print_group_picture($group, $course->id, false, true) . '<br />'; } if ($group) { $cell1 .= groups_get_group_name($group->id); } else { $cell1 .= get_string('notingroup', 'block_quickmail'); } if (count($groups) > 1 and !empty($cells)) { $selectlinks = '<a href="javascript:void(0);" onclick="block_quickmail_toggle(true, ' . $start . ', ' . $end . ');">' . get_string('selectall') . '</a> / <a href="javascript:void(0);" onclick="block_quickmail_toggle(false, ' . $start . ', ' . $end . ');">' . get_string('deselectall') . '</a>'; } else { $selectlinks = ''; } $buttoncount++; // cell2 has the checkboxes and the user names inside of a table if (empty($cells) and !$group) { // there is no one that is not in a group, so no need to print our 'nogroup' group continue; } else {
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; }
/** * This function updates the events associated to the quiz. * If $override is non-zero, then it updates only the events * associated with the specified override. * * @uses QUIZ_MAX_EVENT_LENGTH * @param object $quiz the quiz object. * @param object optional $override limit to a specific override */ function quiz_update_events($quiz, $override = null) { global $DB; // Load the old events relating to this quiz. $conds = array('modulename'=>'quiz', 'instance'=>$quiz->id); if (!empty($override)) { // Only load events for this override. $conds['groupid'] = isset($override->groupid)? $override->groupid : 0; $conds['userid'] = isset($override->userid)? $override->userid : 0; } $oldevents = $DB->get_records('event', $conds); // Now make a todo list of all that needs to be updated. if (empty($override)) { // We are updating the primary settings for the quiz, so we // need to add all the overrides. $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id)); // As well as the original quiz (empty override). $overrides[] = new stdClass(); } else { // Just do the one override. $overrides = array($override); } foreach ($overrides as $current) { $groupid = isset($current->groupid)? $current->groupid : 0; $userid = isset($current->userid)? $current->userid : 0; $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen; $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose; // Only add open/close events for an override if they differ from the quiz default. $addopen = empty($current->id) || !empty($current->timeopen); $addclose = empty($current->id) || !empty($current->timeclose); if (!empty($quiz->coursemodule)) { $cmid = $quiz->coursemodule; } else { $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id; } $event = new stdClass(); $event->description = format_module_intro('quiz', $quiz, $cmid); // Events module won't show user events when the courseid is nonzero. $event->courseid = ($userid) ? 0 : $quiz->course; $event->groupid = $groupid; $event->userid = $userid; $event->modulename = 'quiz'; $event->instance = $quiz->id; $event->timestart = $timeopen; $event->timeduration = max($timeclose - $timeopen, 0); $event->visible = instance_is_visible('quiz', $quiz); $event->eventtype = 'open'; // Determine the event name. if ($groupid) { $params = new stdClass(); $params->quiz = $quiz->name; $params->group = groups_get_group_name($groupid); if ($params->group === false) { // Group doesn't exist, just skip it. continue; } $eventname = get_string('overridegroupeventname', 'quiz', $params); } else if ($userid) { $params = new stdClass(); $params->quiz = $quiz->name; $eventname = get_string('overrideusereventname', 'quiz', $params); } else { $eventname = $quiz->name; } if ($addopen or $addclose) { if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) { // Single event for the whole quiz. if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname; // The method calendar_event::create will reuse a db record if the id field is set. calendar_event::create($event); } else { // Separate start and end events. $event->timeduration = 0; if ($timeopen && $addopen) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')'; // The method calendar_event::create will reuse a db record if the id field is set. calendar_event::create($event); } if ($timeclose && $addclose) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')'; $event->timestart = $timeclose; $event->eventtype = 'close'; calendar_event::create($event); } } } } // Delete any leftover events. foreach ($oldevents as $badevent) { $badevent = calendar_event::load($badevent); $badevent->delete(); } }