function display_submission($extra_javascript = '')
 {
     global $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->libdir . '/tablelib.php';
     $userid = required_param('userid', PARAM_INT);
     $offset = required_param('offset', PARAM_INT);
     //offset for where to start looking for student.
     if (!($user = get_record('user', 'id', $userid))) {
         error('No such user!');
     }
     if (!($submission = $this->get_submission($user->id))) {
         $submission = $this->prepare_new_submission($userid);
     }
     if ($submission->timemodified > $submission->timemarked) {
         $subtype = 'assignmentnew';
     } else {
         $subtype = 'assignmentold';
     }
     // Get the criteria
     $criteriaList = get_records_list('assignment_criteria', 'assignment', $this->assignment->id, 'ordernumber');
     $numberOfCriteria = 0;
     if (is_array($criteriaList)) {
         $criteriaList = array_values($criteriaList);
         $numberOfCriteria = count($criteriaList);
     }
     $reviews = $this->get_reviews_of_student($user->id);
     $numberOfReviewsOfThisStudent = 0;
     if (is_array($reviews)) {
         $numberOfReviewsOfThisStudent = count($reviews);
     }
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
     $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Get all ppl that can submit assignments
     $currentgroup = groups_get_activity_group($cm);
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $nextid = 0;
     if ($users) {
         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                           s.id AS submissionid, s.grade, s.submissioncomment,
                           s.timecreated as submitted, s.timemarked as timemarked ';
         $sql = 'FROM ' . $CFG->prefix . 'user u ' . 'LEFT JOIN ' . $CFG->prefix . 'assignment_submissions s ON u.id = s.userid
                                                                   AND s.assignment = ' . $this->assignment->id . ' ' . 'WHERE u.id IN (' . implode(',', $users) . ') ';
         $sort = 'ORDER BY COALESCE(submitted,2147483647) ASC, submissionid ASC, u.lastname ASC';
         // if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
         // $sort = 'ORDER BY '.$sort.' ';
         // }
         if (($auser = get_records_sql($select . $sql . $sort, $offset + 1, 1)) !== false) {
             $nextuser = array_shift($auser);
             // Calculate user status
             if ($nextuser && $nextuser->submitted) {
                 $nextuser->status = $nextuser->timemarked > 0;
                 $nextid = $nextuser->id;
             }
         }
     }
     print_header(get_string('feedback', 'assignment') . ':' . fullname($user, true) . ':' . format_string($this->assignment->name));
     // Print any extra javascript needed for saveandnext
     print $extra_javascript;
     // Some javascript to help with setting up >.>
     echo '<script type="text/javascript">' . "\n";
     echo 'function setNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'next\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo '}' . "\n";
     echo 'function saveNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo 'document.getElementById(\'submitform\').saveuserid.value="' . $userid . '";' . "\n";
     //        echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
     echo '}' . "\n";
     echo 'function setSavePrev(){' . "\n";
     echo 'document.getElementById(\'submitform\').savePrev.value=\'1\';' . "\n";
     echo '}' . "\n";
     echo '</script>' . "\n";
     require_once $CFG->dirroot . '/mod/assignment/type/peerreview/' . self::STYLES_FILE;
     echo '<table cellspacing="0" class="feedback ' . $subtype . '" style="width:99%;">';
     // Start of student info row
     echo '<tr>';
     echo '<td class="picture user">';
     print_user_picture($user, $this->course->id, $user->picture);
     echo '</td>';
     echo '<td class="topic">';
     echo '<div class="from">';
     echo '<div class="fullname">' . fullname($user, true) . '</div>';
     if ($submission->timemodified) {
         echo '<div class="time">' . get_string('submitted', 'assignment_peerreview') . ': ' . userdate($submission->timecreated) . $this->display_lateness($submission->timecreated) . '</div>';
     }
     echo '<div class="reviewDetailsRow">';
     $moderationCountSQL = 'SELECT count(r.id) FROM ' . $CFG->prefix . 'assignment a, ' . $CFG->prefix . 'assignment_review r WHERE a.course=' . $course->id . ' AND a.id=r.assignment AND r.teacherreview=1 AND r.reviewee=\'' . $user->id . '\'';
     $moderationCount = count_records_sql($moderationCountSQL);
     $moderationtarget = get_user_preferences('assignment_moderationtarget', 0);
     echo get_string('moderations', 'assignment_peerreview') . ': ';
     if ($moderationCount < $moderationtarget) {
         echo '<span class="errorStatus">' . $moderationCount . ' (' . get_string('moderationtargetnotmet', 'assignment_peerreview') . ')</span>';
     } else {
         echo $moderationCount;
     }
     echo '</div>';
     echo '<div class="reviewDetailsRow">';
     echo get_string('status') . ': ';
     $statusCode = $this->get_status($reviews, $numberOfCriteria);
     $this->print_status($statusCode);
     echo $statusCode <= 3 ? ' (' . get_string('moderationrequired', 'assignment_peerreview') . ')' : '';
     echo '</div>';
     echo '</div>';
     if (isset($this->assignment->var3) && $this->assignment->var3 == self::ONLINE_TEXT) {
         $url = '/mod/assignment/type/peerreview/' . self::VIEW_ONLINE_TEXT . '?id=' . $this->cm->id . '&a=' . $this->assignment->id . '&userid=' . $user->id . '&view=moderation';
         echo '<div class="files"><a href="' . $CFG->wwwroot . $url . '" target="_blank" onclick="return openpopup(\'' . $url . '\',\'submission\',\'menubar=0,location=0,scrollbars,resizable,width=500,height=400\');"><img src="' . $CFG->pixpath . '/f/html.gif" />' . get_string('submission', 'assignment_peerreview') . '</a></div>';
     } else {
         $this->print_user_files($user->id);
     }
     echo '</td>';
     echo '</tr>';
     ///Start of marking row
     echo '<tr>';
     echo '<td colspan="2" style="padding:2px;">';
     echo '<form id="submitform" action="submissions.php" method="post">';
     echo '<div>';
     // xhtml compatibility - invisiblefieldset was breaking layout here
     echo '<input type="hidden" name="offset" value="' . ($offset + 1) . '" />';
     echo '<input type="hidden" name="userid" value="' . $userid . '" />';
     echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
     echo '<input type="hidden" name="timeLoaded" value="' . time() . '" />';
     echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
     echo '<input type="hidden" name="mode" value="grade" />';
     //        echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
     echo '<input type="hidden" name="saveuserid" value="-1" />';
     echo '<input type="hidden" name="savePrev" value="0" />';
     echo '<table width="99%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;">';
     echo '<tr>';
     for ($i = 0; $i < $numberOfReviewsOfThisStudent; $i++) {
         echo '<td class="criteriaCheckboxColumn" style="background:' . $this->REVIEW_COLOURS[$i % $this->NUMBER_OF_COLOURS] . '">&nbsp;</td>';
     }
     echo '<td colspan="2" class="reviewStatus"><span style="padding-left:5px;font-weight:bold;">';
     echo get_string('newreview', 'assignment_peerreview');
     echo '</span></td></tr>';
     $options = new object();
     $options->para = false;
     for ($i = 0; $i < $numberOfCriteria; $i++) {
         echo '<tr class="criteriaDisplayRow">';
         for ($j = 0; $j < $numberOfReviewsOfThisStudent; $j++) {
             echo '<td class="criteriaCheckboxColumn" style="background:' . $this->REVIEW_COLOURS[$j % $this->NUMBER_OF_COLOURS] . '"><input type="checkbox" name="checked' . $reviews[$j]->review . 'crit' . $i . '" ' . ($reviews[$j]->{'checked' . $i} == 1 ? ' checked' : '') . ' onchange="document.getElementById(\'savepreexistingonly\').disabled=false;" /></td>';
         }
         echo '<td class="criteriaCheckboxColumn"><input type="checkbox" name="newChecked' . $i . '"  onchange="document.getElementById(\'savenew\').disabled=false;if(document.getElementById(\'saveandnext\')){document.getElementById(\'saveandnext\').disabled=false;}" /></td>';
         echo '<td class="criteriaDisplayColumn">' . format_text($criteriaList[$i]->textshownatreview != '' ? $criteriaList[$i]->textshownatreview : $criteriaList[$i]->textshownwithinstructions, FORMAT_MOODLE, $options) . '</td>';
         echo '</tr>';
     }
     echo '<tr>';
     for ($i = 0; $i < $numberOfReviewsOfThisStudent; $i++) {
         echo '<td class="criteriaCheckboxColumn" style="background:' . $this->REVIEW_COLOURS[$i % $this->NUMBER_OF_COLOURS] . ';">&nbsp;</td>';
     }
     echo '<td colspan="2" style="padding:5px;">';
     echo '<table width="100%" cellspacing="2">';
     echo '<tr>';
     echo '<td style="vertical-align:top;" width="50%">' . get_string('comment', 'assignment_peerreview') . '<br /><textarea name="newComment" rows="10" style="width:99%;" onkeypress="document.getElementById(\'savenew\').disabled=false;document.getElementById(\'saveandnext\').disabled=false;"></textarea><td>';
     echo '<td style="vertical-align:top;">' . get_string('savedcomments', 'assignment_peerreview') . ' (<a href="#null" onclick="commentForm=document.getElementById(\'commentsForm\'); commentForm.comments.value=document.getElementById(\'savedcomments\').value; window.open(\'\', \'savedcommentsWindow\', \'height=300,width=400\'); commentForm.target=\'savedcommentsWindow\'; commentForm.submit();" />' . get_string('savecomments', 'assignment_peerreview') . '</a>)<br /><textarea rows="10" style="width:99%;" id="savedcomments" >' . ($this->assignment->savedcomments ? format_string(stripslashes($this->assignment->savedcomments)) : '') . '</textarea><td>';
     echo '</tr>';
     echo '</table>';
     echo '</td>';
     echo '</tr>';
     $studentCount = 1;
     for ($i = 0; $i < $numberOfReviewsOfThisStudent; $i++) {
         echo '<tr>';
         for ($j = 0; $j < $numberOfReviewsOfThisStudent; $j++) {
             echo '<td class="criteriaCheckboxColumn" style="background:' . ($j > $numberOfReviewsOfThisStudent - $i - 1 ? $this->REVIEW_COLOURS[($numberOfReviewsOfThisStudent - $i - 1) % $this->NUMBER_OF_COLOURS] : $this->REVIEW_COLOURS[$j % $this->NUMBER_OF_COLOURS]) . ';">&nbsp;</td>';
         }
         echo '<td colspan="2" class="reviewCommentRow" style="background:' . $this->REVIEW_COLOURS[($numberOfReviewsOfThisStudent - $i - 1) % $this->NUMBER_OF_COLOURS] . ';">';
         echo '<table width="99%" cellpadding="0" cellspacing="0" border="0">';
         echo '<tr class="reviewDetailsRow">';
         echo '<td><em>' . get_string('conductedby', 'assignment_peerreview') . ': ' . $reviews[$numberOfReviewsOfThisStudent - $i - 1]->firstname . ' ' . $reviews[$numberOfReviewsOfThisStudent - $i - 1]->lastname . ' (' . ($reviews[$numberOfReviewsOfThisStudent - $i - 1]->teacherreview == 1 ? $this->course->teacher : $this->course->student) . ')</em></td>';
         echo '<td class="reviewDateColumn"><em>' . userdate($reviews[$numberOfReviewsOfThisStudent - $i - 1]->timemodified, get_string('strftimedatetime')) . '</em></td>';
         echo '</tr>';
         echo '<tr><td colspan="2"><textarea name="preExistingComment' . $reviews[$numberOfReviewsOfThisStudent - $i - 1]->review . '" rows="3" class="commentTextBox" onkeypress="document.getElementById(\'savepreexistingonly\').disabled=false;;" style="background:' . $this->REVIEW_COMMENT_COLOURS[($numberOfReviewsOfThisStudent - $i - 1) % count($this->REVIEW_COMMENT_COLOURS)] . ';">' . format_string(stripslashes($reviews[$numberOfReviewsOfThisStudent - $i - 1]->reviewcomment)) . '</textarea></td></tr>';
         if ($reviews[$numberOfReviewsOfThisStudent - $i - 1]->flagged == 1) {
             echo '<tr class="reviewDetailsRow" style="color:#ff0000;"><td colspan="2"><em>' . get_string('flagged', 'assignment_peerreview') . '</em></td></tr>';
         }
         echo '</table>';
         echo '</td>';
         echo '</tr>';
     }
     echo '</table>';
     $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
     ///Print Buttons in Single View
     // echo '<input type="hidden" name="mailinfo" value="0" />';
     // echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment_peerreview').'</label>';
     echo '<div class="buttons">';
     if ($numberOfReviewsOfThisStudent > 0) {
         echo '<input type="submit" id="savepreexistingonly" name="submit" value="' . get_string('savepreexistingonly', 'assignment_peerreview') . '" onclick="setSavePrev();" />';
         echo '<script>document.getElementById(\'savepreexistingonly\').disabled=true;</script>';
     }
     echo '<input type="submit" name="cancel" value="' . get_string('cancel') . '" />';
     echo '<input type="submit" id="savenew" name="submit" value="' . get_string('savenew', 'assignment_peerreview') . '" />';
     echo '<script>document.getElementById(\'savenew\').disabled=true;</script>';
     //if there are more to be graded.
     if ($nextid) {
         echo '<input type="submit" id="saveandnext" name="saveandnext" value="' . get_string('saveandnext', 'assignment_peerreview') . '" onclick="saveNext();" />';
         echo '<script>document.getElementById(\'saveandnext\').disabled=true;</script>';
         echo '<input type="submit" name="next" value="' . get_string('next') . '" onclick="setNext();" />';
     }
     echo '</div>';
     echo '</div></form>';
     echo '<form action="type/peerreview/' . self::SAVE_COMMENTS_FILE . '" id="commentsForm" method="post" target="_blank">';
     echo '<input type="hidden" name="id" value="' . $this->cm->id . '">';
     echo '<input type="hidden" name="a" value="' . $this->assignment->id . '">';
     echo '<input type="hidden" name="comments" id="comments" value="">';
     echo '</form>';
     $customfeedback = $this->custom_feedbackform($submission, true);
     if (!empty($customfeedback)) {
         echo $customfeedback;
     }
     echo '</td></tr>';
     echo '</table>';
     print_footer('none');
 }
 function plagiarismSimilarities($id)
 {
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $currentgroup = groups_get_activity_group($cm);
     if ($users = get_users_by_capability($this->context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($this->cfg->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $similarities = get_records('plagiarismdetector_similarities', 'plagiarismid', $id);
     $userssim = array();
     $arrsim;
     $arrusers = array();
     foreach ($similarities as $sim) {
         $userssim[] = $sim->user1;
         $userssim[] = $sim->user2;
         if (!isset($arrsim[$sim->user1])) {
             $arrsim[$sim->user1] = array();
         }
         if (!isset($arrsim[$sim->user2])) {
             $arrsim[$sim->user2] = array();
         }
         $arrsim[$sim->user1][$sim->user2] = new stdClass();
         $arrsim[$sim->user1][$sim->user2]->similarity = $sim->similarity;
         $arrsim[$sim->user1][$sim->user2]->confirmed = $sim->confirmed;
         $arrsim[$sim->user1][$sim->user2]->id = $sim->id;
         $arrsim[$sim->user2][$sim->user1] = $arrsim[$sim->user1][$sim->user2];
         $id = $sim->user1;
         $usa = new stdClass();
         $usa->firstname = $id;
         $usa->lastname = '(false)';
         $usa->id = $id;
         $arrusers[$id] = $usa;
     }
     $userssim = array_unique($userssim);
     $users = array_intersect($users, $userssim);
     $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt ';
     $sql = 'FROM ' . $this->cfg->prefix . 'user u ' . 'WHERE u.id IN (' . implode(',', $users) . ') ';
     $infousers = get_records_sql($select . $sql);
     foreach ($infousers as $us) {
         $id = $us->id;
         $arrusers[$id] = $us;
     }
     $ret = new stdClass();
     $ret->users = $arrusers;
     $ret->similarities = $arrsim;
     return $ret;
 }
if ($meeting->sessiontype == 0) {
    $course_users = $DB->get_records_sql("select u.id from {role_assignments} ra, {context} con, {course} c, {user} u where ra.userid=u.id and ra.contextid=con.id and con.instanceid=c.id and c.id=" . $meeting->course);
    //$course_users = $DB->get_records_sql("select u.id from mdl_role_assignments ra, mdl_context con, mdl_course c, mdl_user u where ra.userid=u.id and ra.contextid=con.id and con.instanceid=c.id and c.id=" . $meeting->course);
    $userids = array_keys($course_users);
} else {
    if ($meeting->sessiontype == 1) {
        $userids = explode(',', $meeting->nonchairlist);
    } else {
        if ($meeting->sessiontype == 2) {
            //This will get all the people in the course
            $course_users = $DB->get_records_sql("select u.id from {role_assignments} ra, {context} con, {course} c, {user} u where ra.userid=u.id and ra.contextid=con.id and con.instanceid=c.id and c.id=" . $meeting->course);
            //$course_users = $DB->get_records_sql("select u.id from mdl_role_assignments ra, mdl_context con, mdl_course c, mdl_user u where ra.userid=u.id and ra.contextid=con.id and con.instanceid=c.id and c.id=" . $meeting->course);
            $userids = array_keys($course_users);
        } else {
            if ($meeting->sessiontype == 3) {
                $userids = array_keys(groups_get_grouping_members($meeting->groupingid, 'distinct u.id', 'u.id'));
            }
        }
    }
}
/// Only care about non-moderators of the activity.
if ($meeting->sessiontype == 1) {
    $userids = implode(', ', $userids);
} else {
    if ($moderators = get_users_by_capability($context, 'mod/elluminate:moderatemeeting', 'u.id', '', '', '', '', '', false)) {
        $userids = implode(', ', array_diff($userids, array_keys($moderators)));
    } else {
        $userids = implode(', ', $userids);
    }
}
$select = 'SELECT u.id, u.firstname, u.lastname ';
Example #4
0
         }
     }
     // Put in a submission link
     $table->data[] = array("<b><a href=\"view.php?id={$cm->id}&amp;action=submitexample\">" . get_string("submitexampleassignment", "workshop") . "</a></b>" . helpbutton("submissionofexamples", get_string("submitexampleassignment", "workshop"), "workshop", true, false, '', true), '&nbsp;', '&nbsp;');
     print_table($table);
     workshop_print_key($workshop);
 }
 // Get all the students
 if (!($users = workshop_get_students($workshop))) {
     echo '</table>';
     print_heading(get_string("nostudentsyet"));
     print_footer($course);
     exit;
 }
 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid) && !empty($users)) {
     $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
     foreach ($users as $key => $user) {
         if (!isset($groupingusers[$user->id])) {
             unset($users[$key]);
         }
     }
 }
 /// Now prepare table with student assessments and submissions
 $tablesort->data = array();
 $tablesort->sortdata = array();
 foreach ($users as $user) {
     // skip if student not in group
     if ($currentgroup) {
         if (!groups_is_member($currentgroup, $user->id)) {
             continue;
         }
Example #5
0
 /**
  *  Display all the submissions ready for grading
  */
 function display_submissions($message = '')
 {
     global $CFG, $db, $USER;
     require_once $CFG->libdir . '/gradelib.php';
     /* first we check to see if the form has just been submitted
      * to request user_preference updates
      */
     if (isset($_POST['updatepref'])) {
         $perpage = optional_param('perpage', 10, PARAM_INT);
         $perpage = $perpage <= 0 ? 10 : $perpage;
         set_user_preference('assignment_perpage', $perpage);
         set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
     }
     /* next we get perpage and quickgrade (allow quick grade) params
      * from database
      */
     $perpage = get_user_preferences('assignment_perpage', 10);
     $quickgrade = get_user_preferences('assignment_quickgrade', 0);
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
     if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
         $uses_outcomes = true;
     } else {
         $uses_outcomes = false;
     }
     $teacherattempts = true;
     /// Temporary measure
     $page = optional_param('page', 0, PARAM_INT);
     $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
     /// Some shortcuts to make the code read better
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $tabindex = 1;
     //tabindex for quick grading tabbing; Not working for dropdowns yet
     add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id=' . $this->assignment->id, $this->assignment->id, $this->cm->id);
     $navlinks = array();
     $navlinks[] = array('name' => $this->strassignments, 'link' => "index.php?id={$course->id}", 'type' => 'activity');
     $navlinks[] = array('name' => format_string($this->assignment->name, true), 'link' => "view.php?a={$this->assignment->id}", 'type' => 'activityinstance');
     $navlinks[] = array('name' => $this->strsubmissions, 'link' => '', 'type' => 'title');
     $navigation = build_navigation($navlinks);
     print_header_simple(format_string($this->assignment->name, true), "", $navigation, '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
     if (!empty($message)) {
         echo $message;
         // display messages here if any
     }
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// find out current groups mode
     $groupmode = groups_get_activity_groupmode($cm);
     $currentgroup = groups_get_activity_group($cm, true);
     groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
     /// Get all ppl that are allowed to submit assignments
     $users = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', $currentgroup, '', false);
     $users = array_keys($users);
     if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
         $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
         $users = array_intersect($users, array_keys($groupingusers));
     }
     $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
     if ($uses_outcomes) {
         $tablecolumns[] = 'outcome';
         // no sorting based on outcomes column
     }
     $tableheaders = array('', get_string('fullname'), get_string('grade'), get_string('comment', 'assignment'), get_string('lastmodified') . ' (' . $course->student . ')', get_string('lastmodified') . ' (' . $course->teacher . ')', get_string('status'), get_string('finalgrade', 'grades'));
     if ($uses_outcomes) {
         $tableheaders[] = get_string('outcome', 'grades');
     }
     require_once $CFG->libdir . '/tablelib.php';
     $table = new flexible_table('mod-assignment-submissions');
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
     $table->define_baseurl($CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id . '&amp;currentgroup=' . $currentgroup);
     $table->sortable(true, 'lastname');
     //sorted by lastname by default
     $table->collapsible(true);
     $table->initialbars(true);
     $table->column_suppress('picture');
     $table->column_suppress('fullname');
     $table->column_class('picture', 'picture');
     $table->column_class('fullname', 'fullname');
     $table->column_class('grade', 'grade');
     $table->column_class('submissioncomment', 'comment');
     $table->column_class('timemodified', 'timemodified');
     $table->column_class('timemarked', 'timemarked');
     $table->column_class('status', 'status');
     $table->column_class('finalgrade', 'finalgrade');
     if ($uses_outcomes) {
         $table->column_class('outcome', 'outcome');
     }
     $table->set_attribute('cellspacing', '0');
     $table->set_attribute('id', 'attempts');
     $table->set_attribute('class', 'submissions');
     $table->set_attribute('width', '90%');
     //$table->set_attribute('align', 'center');
     $table->no_sorting('finalgrade');
     $table->no_sorting('outcome');
     // Start working -- this is necessary as soon as the niceties are over
     $table->setup();
     /// Check to see if groups are being used in this assignment
     if (!$teacherattempts) {
         $teachers = get_course_teachers($course->id);
         if (!empty($teachers)) {
             $keys = array_keys($teachers);
         }
         foreach ($keys as $key) {
             unset($users[$key]);
         }
     }
     if (empty($users)) {
         print_heading(get_string('noattempts', 'assignment'));
         return true;
     }
     /// Construct the SQL
     if ($where = $table->get_sql_where()) {
         $where .= ' AND ';
     }
     if ($sort = $table->get_sql_sort()) {
         $sort = ' ORDER BY ' . $sort;
     }
     $select = 'SELECT u.id, u.firstname, u.lastname, u.picture,
                       s.id AS submissionid, s.grade, s.submissioncomment,
                       s.timemodified, s.timemarked,
                       COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
     $sql = 'FROM ' . $CFG->prefix . 'user u ' . 'LEFT JOIN ' . $CFG->prefix . 'assignment_submissions s ON u.id = s.userid
                                                               AND s.assignment = ' . $this->assignment->id . ' ' . 'WHERE ' . $where . 'u.id IN (' . implode(',', $users) . ') ';
     $table->pagesize($perpage, count($users));
     ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
     $offset = $page * $perpage;
     $strupdate = get_string('update');
     $strgrade = get_string('grade');
     $grademenu = make_grades_menu($this->assignment->grade);
     if (($ausers = get_records_sql($select . $sql . $sort, $table->get_page_start(), $table->get_page_size())) !== false) {
         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
         foreach ($ausers as $auser) {
             $final_grade = $grading_info->items[0]->grades[$auser->id];
             /// Calculate user status
             $auser->status = $auser->timemarked > 0 && $auser->timemarked >= $auser->timemodified;
             $picture = print_user_picture($auser->id, $course->id, $auser->picture, false, true);
             if (empty($auser->submissionid)) {
                 $auser->grade = -1;
                 //no submission yet
             }
             if (!empty($auser->submissionid)) {
                 ///Prints student answer and student modified date
                 ///attach file or print link to student answer, depending on the type of the assignment.
                 ///Refer to print_student_answer in inherited classes.
                 if ($auser->timemodified > 0) {
                     $studentmodified = '<div id="ts' . $auser->id . '">' . $this->print_student_answer($auser->id) . userdate($auser->timemodified) . '</div>';
                 } else {
                     $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 }
                 ///Print grade, dropdown or text
                 if ($auser->timemarked > 0) {
                     $teachermodified = '<div id="tt' . $auser->id . '">' . userdate($auser->timemarked) . '</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '">' . $final_grade->str_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 } else {
                     $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '">' . $final_grade->str_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $menu = choose_from_menu(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 }
                 ///Print Comment
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . shorten_text(strip_tags($final_grade->str_feedback), 15) . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $comment = '<div id="com' . $auser->id . '">' . shorten_text(strip_tags($auser->submissioncomment), 15) . '</div>';
                     }
                 }
             } else {
                 $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                 $status = '<div id="st' . $auser->id . '">&nbsp;</div>';
                 if ($final_grade->locked or $final_grade->overridden) {
                     $grade = '<div id="g' . $auser->id . '">' . $final_grade->str_grade . '</div>';
                 } else {
                     if ($quickgrade) {
                         // allow editing
                         $menu = choose_from_menu(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                         $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                     } else {
                         $grade = '<div id="g' . $auser->id . '">-</div>';
                     }
                 }
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . $final_grade->str_feedback . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $comment = '<div id="com' . $auser->id . '">&nbsp;</div>';
                     }
                 }
             }
             if (empty($auser->status)) {
                 /// Confirm we have exclusively 0 or 1
                 $auser->status = 0;
             } else {
                 $auser->status = 1;
             }
             $buttontext = $auser->status == 1 ? $strupdate : $strgrade;
             ///No more buttons, we use popups ;-).
             $popup_url = '/mod/assignment/submissions.php?id=' . $this->cm->id . '&amp;userid=' . $auser->id . '&amp;mode=single' . '&amp;offset=' . $offset++;
             $button = link_to_popup_window($popup_url, 'grade' . $auser->id, $buttontext, 600, 780, $buttontext, 'none', true, 'button' . $auser->id);
             $status = '<div id="up' . $auser->id . '" class="s' . $auser->status . '">' . $button . '</div>';
             $finalgrade = '<span id="finalgrade_' . $auser->id . '">' . $final_grade->str_grade . '</span>';
             $outcomes = '';
             if ($uses_outcomes) {
                 foreach ($grading_info->outcomes as $n => $outcome) {
                     $outcomes .= '<div class="outcome"><label>' . $outcome->name . '</label>';
                     $options = make_grades_menu(-$outcome->scaleid);
                     if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
                         $options[0] = get_string('nooutcome', 'grades');
                         $outcomes .= ': <span id="outcome_' . $n . '_' . $auser->id . '">' . $options[$outcome->grades[$auser->id]->grade] . '</span>';
                     } else {
                         $outcomes .= ' ';
                         $outcomes .= choose_from_menu($options, 'outcome_' . $n . '[' . $auser->id . ']', $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_' . $n . '_' . $auser->id);
                     }
                     $outcomes .= '</div>';
                 }
             }
             $row = array($picture, fullname($auser), $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
             if ($uses_outcomes) {
                 $row[] = $outcomes;
             }
             $table->add_data($row);
         }
     }
     /// Print quickgrade form around the table
     if ($quickgrade) {
         echo '<form action="submissions.php" id="fastg" method="post">';
         echo '<div>';
         echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
         echo '<input type="hidden" name="mode" value="fastgrade" />';
         echo '<input type="hidden" name="page" value="' . $page . '" />';
         echo '</div>';
         //echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
     }
     $table->print_html();
     /// Print the whole table
     if ($quickgrade) {
         echo '<div style="text-align:center"><input type="submit" name="fastg" value="' . get_string('saveallfeedback', 'assignment') . '" /></div>';
         echo '</form>';
     }
     /// End of fast grading form
     /// Mini form for setting user preference
     echo '<br />';
     echo '<form id="options" action="submissions.php?id=' . $this->cm->id . '" method="post">';
     echo '<div>';
     echo '<input type="hidden" id="updatepref" name="updatepref" value="1" />';
     echo '<table id="optiontable" align="right">';
     echo '<tr align="right"><td>';
     echo '<label for="perpage">' . get_string('pagesize', 'assignment') . '</label>';
     echo ':</td>';
     echo '<td>';
     echo '<input type="text" id="perpage" name="perpage" size="1" value="' . $perpage . '" />';
     helpbutton('pagesize', get_string('pagesize', 'assignment'), 'assignment');
     echo '</td></tr>';
     echo '<tr align="right">';
     echo '<td>';
     print_string('quickgrade', 'assignment');
     echo ':</td>';
     echo '<td>';
     if ($quickgrade) {
         echo '<input type="checkbox" name="quickgrade" value="1" checked="checked" />';
     } else {
         echo '<input type="checkbox" name="quickgrade" value="1" />';
     }
     helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment') . '</p></div>';
     echo '</td></tr>';
     echo '<tr>';
     echo '<td colspan="2" align="right">';
     echo '<input type="submit" value="' . get_string('savepreferences') . '" />';
     echo '</td></tr></table>';
     echo '</div>';
     echo '</form>';
     ///End of mini form
     print_footer($this->course);
 }
Example #6
0
/**
 * Returns a list of issued iomadcertificates - sorted for report.
 *
 * @param int $iomadcertificateid
 * @param string $sort the sort order
 * @param bool $groupmode are we in group mode ?
 * @param stdClass $cm the course module
 * @param int $page offset
 * @param int $perpage total per page
 * @return stdClass the users
 */
function iomadcertificate_get_issues($iomadcertificateid, $sort = "ci.timecreated ASC", $groupmode, $cm, $page = 0, $perpage = 0)
{
    global $CFG, $DB;
    // get all users that can manage this iomadcertificate to exclude them from the report.
    $context = context_module::instance($cm->id);
    $conditionssql = '';
    $conditionsparams = array();
    if ($certmanagers = array_keys(get_users_by_capability($context, 'mod/iomadcertificate:manage', 'u.id'))) {
        list($sql, $params) = $DB->get_in_or_equal($certmanagers, SQL_PARAMS_NAMED, 'cert');
        $conditionssql .= "AND NOT u.id {$sql} \n";
        $conditionsparams += $params;
    }
    $restricttogroup = false;
    if ($groupmode) {
        $currentgroup = groups_get_activity_group($cm);
        if ($currentgroup) {
            $restricttogroup = true;
            $groupusers = array_keys(groups_get_members($currentgroup, 'u.*'));
            if (empty($groupusers)) {
                return array();
            }
        }
    }
    $restricttogrouping = false;
    // if groupmembersonly used, remove users who are not in any group
    if (!empty($CFG->enablegroupings) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $restricttogrouping = true;
        } else {
            return array();
        }
    }
    if ($restricttogroup || $restricttogrouping) {
        if ($restricttogroup) {
            $allowedusers = $groupusers;
        } else {
            if ($restricttogroup && $restricttogrouping) {
                $allowedusers = array_intersect($groupusers, $groupingusers);
            } else {
                $allowedusers = $groupingusers;
            }
        }
        list($sql, $params) = $DB->get_in_or_equal($allowedusers, SQL_PARAMS_NAMED, 'grp');
        $conditionssql .= "AND u.id {$sql} \n";
        $conditionsparams += $params;
    }
    $page = (int) $page;
    $perpage = (int) $perpage;
    // Get all the users that have iomadcertificates issued, should only be one issue per user for a iomadcertificate
    $allparams = $conditionsparams + array('iomadcertificateid' => $iomadcertificateid);
    $users = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated\n                                   FROM {user} u\n                                   INNER JOIN {iomadcertificate_issues} ci\n                                   ON u.id = ci.userid\n                                   WHERE u.deleted = 0\n                                   AND ci.iomadcertificateid = :iomadcertificateid\n                                   {$conditionssql}\n                                   ORDER BY {$sort}", $allparams, $page * $perpage, $perpage);
    return $users;
}
Example #7
0
 /**
  *  Display all the submissions ready for grading
  *
  * @global object
  * @global object
  * @global object
  * @global object
  * @param string $message
  * @return bool|void
  */
 function display_submissions($message = '')
 {
     global $CFG, $DB, $USER, $DB, $OUTPUT;
     require_once $CFG->libdir . '/gradelib.php';
     /* first we check to see if the form has just been submitted
      * to request user_preference updates
      */
     if (isset($_POST['updatepref'])) {
         $perpage = optional_param('perpage', 10, PARAM_INT);
         $perpage = $perpage <= 0 ? 10 : $perpage;
         set_user_preference('assignment_perpage', $perpage);
         set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
     }
     /* next we get perpage and quickgrade (allow quick grade) params
      * from database
      */
     $perpage = get_user_preferences('assignment_perpage', 10);
     $quickgrade = get_user_preferences('assignment_quickgrade', 0);
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
     if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
         $uses_outcomes = true;
     } else {
         $uses_outcomes = false;
     }
     $page = optional_param('page', 0, PARAM_INT);
     $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
     /// Some shortcuts to make the code read better
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $tabindex = 1;
     //tabindex for quick grading tabbing; Not working for dropdowns yet
     add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id=' . $this->cm->id, $this->assignment->id, $this->cm->id);
     $navigation = build_navigation($this->strsubmissions, $this->cm);
     print_header_simple(format_string($this->assignment->name, true), "", $navigation, '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
     $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
     if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
         echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">' . get_string('seeallcoursegrades', 'grades') . '</a></div>';
     }
     if (!empty($message)) {
         echo $message;
         // display messages here if any
     }
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Check to see if groups are being used in this assignment
     /// find out current groups mode
     $groupmode = groups_get_activity_groupmode($cm);
     $currentgroup = groups_get_activity_group($cm, true);
     groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
     /// Get all ppl that are allowed to submit assignments
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
     if ($uses_outcomes) {
         $tablecolumns[] = 'outcome';
         // no sorting based on outcomes column
     }
     $tableheaders = array('', get_string('fullname'), get_string('grade'), get_string('comment', 'assignment'), get_string('lastmodified') . ' (' . get_string('submission', 'assignment') . ')', get_string('lastmodified') . ' (' . get_string('grade') . ')', get_string('status'), get_string('finalgrade', 'grades'));
     if ($uses_outcomes) {
         $tableheaders[] = get_string('outcome', 'grades');
     }
     require_once $CFG->libdir . '/tablelib.php';
     $table = new flexible_table('mod-assignment-submissions');
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
     $table->define_baseurl($CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id . '&amp;currentgroup=' . $currentgroup);
     $table->sortable(true, 'lastname');
     //sorted by lastname by default
     $table->collapsible(true);
     $table->initialbars(true);
     $table->column_suppress('picture');
     $table->column_suppress('fullname');
     $table->column_class('picture', 'picture');
     $table->column_class('fullname', 'fullname');
     $table->column_class('grade', 'grade');
     $table->column_class('submissioncomment', 'comment');
     $table->column_class('timemodified', 'timemodified');
     $table->column_class('timemarked', 'timemarked');
     $table->column_class('status', 'status');
     $table->column_class('finalgrade', 'finalgrade');
     if ($uses_outcomes) {
         $table->column_class('outcome', 'outcome');
     }
     $table->set_attribute('cellspacing', '0');
     $table->set_attribute('id', 'attempts');
     $table->set_attribute('class', 'submissions');
     $table->set_attribute('width', '100%');
     //$table->set_attribute('align', 'center');
     $table->no_sorting('finalgrade');
     $table->no_sorting('outcome');
     // Start working -- this is necessary as soon as the niceties are over
     $table->setup();
     if (empty($users)) {
         echo $OUTPUT->heading(get_string('nosubmitusers', 'assignment'));
         return true;
     }
     /// Construct the SQL
     if ($where = $table->get_sql_where()) {
         $where .= ' AND ';
     }
     if ($sort = $table->get_sql_sort()) {
         $sort = ' ORDER BY ' . $sort;
     }
     $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                       s.id AS submissionid, s.grade, s.submissioncomment,
                       s.timemodified, s.timemarked,
                       COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
     $sql = 'FROM {user} u ' . 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
                                                               AND s.assignment = ' . $this->assignment->id . ' ' . 'WHERE ' . $where . 'u.id IN (' . implode(',', $users) . ') ';
     $table->pagesize($perpage, count($users));
     ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
     $offset = $page * $perpage;
     $strupdate = get_string('update');
     $strgrade = get_string('grade');
     $grademenu = make_grades_menu($this->assignment->grade);
     if (($ausers = $DB->get_records_sql($select . $sql . $sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
         $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
         foreach ($ausers as $auser) {
             $final_grade = $grading_info->items[0]->grades[$auser->id];
             $grademax = $grading_info->items[0]->grademax;
             $final_grade->formatted_grade = round($final_grade->grade, 2) . ' / ' . round($grademax, 2);
             $locked_overridden = 'locked';
             if ($final_grade->overridden) {
                 $locked_overridden = 'overridden';
             }
             /// Calculate user status
             $auser->status = $auser->timemarked > 0 && $auser->timemarked >= $auser->timemodified;
             $picture = $OUTPUT->user_picture(moodle_user_picture::make($auser, $course->id));
             if (empty($auser->submissionid)) {
                 $auser->grade = -1;
                 //no submission yet
             }
             if (!empty($auser->submissionid)) {
                 ///Prints student answer and student modified date
                 ///attach file or print link to student answer, depending on the type of the assignment.
                 ///Refer to print_student_answer in inherited classes.
                 if ($auser->timemodified > 0) {
                     $studentmodified = '<div id="ts' . $auser->id . '">' . $this->print_student_answer($auser->id) . userdate($auser->timemodified) . '</div>';
                 } else {
                     $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 }
                 ///Print grade, dropdown or text
                 if ($auser->timemarked > 0) {
                     $teachermodified = '<div id="tt' . $auser->id . '">' . userdate($auser->timemarked) . '</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '" class="' . $locked_overridden . '">' . $final_grade->formatted_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'));
                             $select->nothingvalue = '-1';
                             $select->tabindex = $tabindex++;
                             $menu = $OUTPUT->select($select);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 } else {
                     $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '" class="' . $locked_overridden . '">' . $final_grade->formatted_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'));
                             $select->nothingvalue = '-1';
                             $select->tabindex = $tabindex++;
                             $menu = $OUTPUT->select($select);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 }
                 ///Print Comment
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . shorten_text(strip_tags($final_grade->str_feedback), 15) . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $comment = '<div id="com' . $auser->id . '">' . shorten_text(strip_tags($auser->submissioncomment), 15) . '</div>';
                     }
                 }
             } else {
                 $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                 $status = '<div id="st' . $auser->id . '">&nbsp;</div>';
                 if ($final_grade->locked or $final_grade->overridden) {
                     $grade = '<div id="g' . $auser->id . '">' . $final_grade->formatted_grade . '</div>';
                 } else {
                     if ($quickgrade) {
                         // allow editing
                         $select = html_select::make(make_grades_menu($this->assignment->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'));
                         $select->nothingvalue = '-1';
                         $select->tabindex = $tabindex++;
                         $menu = $OUTPUT->select($select);
                         $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                     } else {
                         $grade = '<div id="g' . $auser->id . '">-</div>';
                     }
                 }
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . $final_grade->str_feedback . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $comment = '<div id="com' . $auser->id . '">&nbsp;</div>';
                     }
                 }
             }
             if (empty($auser->status)) {
                 /// Confirm we have exclusively 0 or 1
                 $auser->status = 0;
             } else {
                 $auser->status = 1;
             }
             $buttontext = $auser->status == 1 ? $strupdate : $strgrade;
             ///No more buttons, we use popups ;-).
             $popup_url = '/mod/assignment/submissions.php?id=' . $this->cm->id . '&userid=' . $auser->id . '&mode=single' . '&offset=' . $offset++;
             $link = html_link::make($popup_url, $buttontext);
             $link->add_action(new popup_action('click', $link->url, 'grade' . $auser->id, array('height' => 600, 'width' => 700)));
             $link->title = $buttontext;
             $button = $OUTPUT->link($link);
             $status = '<div id="up' . $auser->id . '" class="s' . $auser->status . '">' . $button . '</div>';
             $finalgrade = '<span id="finalgrade_' . $auser->id . '">' . $final_grade->str_grade . '</span>';
             $outcomes = '';
             if ($uses_outcomes) {
                 foreach ($grading_info->outcomes as $n => $outcome) {
                     $outcomes .= '<div class="outcome"><label>' . $outcome->name . '</label>';
                     $options = make_grades_menu(-$outcome->scaleid);
                     if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
                         $options[0] = get_string('nooutcome', 'grades');
                         $outcomes .= ': <span id="outcome_' . $n . '_' . $auser->id . '">' . $options[$outcome->grades[$auser->id]->grade] . '</span>';
                     } else {
                         $outcomes .= ' ';
                         $select = html_select::make($options, 'outcome_' . $n . '[' . $auser->id . ']', $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'));
                         $select->nothingvalue = '0';
                         $select->tabindex = $tabindex++;
                         $select->id = 'outcome_' . $n . '_' . $auser->id;
                         $outcomes .= $OUTPUT->select($select);
                     }
                     $outcomes .= '</div>';
                 }
             }
             $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
             $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
             if ($uses_outcomes) {
                 $row[] = $outcomes;
             }
             $table->add_data($row);
         }
     }
     /// Print quickgrade form around the table
     if ($quickgrade) {
         echo '<form action="submissions.php" id="fastg" method="post">';
         echo '<div>';
         echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
         echo '<input type="hidden" name="mode" value="fastgrade" />';
         echo '<input type="hidden" name="page" value="' . $page . '" />';
         echo '</div>';
     }
     $table->print_html();
     /// Print the whole table
     if ($quickgrade) {
         $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
         echo '<div class="fgcontrols">';
         echo '<div class="emailnotification">';
         echo '<label for="mailinfo">' . get_string('enableemailnotification', 'assignment') . '</label>';
         echo '<input type="hidden" name="mailinfo" value="0" />';
         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" ' . $lastmailinfo . ' />';
         echo $OUTPUT->help_icon(moodle_help_icon::make('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment')) . '</p></div>';
         echo '</div>';
         echo '<div class="fastgbutton"><input type="submit" name="fastg" value="' . get_string('saveallfeedback', 'assignment') . '" /></div>';
         echo '</div>';
         echo '</form>';
     }
     /// End of fast grading form
     /// Mini form for setting user preference
     echo '<div class="qgprefs">';
     echo '<form id="options" action="submissions.php?id=' . $this->cm->id . '" method="post"><div>';
     echo '<input type="hidden" name="updatepref" value="1" />';
     echo '<table id="optiontable">';
     echo '<tr><td>';
     echo '<label for="perpage">' . get_string('pagesize', 'assignment') . '</label>';
     echo '</td>';
     echo '<td>';
     echo '<input type="text" id="perpage" name="perpage" size="1" value="' . $perpage . '" />';
     echo $OUTPUT->help_icon(moodle_help_icon::make('pagesize', get_string('pagesize', 'assignment'), 'assignment'));
     echo '</td></tr>';
     echo '<tr><td>';
     echo '<label for="quickgrade">' . get_string('quickgrade', 'assignment') . '</label>';
     echo '</td>';
     echo '<td>';
     $checked = $quickgrade ? 'checked="checked"' : '';
     echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" ' . $checked . ' />';
     echo $OUTPUT->help_icon(moodle_help_icon::make('quickgrade', get_string('quickgrade', 'assignment'), 'assignment')) . '</p></div>';
     echo '</td></tr>';
     echo '<tr><td colspan="2">';
     echo '<input type="submit" value="' . get_string('savepreferences') . '" />';
     echo '</td></tr></table>';
     echo '</div></form></div>';
     ///End of mini form
     echo $OUTPUT->footer();
 }
function geogebra_view_results($geogebra, $context, $cm, $course, $action)
{
    global $CFG, $DB, $OUTPUT, $PAGE, $USER;
    if ($action == 'submitgrade') {
        // Upgrade submitted grade
        $grade = optional_param('grade', '', PARAM_INT);
        $gradecomment = optional_param_array('comment_editor', '', PARAM_RAW);
        $attemptid = optional_param('attemptid', '', PARAM_INT);
        $attempt = geogebra_get_attempt($attemptid);
        parse_str($attempt->vars, $parsedvars);
        $parsedvars['grade'] = $grade;
        $attempt->vars = http_build_query($parsedvars, '', '&');
        geogebra_update_attempt($attemptid, $attempt->vars, GEOGEBRA_UPDATE_TEACHER, $gradecomment['text']);
    }
    // Show students list with their results
    require_once $CFG->libdir . '/gradelib.php';
    $perpage = optional_param('perpage', 10, PARAM_INT);
    $perpage = $perpage <= 0 ? 10 : $perpage;
    $page = optional_param('page', 0, PARAM_INT);
    // Find out current groups mode
    $groupmode = groups_get_activity_groupmode($cm);
    $currentgroup = groups_get_activity_group($cm, true);
    // Get all ppl that are allowed to submit geogebra
    list($esql, $params) = get_enrolled_sql($context, 'mod/geogebra:submit', $currentgroup);
    $sql = "SELECT u.id FROM {user} u " . "LEFT JOIN ({$esql}) eu ON eu.id=u.id " . "WHERE u.deleted = 0 AND eu.id=u.id ";
    $users = $DB->get_records_sql($sql, $params);
    if (!empty($users)) {
        $users = array_keys($users);
    }
    // If groupmembersonly used, remove users who are not in any group
    if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $users = array_intersect($users, array_keys($groupingusers));
        }
    }
    // TODO: Review to show all users information
    if (!empty($users)) {
        // Create results table
        $extrafields = get_extra_user_fields($context);
        $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields, array('attempts', 'duration', 'grade', 'comment', 'datestudent', 'dateteacher', 'status'));
        $extrafieldnames = array();
        foreach ($extrafields as $field) {
            $extrafieldnames[] = get_user_field_name($field);
        }
        $tableheaders = array_merge(array('', get_string('fullnameuser')), $extrafieldnames, array(get_string('attempts', 'geogebra'), get_string('duration', 'geogebra'), get_string('grade'), get_string('comment', 'geogebra'), get_string('lastmodifiedsubmission', 'geogebra'), get_string('lastmodifiedgrade', 'geogebra'), get_string('status', 'geogebra')));
        require_once $CFG->libdir . '/tablelib.php';
        $table = new flexible_table('mod-geogebra-results');
        $table->define_columns($tablecolumns);
        $table->define_headers($tableheaders);
        $table->define_baseurl($CFG->wwwroot . '/mod/geogebra/report.php?id=' . $cm->id . '&amp;currentgroup=' . $currentgroup);
        $table->sortable(true, 'lastname');
        // Sorted by lastname by default
        $table->collapsible(true);
        $table->initialbars(true);
        $table->column_suppress('picture');
        $table->column_suppress('fullname');
        $table->column_class('picture', 'picture');
        $table->column_class('fullname', 'fullname');
        foreach ($extrafields as $field) {
            $table->column_class($field, $field);
        }
        $table->set_attribute('cellspacing', '0');
        $table->set_attribute('id', 'attempts');
        $table->set_attribute('class', 'results generaltable generalbox');
        $table->set_attribute('width', '100%');
        $table->no_sorting('attempts');
        $table->no_sorting('duration');
        $table->no_sorting('grade');
        $table->no_sorting('comment');
        $table->no_sorting('datestudent');
        $table->no_sorting('dateteacher');
        $table->no_sorting('status');
        // Start working -- this is necessary as soon as the niceties are over
        $table->setup();
        // Construct the SQL
        list($where, $params) = $table->get_sql_where();
        if ($where) {
            $where .= ' AND ';
        }
        if ($sort = $table->get_sql_sort()) {
            $sort = ' ORDER BY ' . $sort;
        }
        $ufields = user_picture::fields('u', $extrafields);
        $select = "SELECT {$ufields} ";
        $sql = 'FROM {user} u WHERE ' . $where . 'u.id IN (' . implode(',', $users) . ') ';
        $ausers = $DB->get_records_sql($select . $sql . $sort, $params, $table->get_page_start(), $table->get_page_size());
        $table->pagesize($perpage, count($users));
        $offset = $page * $perpage;
        // Offset used to calculate index of student in that particular query, needed for the pop up to know who's next
        if ($ausers !== false) {
            // $grading_info = grade_get_grades($course->id, 'mod', 'geogebra', $geogebra->id, array_keys($ausers));
            foreach ($ausers as $auser) {
                $picture = $OUTPUT->user_picture($auser);
                $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $context)) . '</a>';
                $row = array($picture, $userlink);
                $extradata = array();
                foreach ($extrafields as $field) {
                    $extradata[] = $auser->{$field};
                }
                $row += $extradata;
                // Attempts summary
                $attempts = geogebra_get_user_attempts($geogebra->id, $auser->id);
                $attemptssummary = geogebra_get_user_grades($geogebra, $auser->id);
                if ($attemptssummary) {
                    $row[] = $attemptssummary->attempts;
                    $row[] = geogebra_time2str($attemptssummary->duration);
                    $row[] = $attemptssummary->grade;
                    $rowclass = $attemptssummary->attempts > 0 ? 'summary-row' : "";
                } else {
                    $row[] = "";
                    $row[] = "";
                    $row[] = "";
                    $rowclass = "";
                }
                $row[] = "";
                $row[] = "";
                $row[] = "";
                $row[] = "";
                $table->add_data($row, $rowclass);
                // Show attempts information
                foreach ($attempts as $attempt) {
                    $row = array();
                    // In the attempts row, show only the summary of the attempt (it's not necessary to repeat user information)
                    for ($i = 0; $i < count($extradata) + 2; $i++) {
                        array_push($row, '');
                    }
                    // Attempt information
                    $row = geogebra_get_attempt_row($geogebra, $attempt, $auser, $cm, $context, $row);
                    /*array_push($row, $attempt->duration);
                      array_push($row, $attempt->grade);
                      array_push($row, $attempt->comment);*/
                    $table->add_data($row);
                }
            }
        }
        $table->print_html();
        // Print the whole table
    } else {
        echo $OUTPUT->notification(get_string('msg_nosessions', 'geogebra'), 'notifymessage');
    }
}
 /**
  * get_sql_filter
  *
  * @param xxx $data
  * @return xxx
  */
 function get_sql_filter($data)
 {
     global $DB, $hotpot;
     $filter = '';
     $params = array();
     if (($value = $data['value']) && ($operator = $data['operator'])) {
         $userids = array();
         if (substr($value, 0, 5) == 'group') {
             if (substr($value, 5, 3) == 'ing') {
                 $gids = groups_get_all_groupings($hotpot->course->id);
                 $gid = intval(substr($value, 8));
                 if ($gids && array_key_exists($gid, $gids) && ($members = groups_get_grouping_members($gid))) {
                     $userids = array_keys($members);
                 }
             } else {
                 $gids = groups_get_all_groups($hotpot->course->id);
                 $gid = intval(substr($value, 5));
                 if ($gids && array_key_exists($gid, $gids) && ($members = groups_get_members($gid))) {
                     $userids = array_keys($members);
                 }
             }
         }
         if (count($userids)) {
             switch ($operator) {
                 case 1:
                     // is equal to
                     list($filter, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, '', true);
                     break;
                 case 2:
                     // isn't equal to
                     list($filter, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, '', false);
                     break;
             }
             if ($filter) {
                 $filter = 'id ' . $filter;
             }
         }
     }
     // no userids found
     return array($filter, $params);
 }
Example #10
0
function certificate_get_issues($certificate, $user, $sort = "u.studentname ASC", $groupmode, $cm)
{
    global $CFG;
    //get all users that can manage this certificate to exclude them from the report.
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $certmanagers = get_users_by_capability($context, 'mod/certificate:manage', 'u.id');
    //get all the users that have certificates issued.
    $users = get_records_sql("SELECT u.*,u.picture, s.code, s.timecreated, s.certdate, s.studentname, s.reportgrade\n                              FROM {$CFG->prefix}certificate_issues s,\n                                   {$CFG->prefix}user u\n                             WHERE s.certificateid = '{$certificate}'\n                               AND s.userid = u.id\n                               AND s.certdate > 0\n                             ORDER BY {$sort}");
    //now exclude all the certmanagers.
    foreach ($users as $id => $user) {
        if (isset($certmanagers[$id])) {
            //exclude certmanagers.
            unset($users[$id]);
        }
    }
    // if groupmembersonly used, remove users who are not in any group
    if (!empty($users) and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $users = array_intersect($users, array_keys($groupingusers));
        }
    }
    if (!$groupmode) {
        return $users;
    } else {
        $currentgroup = groups_get_activity_group($cm);
        if ($currentgroup) {
            $groupusers = groups_get_members($currentgroup, 'u.*');
            if (empty($groupusers)) {
                return array();
            }
            foreach ($groupusers as $id => $gpuser) {
                if (!isset($users[$id])) {
                    //remove this user as it isn't in the group!
                    unset($users[$id]);
                }
            }
        }
        return $users;
    }
}
 /**
  * Returns a list of users by gradebook roles.
  */
 public function get_gradebook_users(array $userids = null)
 {
     global $DB, $CFG;
     // Must have gradebook roles.
     if (empty($CFG->gradebookroles)) {
         return null;
     }
     $gradebookroles = explode(", ", $CFG->gradebookroles);
     if (!($df = $this->df)) {
         return;
     }
     if (!empty($CFG->enablegroupings) and $df->cm->groupmembersonly) {
         $groupingsusers = groups_get_grouping_members($df->cm->groupingid, 'u.id', 'u.id');
         $gusers = $groupingsusers ? array_keys($groupingsusers) : null;
     }
     if (!empty($userids)) {
         if (!empty($gusers)) {
             $gusers = array_intersect($userids, $gusers);
         } else {
             $gusers = $userids;
         }
     }
     $roleusers = array();
     if (isset($gusers)) {
         if (!empty($gusers)) {
             list($inuids, $params) = $DB->get_in_or_equal($gusers, SQL_PARAMS_NAMED, 'u');
             foreach ($gradebookroles as $roleid) {
                 $roleusers = $roleusers + get_role_users($roleid, $df->context, true, user_picture::fields('u'), 'u.lastname ASC', true, $df->currentgroup, '', '', "u.id {$inuids}", $params);
             }
         }
     } else {
         foreach ($gradebookroles as $roleid) {
             $roleusers = $roleusers + get_role_users($roleid, $df->context, true, user_picture::fields('u'), 'u.lastname ASC', true, $df->currentgroup);
         }
     }
     return $roleusers;
 }
 /**
  * display a marking popup window for teachers marking a team member's submission
  * teacher can not reverse student submission to draft.
  * @param $extra_javascript
  */
 function display_member_marking_window($extra_javascript)
 {
     global $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->libdir . '/tablelib.php';
     $userid = required_param('userid', PARAM_INT);
     $offset = required_param('offset', PARAM_INT);
     //offset for where to start looking for student.
     if (!($user = get_record('user', 'id', $userid))) {
         error('No such user!');
     }
     if (!($submission = $this->get_submission($user->id))) {
         $submission = $this->prepare_new_submission($userid);
     }
     if ($submission->timemodified > $submission->timemarked) {
         $subtype = 'assignmentnew';
     } else {
         $subtype = 'assignmentold';
     }
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
     $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
     /// construct SQL, using current offset to find the data of the next student
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Get all ppl that can submit assignments
     $currentgroup = groups_get_activity_group($cm);
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $nextid = 0;
     if ($users) {
         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                           s.id AS submissionid, s.grade, s.submissioncomment,
                           s.timemodified, s.timemarked,
                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
         $sql = 'FROM ' . $CFG->prefix . 'user u ' . 'LEFT JOIN ' . $CFG->prefix . 'assignment_submissions s ON u.id = s.userid
                                                                   AND s.assignment = ' . $this->assignment->id . ' ' . 'WHERE u.id IN (' . implode(',', $users) . ') ';
         if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
             $sort = 'ORDER BY ' . $sort . ' ';
         }
         if (($auser = get_records_sql($select . $sql . $sort, $offset + 1, 1)) !== false) {
             $nextuser = array_shift($auser);
             /// Calculate user status
             $nextuser->status = $nextuser->timemarked > 0 && $nextuser->timemarked >= $nextuser->timemodified;
             $nextid = $nextuser->id;
         }
     }
     print_header(get_string('feedback', 'assignment') . ':' . fullname($user, true) . ':' . format_string($this->assignment->name));
     /// Print any extra javascript needed for saveandnext
     echo $extra_javascript;
     ///SOme javascript to help with setting up >.>
     echo '<script type="text/javascript">' . "\n";
     echo 'function setNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'next\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo '}' . "\n";
     echo 'function saveNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo 'document.getElementById(\'submitform\').saveuserid.value="' . $userid . '";' . "\n";
     echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;' . "\n";
     echo '}' . "\n";
     echo '</script>' . "\n";
     echo '<table cellspacing="0" class="feedback ' . $subtype . '" >';
     ///Start of teacher info row
     echo '<tr>';
     echo '<td class="picture teacher">';
     if ($submission->teacher) {
         $teacher = get_record('user', 'id', $submission->teacher);
     } else {
         global $USER;
         $teacher = $USER;
     }
     print_user_picture($teacher, $this->course->id, $teacher->picture);
     echo '</td>';
     echo '<td class="content">';
     echo '<form id="submitform" action="submissions.php" method="post">';
     echo '<div>';
     // xhtml compatibility - invisiblefieldset was breaking layout here
     echo '<input type="hidden" name="offset" value="' . ($offset + 1) . '" />';
     echo '<input type="hidden" name="userid" value="' . $userid . '" />';
     echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
     echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
     echo '<input type="hidden" name="mode" value="grade" />';
     echo '<input type="hidden" name="menuindex" value="0" />';
     //selected menu index
     //new hidden field, initialized to -1.
     echo '<input type="hidden" name="saveuserid" value="-1" />';
     if ($submission->timemarked) {
         echo '<div class="from">';
         echo '<div class="fullname">' . fullname($teacher, true) . '</div>';
         echo '<div class="time">' . userdate($submission->timemarked) . '</div>';
         echo '</div>';
     }
     echo '<div class="grade"><label for="menugrade">' . get_string('grade') . '</label> ';
     choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
     echo '</div>';
     echo '<div class="clearer"></div>';
     echo '<div class="finalgrade">' . get_string('finalgrade', 'grades') . ': ' . $grading_info->items[0]->grades[$userid]->str_grade . '</div>';
     echo '<div class="clearer"></div>';
     if (!empty($CFG->enableoutcomes)) {
         foreach ($grading_info->outcomes as $n => $outcome) {
             echo '<div class="outcome"><label for="menuoutcome_' . $n . '">' . $outcome->name . '</label> ';
             $options = make_grades_menu(-$outcome->scaleid);
             if ($outcome->grades[$submission->userid]->locked) {
                 $options[0] = get_string('nooutcome', 'grades');
                 echo $options[$outcome->grades[$submission->userid]->grade];
             } else {
                 choose_from_menu($options, 'outcome_' . $n . '[' . $userid . ']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_' . $n);
             }
             echo '</div>';
             echo '<div class="clearer"></div>';
         }
     }
     $this->preprocess_submission($submission);
     if ($disabled) {
         echo '<div class="disabledfeedback">' . $grading_info->items[0]->grades[$userid]->str_feedback . '</div>';
     } else {
         print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
         if ($this->usehtmleditor) {
             echo '<input type="hidden" name="format" value="' . FORMAT_HTML . '" />';
         } else {
             echo '<div class="format">';
             choose_from_menu(format_text_menu(), "format", $submission->format, "");
             helpbutton("textformat", get_string("helpformatting"));
             echo '</div>';
         }
     }
     $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
     ///Print Buttons in Single View
     echo '<input type="hidden" name="mailinfo" value="0" />';
     echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" ' . $lastmailinfo . ' /><label for="mailinfo">' . get_string('enableemailnotification', 'assignment') . '</label>';
     echo '<div class="buttons">';
     echo '<input type="submit" name="submit" value="' . get_string('savechanges') . '" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
     echo '<input type="submit" name="cancel" value="' . get_string('cancel') . '" />';
     //if there are more to be graded.
     if ($nextid) {
         echo '<input type="submit" name="saveandnext" value="' . get_string('saveandnext') . '" onclick="saveNext()" />';
         echo '<input type="submit" name="next" value="' . get_string('next') . '" onclick="setNext();" />';
     }
     echo '</div>';
     echo '</div></form>';
     $customfeedback = $this->custom_feedbackform($submission, true);
     if (!empty($customfeedback)) {
         echo $customfeedback;
     }
     echo '</td></tr>';
     ///End of teacher info row, Start of student info row
     echo '<tr>';
     echo '<td class="picture user">';
     print_user_picture($user, $this->course->id, $user->picture);
     echo '</td>';
     echo '<td class="topic">';
     echo '<div class="from">';
     echo '<div class="fullname">' . fullname($user, true) . '</div>';
     if ($submission->timemodified) {
         echo '<div class="time">' . userdate($submission->timemodified) . $this->display_lateness($submission->timemodified) . '</div>';
     }
     echo '<div>' . $this->print_student_answer($user->id) . '</div>';
     echo '</div>';
     echo '</td>';
     echo '</tr>';
     ///End of student info row
     echo '</table>';
     if (!$disabled and $this->usehtmleditor) {
         use_html_editor();
     }
     print_footer('none');
 }
Example #13
0
 /**
  *  Display a single submission, ready for grading on a popup window
  * Justin: I just lifted this from assignments/lib.php because  I needed to show the conversation entries properly.beneath the feedback form.
  * This default method prints the teacher info and submissioncomment box at the top and
  * the student info and submission at the bottom.
  * This method also fetches the necessary data in order to be able to
  * provide a "Next submission" button.
  * Calls preprocess_submission() to give assignment type plug-ins a chance
  * to process submissions before they are graded
  * This method gets its arguments from the page parameters userid and offset
  */
 function display_submission($extra_javascript = '')
 {
     global $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->libdir . '/tablelib.php';
     $userid = required_param('userid', PARAM_INT);
     $offset = required_param('offset', PARAM_INT);
     //offset for where to start looking for student.
     if (!($user = get_record('user', 'id', $userid))) {
         error('No such user!');
     }
     if (!($submission = $this->get_submission($user->id))) {
         $submission = $this->prepare_new_submission($userid);
     }
     if ($submission->timemodified > $submission->timemarked) {
         $subtype = 'assignmentnew';
     } else {
         $subtype = 'assignmentold';
     }
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
     $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
     /// construct SQL, using current offset to find the data of the next student
     $course = $this->course;
     $assignment = $this->assignment;
     $cm = $this->cm;
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Get all ppl that can submit assignments
     $currentgroup = groups_get_activity_group($cm);
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $nextid = 0;
     if ($users) {
         $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                           s.id AS submissionid, s.grade, s.submissioncomment,
                           s.timemodified, s.timemarked,
                           COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
         $sql = 'FROM ' . $CFG->prefix . 'user u ' . 'LEFT JOIN ' . $CFG->prefix . 'assignment_submissions s ON u.id = s.userid
                                                                   AND s.assignment = ' . $this->assignment->id . ' ' . 'WHERE u.id IN (' . implode(',', $users) . ') ';
         if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
             $sort = 'ORDER BY ' . $sort . ' ';
         }
         if (($auser = get_records_sql($select . $sql . $sort, $offset + 1, 1)) !== false) {
             $nextuser = array_shift($auser);
             /// Calculate user status
             $nextuser->status = $nextuser->timemarked > 0 && $nextuser->timemarked >= $nextuser->timemodified;
             $nextid = $nextuser->id;
         }
     }
     print_header(get_string('feedback', 'assignment') . ':' . fullname($user, true) . ':' . format_string($this->assignment->name));
     /// Print any extra javascript needed for saveandnext
     echo $extra_javascript;
     ///SOme javascript to help with setting up >.>
     echo '<script type="text/javascript">' . "\n";
     echo 'function setNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'next\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo '}' . "\n";
     echo 'function saveNext(){' . "\n";
     echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';' . "\n";
     echo 'document.getElementById(\'submitform\').userid.value="' . $nextid . '";' . "\n";
     echo 'document.getElementById(\'submitform\').saveuserid.value="' . $userid . '";' . "\n";
     echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;' . "\n";
     echo '}' . "\n";
     echo '</script>' . "\n";
     echo '<table cellspacing="0" class="feedback ' . $subtype . '" >';
     ///Start of teacher info row
     echo '<tr>';
     echo '<td class="picture teacher">';
     //Edited by justin 20081003: otherwise regardlss of which teacher is logged in ,
     //first teacher to write in journal would be shown,
     //if ($submission->teacher) {
     if (false) {
         $teacher = get_record('user', 'id', $submission->teacher);
     } else {
         global $USER;
         $teacher = $USER;
     }
     print_user_picture($teacher, $this->course->id, $teacher->picture);
     echo '</td>';
     echo '<td class="content">';
     echo '<form id="submitform" action="submissions.php" method="post">';
     echo '<div>';
     // xhtml compatibility - invisiblefieldset was breaking layout here
     echo '<input type="hidden" name="offset" value="' . ($offset + 1) . '" />';
     echo '<input type="hidden" name="userid" value="' . $userid . '" />';
     echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
     echo '<input type="hidden" name="mode" value="grade" />';
     echo '<input type="hidden" name="menuindex" value="0" />';
     //selected menu index
     //new hidden field, initialized to -1.
     echo '<input type="hidden" name="saveuserid" value="-1" />';
     if ($submission->timemarked) {
         echo '<div class="from">';
         echo '<div class="fullname">' . fullname($teacher, true) . '</div>';
         echo '<div class="time">' . userdate($submission->timemarked) . '</div>';
         echo '</div>';
     }
     //if we are grading journals
     if ($this->assignment->grade > 0) {
         echo '<div class="grade"><label for="menugrade">' . get_string('grade') . '</label> ';
         choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
         echo '</div>';
         echo '<div class="clearer"></div>';
         echo '<div class="finalgrade">' . get_string('finalgrade', 'grades') . ': ' . $grading_info->items[0]->grades[$userid]->str_grade . '</div>';
         echo '<div class="clearer"></div>';
         if (!empty($CFG->enableoutcomes)) {
             foreach ($grading_info->outcomes as $n => $outcome) {
                 echo '<div class="outcome"><label for="menuoutcome_' . $n . '">' . $outcome->name . '</label> ';
                 $options = make_grades_menu(-$outcome->scaleid);
                 if ($outcome->grades[$submission->userid]->locked) {
                     $options[0] = get_string('nooutcome', 'grades');
                     echo $options[$outcome->grades[$submission->userid]->grade];
                 } else {
                     choose_from_menu($options, 'outcome_' . $n . '[' . $userid . ']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_' . $n);
                 }
                 echo '</div>';
                 echo '<div class="clearer"></div>';
             }
         }
         //if we are not grading journals
     } else {
         echo '<input type="hidden" name="grade" value="-1" />';
     }
     $this->preprocess_submission($submission);
     if ($disabled) {
         echo '<div class="disabledfeedback">' . $grading_info->items[0]->grades[$userid]->str_feedback . '</div>';
     } else {
         //---------------Justin Video Message start 20090105-------------------
         if ($CFG->filter_poodll_journal_video || $CFG->filter_poodll_journal_audio) {
             echo '<a href="#" onclick="document.getElementById(\'teacherrecorder\').style.display=\'block\';">Record Audio/Video</a>';
             echo "<div id='teacherrecorder' style='display: none'>";
             //$rtmplink = "rtmp://{$CFG->rtmp}";
             $rtmplink = $CFG->poodll_media_server;
             //$filename='poodlljournal/' . $this->assignment->id . $submission->userid . time(). rand() . '.flv';
             $filename = 'moddata/assignment/' . $this->assignment->id . '/' . $submission->userid . '/teacher_' . time() . rand() . '.flv';
             $mediadata = fetch_teachersrecorder($filename, "mediafilename");
             echo $mediadata;
             echo '<input type="hidden" value="" id="mediafilename" name="mediafilename" />';
             echo "</div>";
         }
         //---------------Video Message end 20090105---------------------
         //Justin: We never edit old submissions so we show a blank area in the feedback box
         //print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
         print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', "", $this->course->id);
         if ($this->usehtmleditor) {
             echo '<input type="hidden" name="format" value="' . FORMAT_HTML . '" />';
         } else {
             echo '<div class="format">';
             choose_from_menu(format_text_menu(), "format", $submission->format, "");
             helpbutton("textformat", get_string("helpformatting"));
             echo '</div>';
         }
     }
     $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
     ///Print Buttons in Single View
     echo '<input type="hidden" name="mailinfo" value="0" />';
     echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" ' . $lastmailinfo . ' /><label for="mailinfo">' . get_string('enableemailnotification', 'assignment') . '</label>';
     echo '<div class="buttons">';
     echo '<input type="submit" name="submit" value="' . get_string('savechanges') . '" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
     echo '<input type="submit" name="cancel" value="' . get_string('cancel') . '" />';
     //if there are more to be graded.
     if ($nextid) {
         echo '<input type="submit" name="saveandnext" value="' . get_string('saveandnext') . '" onclick="saveNext()" />';
         echo '<input type="submit" name="next" value="' . get_string('next') . '" onclick="setNext();" />';
     }
     echo '</div>';
     echo '</div></form>';
     $customfeedback = $this->custom_feedbackform($submission, true);
     if (!empty($customfeedback)) {
         echo $customfeedback;
     }
     echo '</td></tr>';
     ///End of teacher info row, Start of student info row
     if (!empty($submission)) {
         $comments = explode(COMMENTSDELIM, $submission->data1);
         foreach ($comments as $comment) {
             $commentParts = explode(PARTSDELIM, $comment);
             if (sizeof($commentParts) > 2) {
                 $feedback = $commentParts[0];
                 $personId = $commentParts[1];
                 $comment_date = $commentParts[2];
                 $person = get_record('user', 'id', $personId);
                 /// Print the feedback
                 //print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher));
                 //echo '<table cellspacing="0" class="feedback">';
                 echo '<tr>';
                 echo '<td class="left picture">';
                 if ($person) {
                     print_user_picture($person, $this->course->id, $person->picture);
                 }
                 echo '</td>';
                 echo '<td class="topic">';
                 echo '<div class="from">';
                 if ($person) {
                     echo '<div class="fullname">' . fullname($person) . '</div>';
                 }
                 echo '<div class="time">' . userdate($comment_date) . '</div>';
                 echo '</div>';
                 echo '</td>';
                 echo '</tr>';
                 echo '<tr>';
                 echo '<td class="content" colspan="2">';
                 echo '<div class="comment">';
                 echo format_text($feedback);
                 echo '</div>';
                 echo '</td>';
                 echo '</tr>';
             }
             //end of if sizeof > 2
         }
         //end of for each
     }
     //end of if submission not empty
     ///End of student info row
     echo '</table>';
     if (!$disabled and $this->usehtmleditor) {
         use_html_editor();
     }
     print_footer('none');
 }
 function count_real_submissions($groupid = 0)
 {
     global $CFG;
     $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     // this is all the users with this capability set, in this context or higher
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $this->cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($this->cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     if (empty($users)) {
         return 0;
     }
     $userlists = implode(',', $users);
     // Count the number of assignments that have been submitted and for
     // which a response file has been generated (ie data2 = 'responded',
     // not 'submitted')
     $markedcount = count_records_sql("SELECT COUNT('x')\n                                FROM {$CFG->prefix}assignment_submissions\n                                WHERE assignment = {$this->cm->instance} AND\n                                data2 = '" . ASSIGNMENT_UPLOADPDF_STATUS_RESPONDED . "' AND\n                                userid IN ({$userlists})");
     // Count the number of assignments that have been submitted, but for
     // which a response file has not been generated (ie data2 = 'submitted',
     // not 'responded')
     $unmarkedcount = count_records_sql("SELECT COUNT('x')\n                                FROM {$CFG->prefix}assignment_submissions\n                                WHERE assignment = {$this->cm->instance} AND\n                                data2 = '" . ASSIGNMENT_UPLOADPDF_STATUS_SUBMITTED . "' AND\n                                userid IN ({$userlists})");
     $totalcount = $markedcount + $unmarkedcount;
     if ($unmarkedcount) {
         return "{$totalcount}({$unmarkedcount})";
     } else {
         return $totalcount;
     }
 }
Example #15
0
/// Determine if the current user can participate in this meeting.
$participant = false;
if ($elluminate->sessiontype == 1) {
    $mctx = get_context_instance(CONTEXT_MODULE, $cm->id);
    //Checks to see if the user is a participant in the private meeting
    if (elluminate_is_participant_in_meeting($elluminate, $USER->id)) {
        //then checks to make sure that the user role has the privilege to join a meeting
        $participant = $canjoinmeeting;
    }
} else {
    if ($elluminate->sessiontype == 3) {
        if ($accessallgroups) {
            $participant = $canjoinmeeting;
        } else {
            $isvaliduser = false;
            $groupingusers = groups_get_grouping_members($elluminate->groupingid);
            foreach ($groupingusers as $groupinguser) {
                if (!$isvaliduser) {
                    if ($groupinguser->id == $USER->id) {
                        $isvaliduser = true;
                    }
                    if ($elluminate->creator == $USER->id) {
                        $isvaliduser = true;
                    }
                }
            }
            if ($isvaliduser) {
                $participant = $canjoinmeeting;
            }
        }
    } else {
 /**
  * Creates a zip of all uploaded files and sends a zip to the browser
  * @param unknown $users false => empty zip, true all users, array files from users in array
  */
 public function download_zip($users = array())
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/filelib.php';
     $context = $this->get_context();
     $cm = $this->get_coursemodule();
     $conditions = array();
     $conditions['publication'] = $this->get_instance()->id;
     $filesforzipping = array();
     $fs = get_file_storage();
     $filearea = 'attachment';
     // Find out current groups mode.
     $groupmode = groups_get_activity_groupmode($this->get_coursemodule());
     $currentgroup = groups_get_activity_group($this->get_coursemodule(), true);
     // Get group name for filename.
     $groupname = '';
     // Get all ppl that are allowed to submit assignments.
     list($esql, $params) = get_enrolled_sql($context, 'mod/publication:view', $currentgroup);
     $showall = false;
     if (has_capability('mod/publication:approve', $context) || has_capability('mod/publication:grantextension', $context)) {
         $showall = true;
     }
     if (is_array($users) && count($users) > 0) {
         $customusers = " and u.id IN (" . implode($users, ', ') . ") ";
     } else {
         if ($users == false) {
             $customusers = " AND 1=2 ";
         }
     }
     if ($showall) {
         $sql = 'SELECT u.id FROM {user} u ' . 'LEFT JOIN (' . $esql . ') eu ON eu.id=u.id ' . 'WHERE u.deleted = 0 AND eu.id=u.id ' . $customusers;
     } else {
         $sql = 'SELECT u.id FROM {user} u ' . 'LEFT JOIN (' . $esql . ') eu ON eu.id=u.id ' . 'LEFT JOIN {publication_file} files ON (u.id = files.userid) ' . 'WHERE u.deleted = 0 AND eu.id=u.id ' . $customusers . 'AND files.publication = ' . $this->get_instance()->id . ' ';
         if ($this->get_instance()->mode == PUBLICATION_MODE_UPLOAD) {
             // Mode upload.
             if ($this->get_instance()->obtainteacherapproval) {
                 // Need teacher approval.
                 $where = 'files.teacherapproval = 1';
             } else {
                 // No need for teacher approval.
                 // Teacher only hasnt rejected.
                 $where = '(files.teacherapproval = 1 OR files.teacherapproval IS NULL)';
             }
         } else {
             // Mode import.
             if (!$this->get_instance()->obtainstudentapproval) {
                 // No need to ask student and teacher has approved.
                 $where = 'files.teacherapproval = 1';
             } else {
                 // Student and teacher have approved.
                 $where = 'files.teacherapproval = 1 AND files.studentapproval = 1';
             }
         }
         $sql .= 'AND ' . $where . ' ';
         $sql .= 'GROUP BY u.id';
     }
     $users = $DB->get_records_sql($sql, $params);
     if (!empty($users)) {
         $users = array_keys($users);
     }
     // If groupmembersonly used, remove users who are not in any group.
     if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $filename = str_replace(' ', '_', clean_filename($this->course->shortname . '-' . $this->get_instance()->name . '-' . $groupname . $this->get_instance()->id . '.zip'));
     // Name of new zip file.
     $userfields = get_all_user_name_fields();
     $userfields['id'] = 'id';
     $userfields['username'] = '******';
     $userfields = implode(', ', $userfields);
     $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
     // Get all files from each user.
     foreach ($users as $uploader) {
         $auserid = $uploader;
         $conditions['userid'] = $uploader;
         $records = $DB->get_records('publication_file', $conditions);
         $aassignid = $auserid;
         // Get name of this assignment for use in the file names.
         // Get user firstname/lastname.
         $auser = $DB->get_record('user', array('id' => $auserid), $userfields);
         foreach ($records as $record) {
             if (has_capability('mod/publication:approve', $this->get_context()) || $this->has_filepermission($record->fileid)) {
                 // Is teacher or file is public.
                 $file = $fs->get_file_by_id($record->fileid);
                 // Get files new name.
                 $fileext = strstr($file->get_filename(), '.');
                 $fileoriginal = str_replace($fileext, '', $file->get_filename());
                 $fileforzipname = clean_filename(($viewfullnames ? fullname($auser) : '') . '_' . $fileoriginal . '_' . $auserid . $fileext);
                 // Save file name to array for zipping.
                 $filesforzipping[$fileforzipname] = $file;
             }
         }
     }
     // End of foreach.
     if ($zipfile = $this->pack_files($filesforzipping)) {
         send_temp_file($zipfile, $filename);
         // Send file and delete after sending.
     }
 }
 protected function get_issued_certificate_users($sort = 'username', $groupmode = 0)
 {
     global $CFG, $DB;
     if ($sort == 'username') {
         $sort = $DB->sql_fullname() . ' ASC';
     } else {
         if ($sort == 'issuedate') {
             $sort = 'ci.timecreated ASC';
         } else {
             $sort = '';
         }
     }
     // get all users that can manage this certificate to exclude them from the report.
     $certmanagers = get_users_by_capability($this->context, 'mod/simplecertificate:manage', 'u.id');
     $issedusers = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated \n            FROM {user} u INNER JOIN {simplecertificate_issues} ci ON u.id = ci.userid \n            WHERE u.deleted = 0 \n            AND ci.certificateid = :certificateid \n            AND timedeleted IS NULL \n            ORDER BY {$sort}", array('certificateid' => $this->get_instance()->id));
     // now exclude all the certmanagers.
     foreach ($issedusers as $id => $user) {
         if (!empty($certmanagers[$id])) {
             //exclude certmanagers.
             unset($issedusers[$id]);
         }
     }
     // if groupmembersonly used, remove users who are not in any group
     if (!empty($issedusers) and !empty($CFG->enablegroupings) and $this->coursemodule->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $issedusers = array_intersect($issedusers, array_keys($groupingusers));
         }
     }
     if ($groupmode) {
         $currentgroup = groups_get_activity_group($this->coursemodule);
         if ($currentgroup) {
             $groupusers = groups_get_members($currentgroup, 'u.*');
             if (empty($groupusers)) {
                 return array();
             }
             foreach ($issedusers as $id => $unused) {
                 if (empty($groupusers[$id])) {
                     // remove this user as it isn't in the group!
                     unset($issedusers[$id]);
                 }
             }
         }
     }
     return $issedusers;
 }
Example #18
0
$navigation = build_navigation($strreport, $cm);
print_header("{$course->shortname}: " . format_string($survey->name), $course->fullname, $navigation, "", "", true, update_module_button($cm->id, $course->id, $strsurvey), user_login_string($course) . '<hr style="width:95%">' . navmenu($course, $cm));
/// Check to see if groups are being used in this survey
if ($groupmode = groups_get_activity_groupmode($cm)) {
    // Groups are being used
    $menuaction = $action == "student" ? "students" : $action;
    $currentgroup = groups_get_activity_group($cm, true);
    groups_print_activity_menu($cm, "report.php?id={$cm->id}&amp;action={$menuaction}&amp;qid={$qid}");
} else {
    $currentgroup = 0;
}
if ($currentgroup) {
    $users = groups_get_members($currentgroup);
} else {
    if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
        $users = groups_get_grouping_members($cm->groupingid);
    } else {
        $users = get_course_users($course->id);
    }
}
$groupingid = $cm->groupingid;
print_simple_box_start("center");
if ($showscales) {
    echo "<a href=\"report.php?action=summary&amp;id={$id}\">{$strsummary}</a>";
    echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"report.php?action=scales&amp;id={$id}\">{$strscales}</a>";
    echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"report.php?action=questions&amp;id={$id}\">{$strquestions}</a>";
    echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"report.php?action=students&amp;id={$id}\">{$course->students}</a>";
    if (has_capability('mod/survey:download', $context)) {
        echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"report.php?action=download&amp;id={$id}\">{$strdownload}</a>";
    }
    if (empty($action)) {
 /**
  * Counts all real problemstatement submissions by ENROLLED students (not empty ones)
  *
  * @param $groupid int optional If nonzero then count is restricted to this group
  * @return int The number of submissions
  */
 function count_real_submissions($groupid = 0)
 {
     //return problemstatement_count_real_submissions($this->cm, $groupid);
     global $CFG;
     $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     // this is all the users with this capability set, in this context or higher
     if ($users = get_users_by_capability($context, 'mod/problemstatement:submit', 'u.id', '', '', '', $groupid, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $this->cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($this->cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     if (empty($users)) {
         return 0;
     }
     $userlists = implode(',', $users);
     /*
     	var_dump($userlists);
     	echo $cm->instance;
     	echo "SELECT COUNT('x')
                                     FROM {$CFG->prefix}problemstatement_submissions
                                    WHERE problemstatement = ".$this->cm->instance." AND
                                          timemodified > 0 AND
                                          userid IN ($userlists)";*/
     return count_records_sql("SELECT COUNT('x')\n                                FROM {$CFG->prefix}problemstatement_submissions\n                               WHERE problemstatement = " . $this->cm->instance . " AND\n                                     timemodified > 0 AND\n                                     userid IN ({$userlists})");
 }
 /**
  * get all data necessary for displaying/exporting userlist table
  *
  * @param int $groupingid optional get only this grouping
  * @param int $groupid optional get only this group (groupid not agroupid!)
  * @param stdClass[] $orderby optional current order-by array
  * @param string[] $collapsed optional current array with collapsed columns
  * @param bool $onlydata optional return object with raw data not html-fragment-string
  * @return string|object either html-fragment representing table or raw data as object
  */
 public function userlist_table($groupingid = 0, $groupid = 0, $orderby = array(), $collapsed = array(), $onlydata = false)
 {
     global $OUTPUT, $CFG, $DB, $PAGE, $SESSION;
     $context = context_module::instance($this->cm->id);
     if (!isset($SESSION->mod_grouptool->userlist)) {
         $SESSION->mod_grouptool->userlist = new stdClass();
     }
     // Handles order direction!
     if (!isset($SESSION->mod_grouptool->userlist->orderby)) {
         $SESSION->mod_grouptool->userlist->orderby = array();
     }
     $orderby = $SESSION->mod_grouptool->userlist->orderby;
     if ($tsort = optional_param('tsort', 0, PARAM_ALPHA)) {
         $olddir = 'DESC';
         if (key_exists($tsort, $orderby)) {
             $olddir = $orderby[$tsort];
             unset($orderby[$tsort]);
         }
         // Insert as first element and rebuild!
         $oldorderby = array_keys($orderby);
         $oldorderdir = array_values($orderby);
         array_unshift($oldorderby, $tsort);
         array_unshift($oldorderdir, $olddir == 'DESC' ? 'ASC' : 'DESC');
         $orderby = array_combine($oldorderby, $oldorderdir);
         $SESSION->mod_grouptool->userlist->orderby = $orderby;
     }
     // Handles collapsed columns!
     if (!isset($SESSION->mod_grouptool->userlist->collapsed)) {
         $SESSION->mod_grouptool->userlist->collapsed = array();
     }
     $collapsed = $SESSION->mod_grouptool->userlist->collapsed;
     if ($thide = optional_param('thide', 0, PARAM_ALPHA)) {
         if (!in_array($thide, $collapsed)) {
             array_push($collapsed, $thide);
         }
         $SESSION->mod_grouptool->userlist->collapsed = $collapsed;
     }
     if ($tshow = optional_param('tshow', 0, PARAM_ALPHA)) {
         foreach ($collapsed as $key => $value) {
             if ($value == $tshow) {
                 unset($collapsed[$key]);
             }
         }
         $SESSION->mod_grouptool->userlist->collapsed = $collapsed;
     }
     if (!$onlydata) {
         flush();
         $orientation = optional_param('orientation', 0, PARAM_BOOL);
         $downloadurl = new moodle_url('/mod/grouptool/download.php', array('id' => $this->cm->id, 'groupingid' => $groupingid, 'groupid' => $groupid, 'orientation' => $orientation, 'sesskey' => sesskey(), 'tab' => 'userlist'));
     } else {
         $return = array();
     }
     // Get all ppl that are allowed to register!
     list($esql, $params) = get_enrolled_sql($this->context, 'mod/grouptool:register');
     $sql = "SELECT u.id\n                  FROM {user} u\n             LEFT JOIN ({$esql}) eu ON eu.id=u.id\n                 WHERE u.deleted = 0 AND eu.id=u.id ";
     if (!empty($groupingid)) {
         // Get all groupings groups!
         $groups = groups_get_all_groups($this->course->id, 0, $groupingid);
         $ufields = user_picture::fields('u', array('idnumber'));
         $groupingsusers = groups_get_grouping_members($groupingid, 'DISTINCT u.id, ' . $ufields);
         if (empty($groupingusers)) {
             $groupingusers = array();
         } else {
             $groupingusers = array_keys($groupingusers);
         }
         list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups));
         $groupingusers2 = $DB->get_fieldset_sql("\n            SELECT DISTINCT u.id\n              FROM {user} u\n         LEFT JOIN {grouptool_registered} reg ON u.id = reg.userid AND reg.modified_by >= 0\n         LEFT JOIN {grouptool_queued} queue ON u.id = queue.userid\n         LEFT JOIN {grouptool_agrps} agrp ON reg.agrpid = agrp.id OR queue.agrpid = agrp.id\n             WHERE agrp.groupid " . $groupssql, $groupsparams);
         $groupingusers = array_merge($groupingusers, $groupingusers2);
         if (empty($groupingusers)) {
             $userssql = " = :groupingparam";
             $groupingparams = array('groupingparam' => -1);
         } else {
             list($userssql, $groupingparams) = $DB->get_in_or_equal($groupingusers, SQL_PARAMS_NAMED);
         }
         // Extend sql to only include people registered in moodle-group/grouptool-group or queued in grouptool group!
         $sql .= " AND u.id " . $userssql;
         $params = array_merge($params, $groupingparams);
     }
     if (!empty($groupid)) {
         // Same as with groupingid but just with 1 group!
         // Get all group members!
         $ufields = user_picture::fields('u', array('idnumber'));
         $groupusers = groups_get_members($groupid, 'DISTINCT u.id, ' . $ufields);
         if (empty($groupusers)) {
             $groupusers = array();
         } else {
             $groupusers = array_keys($groupusers);
         }
         $groupusers2 = $DB->get_fieldset_sql("\n            SELECT DISTINCT u.id\n              FROM {user} u\n         LEFT JOIN {grouptool_registered} reg ON u.id = reg.userid AND reg.modified_by >= 0\n         LEFT JOIN {grouptool_queued} queue ON u.id = queue.userid\n         LEFT JOIN {grouptool_agrps} agrp ON reg.agrpid = agrp.id OR queue.agrpid = agrp.id\n             WHERE agrp.groupid = ?", array($groupid));
         $groupusers = array_merge($groupusers, $groupusers2);
         if (empty($groupusers)) {
             $userssql = " = :groupparam";
             $groupparams = array('groupparam' => -1);
         } else {
             list($userssql, $groupparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
         }
         // Extend sql to only include people registered in moodle-group/grouptool-group or queued in grouptool group!
         $sql .= " AND u.id " . $userssql;
         $params = array_merge($params, $groupparams);
     }
     $users = $DB->get_records_sql($sql, $params);
     if (!$onlydata) {
         if (has_capability('mod/grouptool:export', $context)) {
             $txturl = new moodle_url($downloadurl, array('format' => GROUPTOOL_TXT));
             $xlsxurl = new moodle_url($downloadurl, array('format' => GROUPTOOL_XLSX));
             $pdfurl = new moodle_url($downloadurl, array('format' => GROUPTOOL_PDF));
             $odsurl = new moodle_url($downloadurl, array('format' => GROUPTOOL_ODS));
             $downloadlinks = html_writer::tag('span', get_string('downloadall') . ":", array('class' => 'title')) . '&nbsp;' . html_writer::link($txturl, '.TXT') . '&nbsp;' . html_writer::link($xlsxurl, '.XLSX') . '&nbsp;' . html_writer::link($pdfurl, '.PDF') . '&nbsp;' . html_writer::link($odsurl, '.ODS');
             echo html_writer::tag('div', $downloadlinks, array('class' => 'download all'));
         }
         flush();
     }
     if (!empty($users)) {
         $users = array_keys($users);
         $userdata = $this->get_user_data($groupingid, $groupid, $users, $orderby);
     } else {
         if (!$onlydata) {
             echo $OUTPUT->box($OUTPUT->notification(get_string('no_users_to_display', 'grouptool'), 'notifyproblem'), 'centered generalbox');
         } else {
             return get_string('no_users_to_display', 'grouptool');
         }
     }
     $groupinfo = $this->get_active_groups(false, false, 0, $groupid, $groupingid, false);
     if (!$onlydata) {
         echo html_writer::start_tag('table', array('class' => 'centeredblock userlist table table-striped table-hover table-condensed'));
         echo html_writer::start_tag('thead');
         echo html_writer::start_tag('tr');
         echo html_writer::tag('th', $this->collapselink($collapsed, 'picture'), array('class' => ''));
         flush();
         if (!in_array('fullname', $collapsed)) {
             $firstnamelink = html_writer::link(new moodle_url($PAGE->url, array('tsort' => 'firstname')), get_string('firstname') . $this->pic_if_sorted($orderby, 'firstname'));
             $surnamelink = html_writer::link(new moodle_url($PAGE->url, array('tsort' => 'lastname')), get_string('lastname') . $this->pic_if_sorted($orderby, 'lastname'));
             $fullname = html_writer::tag('div', get_string('fullname') . html_writer::empty_tag('br') . $firstnamelink . '&nbsp;/&nbsp;' . $surnamelink);
             echo html_writer::tag('th', $fullname . $this->collapselink($collapsed, 'fullname'), array('class' => ''));
         } else {
             echo html_writer::tag('th', $this->collapselink($collapsed, 'fullname'), array('class' => ''));
         }
         if (!in_array('idnumber', $collapsed)) {
             $idnumberlink = html_writer::link(new moodle_url($PAGE->url, array('tsort' => 'idnumber')), get_string('idnumber') . $this->pic_if_sorted($orderby, 'idnumber'));
             echo html_writer::tag('th', $idnumberlink . $this->collapselink($collapsed, 'idnumber'), array('class' => ''));
         } else {
             echo html_writer::tag('th', $this->collapselink($collapsed, 'idnumber'), array('class' => ''));
         }
         if (!in_array('email', $collapsed)) {
             $emaillink = html_writer::link(new moodle_url($PAGE->url, array('tsort' => 'email')), get_string('email') . $this->pic_if_sorted($orderby, 'email'));
             echo html_writer::tag('th', $emaillink . $this->collapselink($collapsed, 'email'), array('class' => ''));
         } else {
             echo html_writer::tag('th', $this->collapselink($collapsed, 'email'), array('class' => ''));
         }
         if (!in_array('registrations', $collapsed)) {
             $registrationslink = get_string('registrations', 'grouptool');
             echo html_writer::tag('th', $registrationslink . $this->collapselink($collapsed, 'registrations'), array('class' => ''));
         } else {
             echo html_writer::tag('th', $this->collapselink($collapsed, 'registrations'), array('class' => ''));
         }
         if (!in_array('queues', $collapsed)) {
             $queueslink = get_string('queues', 'grouptool') . ' (' . get_string('rank', 'grouptool') . ')';
             echo html_writer::tag('th', $queueslink . $this->collapselink($collapsed, 'queues'), array('class' => ''));
         } else {
             echo html_writer::tag('th', $this->collapselink($collapsed, 'queues'), array('class' => ''));
         }
         echo html_writer::end_tag('tr');
         echo html_writer::end_tag('thead');
     } else {
         // We create a dummy user-object to get the fullname-format!
         $dummy = new stdClass();
         $namefields = get_all_user_name_fields();
         foreach ($namefields as $namefield) {
             $dummy->{$namefield} = $namefield;
         }
         $fullnameformat = fullname($dummy);
         // Now get the ones used in fullname in the correct order!
         $namefields = order_in_string($namefields, $fullnameformat);
         $head = array('name' => get_string('fullname'));
         foreach ($namefields as $namefield) {
             $head[$namefield] = get_user_field_name($namefield);
         }
         if (empty($CFG->showuseridentity)) {
             $head['idnumber'] = get_user_field_name('idnumber');
         } else {
             $fields = explode(',', $CFG->showuseridentity);
             foreach ($fields as $field) {
                 $head[$field] = get_user_field_name($field);
             }
         }
         $head['idnumber'] = get_user_field_name('idnumber');
         $head['email'] = get_user_field_name('email');
         $head['registrations'] = get_string('registrations', 'grouptool');
         $head['queues'] = get_string('queues', 'grouptool') . ' (' . get_string('rank', 'grouptool') . ')';
     }
     if (!$onlydata) {
         echo html_writer::start_tag('tbody');
     }
     if (!empty($userdata)) {
         core_php_time_limit::raise(5 * count($userdata));
         foreach ($userdata as $key => $user) {
             if (!$onlydata) {
                 echo html_writer::start_tag('tr', array('class' => ''));
                 $userlink = new moodle_url($CFG->wwwroot . '/user/view.php', array('id' => $user->id, 'course' => $this->course->id));
                 if (!in_array('picture', $collapsed)) {
                     $picture = html_writer::link($userlink, $OUTPUT->user_picture($user));
                     echo html_writer::tag('td', $picture, array('class' => ''));
                 } else {
                     $picture = "";
                 }
                 if (!in_array('fullname', $collapsed)) {
                     $fullname = html_writer::link($userlink, fullname($user));
                     echo html_writer::tag('td', $fullname, array('class' => ''));
                 } else {
                     $fullname = "";
                 }
                 if (!in_array('idnumber', $collapsed)) {
                     $idnumber = $user->idnumber;
                     echo html_writer::tag('td', $idnumber, array('class' => ''));
                 } else {
                     $idnumber = "";
                 }
                 if (!in_array('email', $collapsed)) {
                     $email = $user->email;
                     echo html_writer::tag('td', $email, array('class' => ''));
                 } else {
                     $email = "";
                 }
                 if (!in_array('registrations', $collapsed)) {
                     if (!empty($user->regs)) {
                         $registrations = array();
                         foreach ($user->regs as $reg) {
                             $grouplink = new moodle_url($PAGE->url, array('tab' => 'overview', 'groupid' => $groupinfo[$reg]->id));
                             $registrations[] = html_writer::link($grouplink, $groupinfo[$reg]->name);
                         }
                     } else {
                         $registrations = array('-');
                     }
                     $registrations = implode(html_writer::empty_tag('br'), $registrations);
                     echo html_writer::tag('td', $registrations, array('class' => ''));
                 } else {
                     $registrations = "";
                 }
                 if (!in_array('queues', $collapsed)) {
                     if (!empty($user->queued)) {
                         $queueentries = array();
                         foreach ($user->queued as $queue) {
                             $grouplink = new moodle_url($PAGE->url, array('tab' => 'overview', 'groupid' => $groupinfo[$queue]->id));
                             $groupdata = $this->get_active_groups(false, true, $queue);
                             $groupdata = current($groupdata);
                             $rank = $this->get_rank_in_queue($groupdata->queued, $user->id);
                             $groupdata = null;
                             unset($groupdata);
                             if (empty($rank)) {
                                 $rank = '*';
                             }
                             $queueentries[] = html_writer::link($grouplink, $groupinfo[$queue]->name . " (#" . $rank . ")");
                         }
                     } else {
                         $queueentries = array('-');
                     }
                     $queueentries = implode(html_writer::empty_tag('br'), $queueentries);
                     echo html_writer::tag('td', $queueentries, array('class' => ''));
                 } else {
                     $queueentries = "";
                 }
                 echo html_writer::end_tag('tr');
                 flush();
                 $picture = null;
                 unset($picture);
                 $fullname = null;
                 unset($fullname);
                 $idnumber = null;
                 unset($idnumber);
                 $email = null;
                 unset($email);
                 $registrations = null;
                 unset($registrations);
                 $queueentries = null;
                 unset($queueentries);
             } else {
                 $row = array();
                 $row['name'] = fullname($user);
                 foreach ($namefields as $namefield) {
                     $row[$namefield] = $user->{$namefield};
                     $user->namefield = null;
                     unset($user->namefield);
                 }
                 $row['idnumber'] = $user->idnumber;
                 $row['email'] = $user->email;
                 if (empty($CFG->showuseridentity)) {
                     $row['idnumber'] = $user->idnumber;
                     $user->idnumber = null;
                     unset($user->idnumber);
                     $row['email'] = $user->email;
                     $user->email = null;
                     unset($user->email);
                 } else {
                     $fields = explode(',', $CFG->showuseridentity);
                     foreach ($fields as $field) {
                         $row[$field] = $user->{$field};
                         $user->{$field} = null;
                         unset($user->{$field});
                     }
                 }
                 if (!empty($user->regs)) {
                     $registrations = array();
                     foreach ($user->regs as $reg) {
                         $registrations[] = $groupinfo[$reg]->name;
                     }
                     $row['registrations'] = $registrations;
                 } else {
                     $row['registrations'] = array();
                 }
                 $user->regs = null;
                 unset($user->regs);
                 if (!empty($user->queued)) {
                     $queueentries = array();
                     foreach ($user->queued as $queue) {
                         $groupdata = $this->get_active_groups(false, true, $queue);
                         $groupdata = current($groupdata);
                         $rank = $this->get_rank_in_queue($groupdata->queued, $user->id);
                         if (empty($rank)) {
                             $rank = '*';
                         }
                         $queueentries[] = array('rank' => $rank, 'name' => $groupinfo[$queue]->name);
                     }
                     $row['queues'] = $queueentries;
                 } else {
                     $row['queues'] = array();
                 }
                 $user->queues = null;
                 unset($user->queues);
                 $rows[] = $row;
                 $row = null;
                 unset($row);
             }
         }
     }
     if (!$onlydata) {
         echo html_writer::end_tag('tbody');
         echo html_writer::end_tag('table');
     } else {
         return array_merge(array($head), $rows);
     }
 }
Example #21
0
/**
 * Returns a list of issued certificates - sorted for report.
 *
 * @param int $certificateid
 * @param string $sort the sort order
 * @param boolean $groupmode are we in group mode ?
 * @param stdClass $cm the course module
 */
function certificate_get_issues($certificateid, $sort = "ci.certdate ASC", $groupmode, $cm)
{
    global $CFG, $DB;
    // get all users that can manage this certificate to exclude them from the report.
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $certmanagers = get_users_by_capability($context, 'mod/certificate:manage', 'u.id');
    // Get all the users that have certificates issued, first, create subsql
    // used in the main sql query, this is used so that we don't get an error
    // about the same u.id being returned multiple times due to being in the
    // certificate issues table multiple times.
    $subsql = "SELECT MAX(ci2.timecreated) as timecreated\n               FROM {certificate_issues} ci2\n               WHERE ci2.certificateid = :subsqlcertificateid\n               AND ci2.certdate > 0\n               AND ci2.userid = u.id";
    $users = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated, ci.certdate, ci.studentname, ci.reportgrade\n                                   FROM {user} u\n                                   INNER JOIN {certificate_issues} ci\n                                   ON u.id = ci.userid\n                                   WHERE u.deleted = 0\n                                   AND ci.certificateid = :certificateid\n                                   AND ci.certdate > 0\n                                   AND ci.timecreated = ({$subsql})\n                                   ORDER BY {$sort}", array('certificateid' => $certificateid, 'subsqlcertificateid' => $certificateid));
    // now exclude all the certmanagers.
    foreach ($users as $id => $user) {
        if (isset($certmanagers[$id])) {
            //exclude certmanagers.
            unset($users[$id]);
        }
    }
    // if groupmembersonly used, remove users who are not in any group
    if (!empty($users) and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $users = array_intersect($users, array_keys($groupingusers));
        }
    }
    if (!$groupmode) {
        return $users;
    } else {
        $currentgroup = groups_get_activity_group($cm);
        if ($currentgroup) {
            $groupusers = groups_get_members($currentgroup, 'u.*');
            if (empty($groupusers)) {
                return array();
            }
            foreach ($groupusers as $id => $gpuser) {
                if (!isset($users[$id])) {
                    //remove this user as it isn't in the group!
                    unset($users[$id]);
                }
            }
        }
        return $users;
    }
}
Example #22
0
function choice_show_results($choice, $course, $cm, $forcepublish = '')
{
    global $CFG, $COLUMN_HEIGHT, $USER;
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    print_heading(get_string("responses", "choice"));
    if (empty($forcepublish)) {
        //alow the publish setting to be overridden
        $forcepublish = $choice->publish;
    }
    $groupmode = groups_get_activity_groupmode($cm);
    if ($groupmode > 0) {
        $currentgroup = groups_get_activity_group($cm);
    } else {
        $currentgroup = 0;
    }
    $users = get_users_by_capability($context, 'mod/choice:choose', 'u.id, u.picture, u.firstname, u.lastname, u.idnumber', 'u.firstname ASC', '', '', $currentgroup, '', false, true);
    if (!empty($CFG->enablegroupings) && !empty($cm->groupingid) && !empty($users)) {
        $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
        foreach ($users as $key => $user) {
            if (!isset($groupingusers[$user->id])) {
                unset($users[$key]);
            }
        }
    }
    if (!$users) {
        print_heading(get_string("nousersyet"));
    }
    $answers = array();
    if ($allresponses = get_records("choice_answers", "choiceid", $choice->id)) {
        foreach ($allresponses as $aa) {
            //TODO: rewrite with SQL
            if ($groupmode and $currentgroup) {
                if (groups_is_member($currentgroup, $aa->userid)) {
                    $answers[$aa->userid] = $aa;
                }
            } else {
                $answers[$aa->userid] = $aa;
            }
        }
    }
    $timenow = time();
    foreach ($choice->option as $optionid => $text) {
        $useranswer[$optionid] = array();
    }
    if (!empty($users)) {
        foreach ($users as $user) {
            if (!empty($user->id) and !empty($answers[$user->id])) {
                $answer = $answers[$user->id];
                $useranswer[(int) $answer->optionid][] = $user;
            } else {
                $useranswer[0][] = $user;
            }
        }
    }
    foreach ($choice->option as $optionid => $text) {
        if (!$choice->option[$optionid]) {
            unset($useranswer[$optionid]);
            // Throw away any data that doesn't apply
        }
    }
    ksort($useranswer);
    switch ($forcepublish) {
        case CHOICE_PUBLISH_NAMES:
            $tablewidth = (int) (100.0 / count($useranswer));
            if (has_capability('mod/choice:readresponses', $context)) {
                echo '<div id="tablecontainer">';
                echo '<form id="attemptsform" method="post" action="' . $_SERVER['PHP_SELF'] . '" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? \'' . addslashes(get_string('deleteattemptcheck', 'quiz')) . '\' : true);">';
                echo '<div>';
                echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
                echo '<input type="hidden" name="mode" value="overview" />';
            }
            echo "<table cellpadding=\"5\" cellspacing=\"10\" class=\"results names\">";
            echo "<tr>";
            $count = 0;
            $columncount = array();
            // number of votes in each column
            foreach ($useranswer as $optionid => $userlist) {
                $columncount[$optionid] = 0;
                // init counters
                if ($optionid) {
                    echo "<th class=\"col{$count} header\" style=\"width:{$tablewidth}%\" scope=\"col\">";
                } else {
                    if ($choice->showunanswered) {
                        echo "<th class=\"col{$count} header\" style=\"width:{$tablewidth}%\" scope=\"col\">";
                    } else {
                        continue;
                    }
                }
                echo format_string(choice_get_option_text($choice, $optionid));
                echo "</th>";
                $count++;
            }
            echo "</tr><tr>";
            $count = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if ($optionid) {
                    echo "<td class=\"col{$count} data\" style=\"width:{$tablewidth}%;\">";
                } else {
                    if ($choice->showunanswered) {
                        echo "<td class=\"col{$count} data\" style=\"width:{$tablewidth}%;\">";
                    } else {
                        continue;
                    }
                }
                // added empty row so that when the next iteration is empty,
                // we do not get <table></table> erro from w3c validator
                // MDL-7861
                echo "<table class=\"choiceresponse\"><tr><td></td></tr>";
                foreach ($userlist as $user) {
                    if ($optionid != 0 or has_capability('mod/choice:choose', $context, $user->id, false)) {
                        $columncount[$optionid] += 1;
                        echo "<tr>";
                        if (has_capability('mod/choice:readresponses', $context) && $optionid != 0) {
                            echo '<td class="attemptcell"><input type="checkbox" name="attemptid[]" value="' . $answers[$user->id]->id . '" /></td>';
                        }
                        echo "<td class=\"picture\">";
                        print_user_picture($user->id, $course->id, $user->picture);
                        echo "</td><td class=\"fullname\">";
                        echo "<a href=\"{$CFG->wwwroot}/user/view.php?id={$user->id}&amp;course={$course->id}\">";
                        echo fullname($user, has_capability('moodle/site:viewfullnames', $context));
                        echo "</a>";
                        echo "</td></tr>";
                    }
                }
                $count++;
                echo "</table>";
                echo "</td>";
            }
            echo "</tr><tr>";
            $count = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if (!$optionid and !$choice->showunanswered) {
                    continue;
                }
                echo "<td align=\"center\" class=\"count\">";
                if ($choice->limitanswers && !$optionid == 0) {
                    echo get_string("taken", "choice") . ":";
                    echo $columncount[$optionid];
                    echo "<br/>";
                    echo get_string("limit", "choice") . ":";
                    $choice_option = get_record("choice_options", "id", $optionid);
                    echo $choice_option->maxanswers;
                } else {
                    echo $columncount[$optionid];
                }
                echo "</td>";
                $count++;
            }
            echo "</tr>";
            /// Print "Select all" etc.
            if (has_capability('mod/choice:readresponses', $context)) {
                echo '<tr><td></td><td>';
                echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectall', 'quiz') . '</a> / ';
                echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectnone', 'quiz') . '</a> ';
                echo '&nbsp;&nbsp;';
                $options = array('delete' => get_string('delete'));
                echo choose_from_menu($options, 'action', '', get_string('withselected', 'quiz'), 'if(this.selectedIndex > 0) submitFormById(\'attemptsform\');', '', true);
                echo '<noscript id="noscriptmenuaction" style="display: inline;">';
                echo '<div>';
                echo '<input type="submit" value="' . get_string('go') . '" /></div></noscript>';
                echo '<script type="text/javascript">' . "\n<!--\n" . 'document.getElementById("noscriptmenuaction").style.display = "none";' . "\n-->\n" . '</script>';
                echo '</td><td></td></tr>';
            }
            echo "</table>";
            if (has_capability('mod/choice:readresponses', $context)) {
                echo "</div></form></div>";
            }
            break;
        case CHOICE_PUBLISH_ANONYMOUS:
            $tablewidth = (int) (100.0 / count($useranswer));
            echo "<table cellpadding=\"5\" cellspacing=\"0\" class=\"results anonymous\">";
            echo "<tr>";
            $count = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if ($optionid) {
                    echo "<th style=\"width:{$tablewidth}%\" class=\"col{$count} header\" scope=\"col\">";
                } else {
                    if ($choice->showunanswered) {
                        echo "<th style=\"width:{$tablewidth}%\" class=\"col{$count} header\" scope=\"col\">";
                    } else {
                        continue;
                    }
                }
                echo format_string(choice_get_option_text($choice, $optionid));
                echo "</th>";
                $count++;
            }
            echo "</tr>";
            $maxcolumn = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if (!$optionid and !$choice->showunanswered) {
                    continue;
                }
                $column[$optionid] = 0;
                foreach ($userlist as $user) {
                    if ($optionid != 0 or has_capability('mod/choice:choose', $context, $user->id, false)) {
                        $column[$optionid]++;
                    }
                }
                if ($column[$optionid] > $maxcolumn) {
                    $maxcolumn = $column[$optionid];
                }
            }
            echo "<tr>";
            $count = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if (!$optionid and !$choice->showunanswered) {
                    continue;
                }
                $height = 0;
                if ($maxcolumn) {
                    $height = $COLUMN_HEIGHT * ((double) $column[$optionid] / (double) $maxcolumn);
                }
                echo "<td style=\"vertical-align:bottom\" align=\"center\" class=\"col{$count} data\">";
                echo "<img src=\"column.png\" height=\"{$height}\" width=\"49\" alt=\"\" />";
                echo "</td>";
                $count++;
            }
            echo "</tr>";
            echo "<tr>";
            $count = 0;
            foreach ($useranswer as $optionid => $userlist) {
                if (!$optionid and !$choice->showunanswered) {
                    continue;
                }
                echo "<td align=\"center\" class=\"col{$count} count\">";
                if ($choice->limitanswers && !$optionid == 0) {
                    echo get_string("taken", "choice") . ":";
                    echo $column[$optionid];
                    echo "<br/>";
                    echo get_string("limit", "choice") . ":";
                    $choice_option = get_record("choice_options", "id", $optionid);
                    echo $choice_option->maxanswers;
                } else {
                    echo $column[$optionid];
                }
                echo "</td>";
                $count++;
            }
            echo "</tr></table>";
            break;
    }
}
/**
 * Return a list of students that the current user is able to open a dialogue with
 * 
 * Called by dialogue_get_available_users(). The list is used to populate a drop-down
 * list in the UI. The returned array of usernames starts with a list of student-groups 
 * for a teacher, followed by an "All Participants" entry if a teacher, followed by a
 * list of students. The students list is refined to just the student's own group 
 * if the activity is in group-mode and also filters out the students own name
 * @param   object  $dialogue
 * @param   object  $context    for a user in this activity
 * @param   int     $editconversationid
 * @return  array   usernames and ids
 */
function dialogue_get_available_students($dialogue, $context, $editconversationid = 0)
{
    global $USER, $CFG;
    if (!($course = get_record('course', 'id', $dialogue->course))) {
        error('Course is misconfigured');
    }
    if (!($cm = get_coursemodule_from_instance('dialogue', $dialogue->id, $course->id))) {
        error('Course Module ID was incorrect');
    }
    // get the list of teachers (actually, those who have dialogue:manage capability)
    $teachers = array();
    if ($users = get_users_by_capability($context, 'mod/dialogue:manage', '', null, null, null, null, null, null, null, false)) {
        foreach ($users as $user) {
            $teachers[$user->id] = 1;
        }
    }
    $groupid = groups_get_activity_group($cm, true);
    // add current group before list of students if it's the teacher
    if (isset($teachers[$USER->id])) {
        // show teacher their current group
        if ($groupid) {
            if (!($group = get_record('groups', 'id', $groupid))) {
                error('Dialogue get available students: group not found');
            }
            $gnames["g{$groupid}"] = $group->name;
        }
        $gnames['g0'] = get_string('allparticipants');
        $gnames['spacer'] = '------------';
    }
    // get the students on this course (default sort order)...
    if ($users = get_users_by_capability($context, 'mod/dialogue:participate', null, null, null, null, null, null, null, null, false)) {
        if (!empty($CFG->enablegroupings) && !empty($cm->groupingid) && !empty($users)) {
            $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
            foreach ($users as $key => $user) {
                if (!isset($groupingusers[$user->id])) {
                    unset($users[$key]);
                }
            }
        }
        foreach ($users as $otheruser) {
            // ...exclude self and...
            if ($USER->id != $otheruser->id) {
                // ...if not a student (eg co-teacher, teacher) then exclude from students list
                if (isset($teachers[$otheruser->id]) && $teachers[$otheruser->id] == 1) {
                    continue;
                }
                $groupmode = groupmode($course, $cm);
                // ...if teacher and groups then exclude students not in the current group
                if (isset($teachers[$USER->id]) and $groupmode and $groupid) {
                    if (!ismember($groupid, $otheruser->id)) {
                        continue;
                    }
                }
                // ...if student and groupmode then exclude students not in student's group
                if (!isset($teachers[$USER->id]) && $groupmode && $groupid) {
                    if (!ismember($groupid, $otheruser->id)) {
                        continue;
                    }
                }
                // ... and any already in any open conversations unless multiple conversations allowed
                if ($dialogue->multipleconversations or count_records_select('dialogue_conversations', "dialogueid = {$dialogue->id} AND id != {$editconversationid} AND \n                        ((userid = {$USER->id} AND recipientid = {$otheruser->id}) OR \n                        (userid = {$otheruser->id} AND recipientid = {$USER->id})) AND closed = 0") == 0) {
                    $names[$otheruser->id] = fullname($otheruser);
                }
            }
        }
    }
    if (isset($gnames)) {
        // group names
        $list = $gnames;
    }
    if (isset($names)) {
        natcasesort($names);
        if (isset($list)) {
            $list += $names;
        } else {
            $list = $names;
        }
    }
    if (isset($list)) {
        return $list;
    } else {
        return;
    }
}
 function count_real_submissions($groupid = 0)
 {
     global $CFG, $DB;
     $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     // this is all the users with this capability set, in this context or higher
     if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $this->cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($this->cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     if (empty($users)) {
         return 0;
     }
     list($usql, $uparam) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
     $uparam['cminstance'] = $this->cm->instance;
     // Count the number of assignments that have been submitted and for
     // which a response file has been generated (ie data2 = 'responded',
     // not 'submitted')
     $uparam['data2'] = ASSIGNMENT_UPLOADPDF_STATUS_RESPONDED;
     $markedcount = $DB->count_records_sql('SELECT COUNT(*)
                             FROM {assignment_submissions}
                             WHERE assignment = :cminstance AND
                             data2 = :data2 AND
                             userid ' . $usql, $uparam);
     // Count the number of assignments that have been submitted, but for
     // which a response file has not been generated (ie data2 = 'submitted',
     // not 'responded')
     $uparam['data2'] = ASSIGNMENT_UPLOADPDF_STATUS_SUBMITTED;
     $unmarkedcount = $DB->count_records_sql('SELECT COUNT(*)
                             FROM {assignment_submissions}
                             WHERE assignment = :cminstance AND
                             data2 = :data2 AND
                             userid ' . $usql, $uparam);
     $totalcount = $markedcount + $unmarkedcount;
     if ($unmarkedcount) {
         return "{$totalcount}({$unmarkedcount})";
     } else {
         return $totalcount;
     }
 }
Example #25
0
    /**
     *  Display all the submissions ready for grading
     *
     * @global object
     * @global object
     * @global object
     * @global object
     * @param string $message
     * @return bool|void
     */
    function display_submissions($message='') {
        global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
        require_once($CFG->libdir.'/gradelib.php');

        /* first we check to see if the form has just been submitted
         * to request user_preference updates
         */

       $filters = array(self::FILTER_ALL             => get_string('all'),
                        self::FILTER_SUBMITTED       => get_string('submitted', 'assignment'),
                        self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));

        $updatepref = optional_param('updatepref', 0, PARAM_INT);

        if (isset($_POST['updatepref'])){
            $perpage = optional_param('perpage', 10, PARAM_INT);
            $perpage = ($perpage <= 0) ? 10 : $perpage ;
            $filter = optional_param('filter', 0, PARAM_INT);
            set_user_preference('assignment_perpage', $perpage);
            set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
            set_user_preference('assignment_filter', $filter);
        }

        /* next we get perpage and quickgrade (allow quick grade) params
         * from database
         */
        $perpage    = get_user_preferences('assignment_perpage', 10);
        $quickgrade = get_user_preferences('assignment_quickgrade', 0);
        $filter = get_user_preferences('assignment_filter', 0);
        $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);

        if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
            $uses_outcomes = true;
        } else {
            $uses_outcomes = false;
        }

        $page    = optional_param('page', 0, PARAM_INT);
        $strsaveallfeedback = get_string('saveallfeedback', 'assignment');

    /// Some shortcuts to make the code read better

        $course     = $this->course;
        $assignment = $this->assignment;
        $cm         = $this->cm;

        $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
        add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);

        $PAGE->set_title(format_string($this->assignment->name,true));
        $PAGE->set_heading($this->course->fullname);
        echo $OUTPUT->header();

        echo '<div class="usersubmissions">';

        //hook to allow plagiarism plugins to update status/print links.
        plagiarism_update_status($this->course, $this->cm);

        /// Print quickgrade form around the table
        if ($quickgrade) {
            $formattrs = array();
            $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
            $formattrs['id'] = 'fastg';
            $formattrs['method'] = 'post';

            echo html_writer::start_tag('form', $formattrs);
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
        }

        $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
        if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
            echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
                . get_string('seeallcoursegrades', 'grades') . '</a></div>';
        }

        if (!empty($message)) {
            echo $message;   // display messages here if any
        }

        $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    /// Check to see if groups are being used in this assignment

        /// find out current groups mode
        $groupmode = groups_get_activity_groupmode($cm);
        $currentgroup = groups_get_activity_group($cm, true);
        groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);

        /// Get all ppl that are allowed to submit assignments
        list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $currentgroup);

        if ($filter == self::FILTER_ALL) {
            $sql = "SELECT u.id FROM {user} u ".
                   "LEFT JOIN ($esql) eu ON eu.id=u.id ".
                   "WHERE u.deleted = 0 AND eu.id=u.id ";
        } else {
            $wherefilter = '';
            if($filter == self::FILTER_SUBMITTED) {
               $wherefilter = ' AND s.timemodified > 0';
            } else if($filter == self::FILTER_REQUIRE_GRADING) {
                $wherefilter = ' AND s.timemarked < s.timemodified ';
            }

            $sql = "SELECT u.id FROM {user} u ".
                   "LEFT JOIN ($esql) eu ON eu.id=u.id ".
                   "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) " .
                   "WHERE u.deleted = 0 AND eu.id=u.id ".
                   'AND s.assignment = '. $this->assignment->id .
                    $wherefilter;
        }

        $users = $DB->get_records_sql($sql, $params);
        if (!empty($users)) {
            $users = array_keys($users);
        }

        // if groupmembersonly used, remove users who are not in any group
        if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
            if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
                $users = array_intersect($users, array_keys($groupingusers));
            }
        }

        $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
        if ($uses_outcomes) {
            $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
        }

        $tableheaders = array('',
                              get_string('fullname'),
                              get_string('grade'),
                              get_string('comment', 'assignment'),
                              get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
                              get_string('lastmodified').' ('.get_string('grade').')',
                              get_string('status'),
                              get_string('finalgrade', 'grades'));
        if ($uses_outcomes) {
            $tableheaders[] = get_string('outcome', 'grades');
        }

        require_once($CFG->libdir.'/tablelib.php');
        $table = new flexible_table('mod-assignment-submissions');

        $table->define_columns($tablecolumns);
        $table->define_headers($tableheaders);
        $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);

        $table->sortable(true, 'lastname');//sorted by lastname by default
        $table->collapsible(true);
        $table->initialbars(true);

        $table->column_suppress('picture');
        $table->column_suppress('fullname');

        $table->column_class('picture', 'picture');
        $table->column_class('fullname', 'fullname');
        $table->column_class('grade', 'grade');
        $table->column_class('submissioncomment', 'comment');
        $table->column_class('timemodified', 'timemodified');
        $table->column_class('timemarked', 'timemarked');
        $table->column_class('status', 'status');
        $table->column_class('finalgrade', 'finalgrade');
        if ($uses_outcomes) {
            $table->column_class('outcome', 'outcome');
        }

        $table->set_attribute('cellspacing', '0');
        $table->set_attribute('id', 'attempts');
        $table->set_attribute('class', 'submissions');
        $table->set_attribute('width', '100%');
        //$table->set_attribute('align', 'center');

        $table->no_sorting('finalgrade');
        $table->no_sorting('outcome');

        // Start working -- this is necessary as soon as the niceties are over
        $table->setup();

        if (empty($users)) {
            echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
            echo '</div>';
            return true;
        }
        if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
            echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
        }
    /// Construct the SQL

        list($where, $params) = $table->get_sql_where();
        if ($where) {
            $where .= ' AND ';
        }

        if ($filter == self::FILTER_SUBMITTED) {
           $where .= 's.timemodified > 0 AND ';
        } else if($filter == self::FILTER_REQUIRE_GRADING) {
           $where .= 's.timemarked < s.timemodified AND ';
        }

        if ($sort = $table->get_sql_sort()) {
            $sort = ' ORDER BY '.$sort;
        }

        $ufields = user_picture::fields('u');

        $select = "SELECT $ufields,
                          s.id AS submissionid, s.grade, s.submissioncomment,
                          s.timemodified, s.timemarked,
                          COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
        $sql = 'FROM {user} u '.
               'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
                AND s.assignment = '.$this->assignment->id.' '.
               'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';

        $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());

        $table->pagesize($perpage, count($users));

        ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
        $offset = $page * $perpage;
        $strupdate = get_string('update');
        $strgrade  = get_string('grade');
        $grademenu = make_grades_menu($this->assignment->grade);

        if ($ausers !== false) {
            $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
            $endposition = $offset + $perpage;
            $currentposition = 0;
            foreach ($ausers as $auser) {
                if ($currentposition == $offset && $offset < $endposition) {
                    $final_grade = $grading_info->items[0]->grades[$auser->id];
                    $grademax = $grading_info->items[0]->grademax;
                    $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
                    $locked_overridden = 'locked';
                    if ($final_grade->overridden) {
                        $locked_overridden = 'overridden';
                    }

                /// Calculate user status
                    $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
                    $picture = $OUTPUT->user_picture($auser);

                    if (empty($auser->submissionid)) {
                        $auser->grade = -1; //no submission yet
                    }

                    if (!empty($auser->submissionid)) {
                    ///Prints student answer and student modified date
                    ///attach file or print link to student answer, depending on the type of the assignment.
                    ///Refer to print_student_answer in inherited classes.
                        if ($auser->timemodified > 0) {
                            $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
                                             . userdate($auser->timemodified).'</div>';
                        } else {
                            $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
                        }
                    ///Print grade, dropdown or text
                        if ($auser->timemarked > 0) {
                            $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';

                            if ($final_grade->locked or $final_grade->overridden) {
                                $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
                            } else if ($quickgrade) {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                                $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
                            } else {
                                $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
                            }

                        } else {
                            $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
                            if ($final_grade->locked or $final_grade->overridden) {
                                $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
                            } else if ($quickgrade) {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                                $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
                            } else {
                                $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
                            }
                        }
                    ///Print Comment
                        if ($final_grade->locked or $final_grade->overridden) {
                            $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';

                        } else if ($quickgrade) {
                            $comment = '<div id="com'.$auser->id.'">'
                                     . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
                                     . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
                        } else {
                            $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
                        }
                    } else {
                        $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
                        $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
                        $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';

                        if ($final_grade->locked or $final_grade->overridden) {
                            $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
                        } else if ($quickgrade) {   // allow editing
                            $attributes = array();
                            $attributes['tabindex'] = $tabindex++;
                            $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                            $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
                        } else {
                            $grade = '<div id="g'.$auser->id.'">-</div>';
                        }

                        if ($final_grade->locked or $final_grade->overridden) {
                            $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
                        } else if ($quickgrade) {
                            $comment = '<div id="com'.$auser->id.'">'
                                     . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
                                     . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
                        } else {
                            $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
                        }
                    }

                    if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
                        $auser->status = 0;
                    } else {
                        $auser->status = 1;
                    }

                    $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;

                    ///No more buttons, we use popups ;-).
                    $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
                               . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;

                    $button = $OUTPUT->action_link($popup_url, $buttontext);

                    $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';

                    $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';

                    $outcomes = '';

                    if ($uses_outcomes) {

                        foreach($grading_info->outcomes as $n=>$outcome) {
                            $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
                            $options = make_grades_menu(-$outcome->scaleid);

                            if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
                                $options[0] = get_string('nooutcome', 'grades');
                                $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
                            } else {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
                                $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
                            }
                            $outcomes .= '</div>';
                        }
                    }

                    $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
                    $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
                    if ($uses_outcomes) {
                        $row[] = $outcomes;
                    }

                    $table->add_data($row);
                }
                $currentposition++;
            }
        }

        $table->print_html();  /// Print the whole table

        /// Print quickgrade form around the table
        if ($quickgrade && $table->started_output){
            $mailinfopref = false;
            if (get_user_preferences('assignment_mailinfo', 1)) {
                $mailinfopref = true;
            }
            $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enableemailnotification','assignment'));

            $emailnotification .= $OUTPUT->help_icon('enableemailnotification', 'assignment');
            echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));

            $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
            echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));

            echo html_writer::end_tag('form');
        } else if ($quickgrade) {
            echo html_writer::end_tag('form');
        }

        echo '</div>';
        /// End of fast grading form

        /// Mini form for setting user preference

        $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
        $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));

        $mform->addElement('hidden', 'updatepref');
        $mform->setDefault('updatepref', 1);
        $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
        $mform->addElement('select', 'filter', get_string('show'),  $filters);

        $mform->setDefault('filter', $filter);

        $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
        $mform->setDefault('perpage', $perpage);

        $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
        $mform->setDefault('quickgrade', $quickgrade);
        $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');

        $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));

        $mform->display();

        echo $OUTPUT->footer();
    }
/**
 * Get all users who can collect stamps in the given Stamp Collection
 *
 * Returns array of users with the capability mod/stampcoll:collectstamps. Caller may specify the group.
 * If groupmembersonly used, do not return users who are not in any group.
 *
 * @uses $CFG;
 * @param object $cm Course module record
 * @param object $context Current context
 * @param int $currentgroup ID of group the users must be in
 * @return array Array of users
 */
function stampcoll_get_users_can_collect($cm, $context, $currentgroup = false)
{
    global $CFG;
    $users = get_users_by_capability($context, 'mod/stampcoll:collectstamps', 'u.id,u.picture,u.firstname,u.lastname', '', '', '', $currentgroup, '', false, true);
    /// If groupmembersonly used, remove users who are not in any group
    /// XXX this has not been tested yet !!!
    if ($users && !empty($CFG->enablegroupings) && $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id,u.picture,u.firstname,u.lastname')) {
            $users = array_intersect($users, $groupingusers);
        }
    }
    return $users;
}