<commit_before><?php
/**
 * This script lists student attempts
 *
 * @version $Id$
 * @author <NAME>, <NAME> and others.
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package quiz
 *//** */

require_once($CFG->libdir.'/tablelib.php');

class quiz_report extends quiz_default_report {

    /**
     * Display the report.
     */
    function display($quiz, $cm, $course) {
        global $CFG, $SESSION, $db, $QTYPES;

        // Define some strings
        $strreallydel  = addslashes(get_string('deleteattemptcheck','quiz'));
        $strtimeformat = get_string('strftimedatetime');
        $strreviewquestion = get_string('reviewresponse', 'quiz');

        // Only print headers if not asked to download data
        if (!$download = optional_param('download', NULL)) {
            $this->print_header_and_tabs($cm, $course, $quiz, $reportmode="overview");
        }

        // Deal with actions
        $action = optional_param('action', '', PARAM_ACTION);

        switch($action) {
            case 'delete': // Some attempts need to be deleted
                $attemptids = optional_param('attemptid', array(), PARAM_INT);

                foreach($attemptids as $attemptid) {
                    if ($attemptid && $todelete = get_record('quiz_attempts', 'id', $attemptid)) {
                        delete_records('quiz_attempts', 'id', $attemptid);
                        delete_attempt($todelete->uniqueid);

                        // Search quiz_attempts for other instances by this user.
                        // If none, then delete record for this quiz, this user from quiz_grades
                        // else recalculate best grade

                        $userid = $todelete->userid;
                        if (!record_exists('quiz_attempts', 'userid', $userid, 'quiz', $quiz->id)) {
                            delete_records('quiz_grades', 'userid', $userid,'quiz', $quiz->id);
                        } else {
                            quiz_save_best_grade($quiz, $userid);
                        }
                    }
                }
            break;
        }
        
        // Print information on the number of existing attempts
        if (!$download) { //do not print notices when downloading
            if ($attemptnum = count_records('quiz_attempts', 'quiz', $quiz->id, 'preview', 0)) {
                $a = new stdClass;
                $a->attemptnum = $attemptnum;
                $a->studentnum = count_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'", 'COUNT(DISTINCT userid)');
                $a->studentstring = $course->students;
    
                notify(get_string('numattempts', 'quiz', $a));
            }
        }
        
        // Check to see if groups are being used in this quiz
        if ($groupmode = groupmode($course, $cm)) {   // Groups are being used
            if (!$download) {
                $currentgroup = setup_and_print_groups($course, $groupmode, "report.php?id=$cm->id&amp;mode=overview");
            } else {
                if (isset($_GET['group'])) {
                    $changegroup = $_GET['group']; // 0 or higher
                } else {
                    $changegroup = -1; // This means no group change was specified
                }

                $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
            }
        } else {
            $currentgroup = false;
        }

        // Set table options
        $noattempts = optional_param('noattempts', 0, PARAM_INT);
        $detailedmarks = optional_param('detailedmarks', 0, PARAM_INT);
        $pagesize = optional_param('pagesize', 10, PARAM_INT);
        $hasfeedback = quiz_has_feedback($quiz->id) && $quiz->grade > 1.e-7 && $quiz->sumgrades > 1.e-7;

        // Now check if asked download of data
        if ($download) {
            $filename = clean_filename("$course->shortname ".format_string($quiz->name,true));
            $sort = '';
            $limit = '';
        }

        // Define table columns
        $tablecolumns = array('checkbox', 'picture', 'fullname', 'timestart', 'timefinish', 'duration');
        $tableheaders = array(NULL, '', get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted','quiz'), get_string('attemptduration', 'quiz'));

        if ($quiz->grade and $quiz->sumgrades) {
            $tablecolumns[] = 'sumgrades';
            $tableheaders[] = get_string('grade', 'quiz').'/'.$quiz->grade;
        }

        if($detailedmarks) {
            // we want to display marks for all questions
            // Start by getting all questions
            $questionlist = quiz_questions_in_quiz($quiz->questions);
            $questionids = explode(',', $questionlist);
            $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance".
                    "  FROM {$CFG->prefix}question q,".
                    "       {$CFG->prefix}quiz_question_instances i".
                    " WHERE i.quiz = '$quiz->id' AND q.id = i.question".
                    "   AND q.id IN ($questionlist)";
            if (!$questions = get_records_sql($sql)) {
                error('No questions found');
            }
            $number = 1;
            foreach($questionids as $key => $id) {
                if ($questions[$id]->length) {
                    // Only print questions of non-zero length
                    $tablecolumns[] = '$'.$id;
                    $tableheaders[] = '#'.$number;
                    $questions[$id]->number = $number;
                    $number += $questions[$id]->length;
                } else {
                    // get rid of zero length questions
                    unset($questions[$id]);
                    unset($questionids[$key]);
                }
            }
        }

        if ($hasfeedback) {
            $tablecolumns[] = 'feedback';
            $tableheaders[] = get_string('feedback', 'quiz');
        }
        
        if (!$download) {
            // Set up the table

            $table = new flexible_table('mod-quiz-report-overview-report');

            $table->define_columns($tablecolumns);
            $table->define_headers($tableheaders);
            $table->define_baseurl($CFG->wwwroot.'/mod/quiz/report.php?mode=overview&amp;id='.$cm->id);

            $table->sortable(true);
            $table->collapsible(true);

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

            $table->column_class('picture', 'picture');

            $table->set_attribute('cellspacing', '0');
            $table->set_attribute('id', 'attempts');
            $table->set_attribute('class', 'generaltable generalbox');

            // Start working -- this is necessary as soon as the niceties are over
            $table->setup();
        } else if ($download =='Excel') {
            require_once("$CFG->libdir/excellib.class.php");

            $filename .= ".xls";
            // Creating a workbook
            $workbook = new MoodleExcelWorkbook("-");
            // Sending HTTP headers
            $workbook->send($filename);
            // Creating the first worksheet
            $sheettitle = get_string('reportoverview','quiz');
            $myxls =& $workbook->add_worksheet($sheettitle);
            // format types
            $format =& $workbook->add_format();
            $format->set_bold(0);
            $formatbc =& $workbook->add_format();
            $formatbc->set_bold(1);
            $formatbc->set_align('center');
            $formatb =& $workbook->add_format();
            $formatb->set_bold(1);
            $formaty =& $workbook->add_format();
            $formaty->set_bg_color('yellow');
            $formatc =& $workbook->add_format();
            $formatc->set_align('center');
            $formatr =& $workbook->add_format();
            $formatr->set_bold(1);
            $formatr->set_color('red');
            $formatr->set_align('center');
            $formatg =& $workbook->add_format();
            $formatg->set_bold(1);
            $formatg->set_color('green');
            $formatg->set_align('center');
            // Here starts workshhet headers

            $headers = array(get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted', 'quiz'), get_string('attemptduration', 'quiz'));

            if ($quiz->grade and $quiz->sumgrades) {
                $headers[] = get_string('grade', 'quiz').'/'.$quiz->grade;
            }
            if($detailedmarks) {
                foreach ($questionids as $id) {
                    $headers[] = '#'.$questions[$id]->number;
                }
            }
            if ($hasfeedback) {
                $headers[] = get_string('feedback', 'quiz');
            }
            $colnum = 0;
            foreach ($headers as $item) {
                $myxls->write(0,$colnum,$item,$formatbc);
                $colnum++;
            }
            $rownum=1;
        } else if ($download=='CSV') {
            $filename .= ".txt";

            header("Content-Type: application/download\n");
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header("Expires: 0");
            header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
            header("Pragma: public");

            $headers = get_string('fullname')."\t".get_string('startedon', 'quiz')."\t".get_string('timecompleted', 'quiz')."\t".get_string('attemptduration', 'quiz');

            if ($quiz->grade and $quiz->sumgrades) {
                $headers .= "\t".get_string('grade', 'quiz')."/".$quiz->grade;
            }
            if($detailedmarks) {
                foreach ($questionids as $id) {
                    $headers .= "\t#".$questions[$id]->number;
                }
            }
            if ($hasfeedback) {
                $headers .= "\t" . get_string('feedback', 'quiz');
            }
            echo $headers." \n";
        }
        
        $contextlists = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $course->id));

        // Construct the SQL
        $select = 'SELECT '.$db->Concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')).' AS uniqueid, '.
            'qa.uniqueid as attemptuniqueid, qa.id AS attempt, u.id AS userid, u.firstname, u.lastname, u.picture, '.
            'qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ';
        if ($course->id != SITEID) { // this is too complicated, so just do it for each of the four cases.
            if (!empty($currentgroup) && empty($noattempts)) {
                // we want a particular group and we only want to see students WITH attempts.
                // So join on groups_members and do an inner join on attempts.
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id JOIN '.$CFG->prefix.'groups_members gm ON u.id = gm.userid '.
                    'JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = ' WHERE ra.contextid $contextlists AND gm.groupid = '.$currentgroup.' AND qa.preview = 0';                
            } else if (!empty($currentgroup) && !empty($noattempts)) {
                // We want a particular group and we want to do something funky with attempts
                // So join on groups_members and left join on attempts... 
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id JOIN '.$CFG->prefix.'groups_members gm ON u.id = gm.userid '.
                    'LEFT JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = ' WHERE ra.contextid $contextlists AND gm.groupid = '.$currentgroup.' AND qa.preview = 0';
                if ($noattempts == 1) {
                    // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
                    $where .= ' AND qa.userid IS NULL'; // show ONLY no attempts;
                } // no else, the left join is not filtered, which means we get both back.
            } else if (empty($currentgroup)) {
                // We don't care about group, and we to do something funky with attempts
                // So do a left join on attempts
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id LEFT JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = " WHERE ra.contextid $contextlists";
                if (empty($noattempts)) {
                    $where .= ' AND qa.userid IS NOT NULL'; // show ONLY students with attempts;
                } else if ($noattempts == 1) {
                    // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
                    $where .= ' AND qa.userid IS NULL'; // show ONLY students without attempts;
                } else if ($noattempts == 3) {
                    // we want all attempts
                    $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid ';
                    $where = ' WHERE qa.quiz = '.$quiz->id.' AND qa.preview = 0';<commit_msg>Fix typos in string concatenation.<commit_after><?php
/**
 * This script lists student attempts
 *
 * @version $Id$
 * @author <NAME>, <NAME> and others.
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package quiz
 *//** */

require_once($CFG->libdir.'/tablelib.php');

class quiz_report extends quiz_default_report {

    /**
     * Display the report.
     */
    function display($quiz, $cm, $course) {
        global $CFG, $SESSION, $db, $QTYPES;

        // Define some strings
        $strreallydel  = addslashes(get_string('deleteattemptcheck','quiz'));
        $strtimeformat = get_string('strftimedatetime');
        $strreviewquestion = get_string('reviewresponse', 'quiz');

        // Only print headers if not asked to download data
        if (!$download = optional_param('download', NULL)) {
            $this->print_header_and_tabs($cm, $course, $quiz, $reportmode="overview");
        }

        // Deal with actions
        $action = optional_param('action', '', PARAM_ACTION);

        switch($action) {
            case 'delete': // Some attempts need to be deleted
                $attemptids = optional_param('attemptid', array(), PARAM_INT);

                foreach($attemptids as $attemptid) {
                    if ($attemptid && $todelete = get_record('quiz_attempts', 'id', $attemptid)) {
                        delete_records('quiz_attempts', 'id', $attemptid);
                        delete_attempt($todelete->uniqueid);

                        // Search quiz_attempts for other instances by this user.
                        // If none, then delete record for this quiz, this user from quiz_grades
                        // else recalculate best grade

                        $userid = $todelete->userid;
                        if (!record_exists('quiz_attempts', 'userid', $userid, 'quiz', $quiz->id)) {
                            delete_records('quiz_grades', 'userid', $userid,'quiz', $quiz->id);
                        } else {
                            quiz_save_best_grade($quiz, $userid);
                        }
                    }
                }
            break;
        }
        
        // Print information on the number of existing attempts
        if (!$download) { //do not print notices when downloading
            if ($attemptnum = count_records('quiz_attempts', 'quiz', $quiz->id, 'preview', 0)) {
                $a = new stdClass;
                $a->attemptnum = $attemptnum;
                $a->studentnum = count_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'", 'COUNT(DISTINCT userid)');
                $a->studentstring = $course->students;
    
                notify(get_string('numattempts', 'quiz', $a));
            }
        }
        
        // Check to see if groups are being used in this quiz
        if ($groupmode = groupmode($course, $cm)) {   // Groups are being used
            if (!$download) {
                $currentgroup = setup_and_print_groups($course, $groupmode, "report.php?id=$cm->id&amp;mode=overview");
            } else {
                if (isset($_GET['group'])) {
                    $changegroup = $_GET['group']; // 0 or higher
                } else {
                    $changegroup = -1; // This means no group change was specified
                }

                $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
            }
        } else {
            $currentgroup = false;
        }

        // Set table options
        $noattempts = optional_param('noattempts', 0, PARAM_INT);
        $detailedmarks = optional_param('detailedmarks', 0, PARAM_INT);
        $pagesize = optional_param('pagesize', 10, PARAM_INT);
        $hasfeedback = quiz_has_feedback($quiz->id) && $quiz->grade > 1.e-7 && $quiz->sumgrades > 1.e-7;

        // Now check if asked download of data
        if ($download) {
            $filename = clean_filename("$course->shortname ".format_string($quiz->name,true));
            $sort = '';
            $limit = '';
        }

        // Define table columns
        $tablecolumns = array('checkbox', 'picture', 'fullname', 'timestart', 'timefinish', 'duration');
        $tableheaders = array(NULL, '', get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted','quiz'), get_string('attemptduration', 'quiz'));

        if ($quiz->grade and $quiz->sumgrades) {
            $tablecolumns[] = 'sumgrades';
            $tableheaders[] = get_string('grade', 'quiz').'/'.$quiz->grade;
        }

        if($detailedmarks) {
            // we want to display marks for all questions
            // Start by getting all questions
            $questionlist = quiz_questions_in_quiz($quiz->questions);
            $questionids = explode(',', $questionlist);
            $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance".
                    "  FROM {$CFG->prefix}question q,".
                    "       {$CFG->prefix}quiz_question_instances i".
                    " WHERE i.quiz = '$quiz->id' AND q.id = i.question".
                    "   AND q.id IN ($questionlist)";
            if (!$questions = get_records_sql($sql)) {
                error('No questions found');
            }
            $number = 1;
            foreach($questionids as $key => $id) {
                if ($questions[$id]->length) {
                    // Only print questions of non-zero length
                    $tablecolumns[] = '$'.$id;
                    $tableheaders[] = '#'.$number;
                    $questions[$id]->number = $number;
                    $number += $questions[$id]->length;
                } else {
                    // get rid of zero length questions
                    unset($questions[$id]);
                    unset($questionids[$key]);
                }
            }
        }

        if ($hasfeedback) {
            $tablecolumns[] = 'feedback';
            $tableheaders[] = get_string('feedback', 'quiz');
        }
        
        if (!$download) {
            // Set up the table

            $table = new flexible_table('mod-quiz-report-overview-report');

            $table->define_columns($tablecolumns);
            $table->define_headers($tableheaders);
            $table->define_baseurl($CFG->wwwroot.'/mod/quiz/report.php?mode=overview&amp;id='.$cm->id);

            $table->sortable(true);
            $table->collapsible(true);

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

            $table->column_class('picture', 'picture');

            $table->set_attribute('cellspacing', '0');
            $table->set_attribute('id', 'attempts');
            $table->set_attribute('class', 'generaltable generalbox');

            // Start working -- this is necessary as soon as the niceties are over
            $table->setup();
        } else if ($download =='Excel') {
            require_once("$CFG->libdir/excellib.class.php");

            $filename .= ".xls";
            // Creating a workbook
            $workbook = new MoodleExcelWorkbook("-");
            // Sending HTTP headers
            $workbook->send($filename);
            // Creating the first worksheet
            $sheettitle = get_string('reportoverview','quiz');
            $myxls =& $workbook->add_worksheet($sheettitle);
            // format types
            $format =& $workbook->add_format();
            $format->set_bold(0);
            $formatbc =& $workbook->add_format();
            $formatbc->set_bold(1);
            $formatbc->set_align('center');
            $formatb =& $workbook->add_format();
            $formatb->set_bold(1);
            $formaty =& $workbook->add_format();
            $formaty->set_bg_color('yellow');
            $formatc =& $workbook->add_format();
            $formatc->set_align('center');
            $formatr =& $workbook->add_format();
            $formatr->set_bold(1);
            $formatr->set_color('red');
            $formatr->set_align('center');
            $formatg =& $workbook->add_format();
            $formatg->set_bold(1);
            $formatg->set_color('green');
            $formatg->set_align('center');
            // Here starts workshhet headers

            $headers = array(get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted', 'quiz'), get_string('attemptduration', 'quiz'));

            if ($quiz->grade and $quiz->sumgrades) {
                $headers[] = get_string('grade', 'quiz').'/'.$quiz->grade;
            }
            if($detailedmarks) {
                foreach ($questionids as $id) {
                    $headers[] = '#'.$questions[$id]->number;
                }
            }
            if ($hasfeedback) {
                $headers[] = get_string('feedback', 'quiz');
            }
            $colnum = 0;
            foreach ($headers as $item) {
                $myxls->write(0,$colnum,$item,$formatbc);
                $colnum++;
            }
            $rownum=1;
        } else if ($download=='CSV') {
            $filename .= ".txt";

            header("Content-Type: application/download\n");
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header("Expires: 0");
            header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
            header("Pragma: public");

            $headers = get_string('fullname')."\t".get_string('startedon', 'quiz')."\t".get_string('timecompleted', 'quiz')."\t".get_string('attemptduration', 'quiz');

            if ($quiz->grade and $quiz->sumgrades) {
                $headers .= "\t".get_string('grade', 'quiz')."/".$quiz->grade;
            }
            if($detailedmarks) {
                foreach ($questionids as $id) {
                    $headers .= "\t#".$questions[$id]->number;
                }
            }
            if ($hasfeedback) {
                $headers .= "\t" . get_string('feedback', 'quiz');
            }
            echo $headers." \n";
        }
        
        $contextlists = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $course->id));

        // Construct the SQL
        $select = 'SELECT '.$db->Concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')).' AS uniqueid, '.
            'qa.uniqueid as attemptuniqueid, qa.id AS attempt, u.id AS userid, u.firstname, u.lastname, u.picture, '.
            'qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ';
        if ($course->id != SITEID) { // this is too complicated, so just do it for each of the four cases.
            if (!empty($currentgroup) && empty($noattempts)) {
                // we want a particular group and we only want to see students WITH attempts.
                // So join on groups_members and do an inner join on attempts.
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id JOIN '.$CFG->prefix.'groups_members gm ON u.id = gm.userid '.
                    'JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = ' WHERE ra.contextid ' . $contextlists . ' AND gm.groupid = '.$currentgroup.' AND qa.preview = 0';                
            } else if (!empty($currentgroup) && !empty($noattempts)) {
                // We want a particular group and we want to do something funky with attempts
                // So join on groups_members and left join on attempts... 
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id JOIN '.$CFG->prefix.'groups_members gm ON u.id = gm.userid '.
                    'LEFT JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = ' WHERE ra.contextid ' . $contextlists . ' AND gm.groupid = '.$currentgroup.' AND qa.preview = 0';
                if ($noattempts == 1) {
                    // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
                    $where .= ' AND qa.userid IS NULL'; // show ONLY no attempts;
                } // no else, the left join is not filtered, which means we get both back.
            } else if (empty($currentgroup)) {
                // We don't care about group, and we to do something funky with attempts
                // So do a left join on attempts
                $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id LEFT JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id;
                $where = " WHERE ra.contextid $contextlists";
                if (empty($noattempts)) {
                    $where .= ' AND qa.userid IS NOT NULL'; // show ONLY students with attempts;
                } else if ($noattempts == 1) {
                    // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
                    $where .= ' AND qa.userid IS NULL'; // show ONLY students without attempts;
                } else if ($noattempts == 3) {
                    // we want all attempts
                    $from  = 'FROM '.$CFG->prefix.'user u JOIN '.$CFG->prefix.'quiz_attempts qa ON u.id = qa.userid ';
                    $where = ' WHERE qa.quiz = '.$quiz->id.' AND qa.preview = 0';
{'fraction_non_alphanumeric': 0.14573313946985797, 'fraction_numerical': 0.0025351377549118295, 'mean_word_length': 1.8029258098223615, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 201, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2746035', 'n_tokens_mistral': 7806, 'n_tokens_neox': 7350, 'n_words': 1795}