Example #1
0
function user_download_ods($fields)
{
    global $CFG, $SESSION, $DB;
    require_once "{$CFG->libdir}/odslib.class.php";
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $filename = clean_filename(get_string('users') . '.ods');
    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] =& $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }
    $row = 1;
    foreach ($SESSION->bulk_users as $userid) {
        if (!($user = $DB->get_record('user', array('id' => $userid)))) {
            continue;
        }
        $col = 0;
        profile_load_data($user);
        foreach ($fields as $field => $unused) {
            $worksheet[0]->write($row, $col, $user->{$field});
            $col++;
        }
        $row++;
    }
    $workbook->close();
    die;
}
function user_download_ods($fields, $extrafields = array())
{
    global $CFG, $SESSION, $DB;
    require_once "{$CFG->libdir}/odslib.class.php";
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $filename = clean_filename(get_string('users') . '.ods');
    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }
    $extrafield_sql = '';
    foreach ($extrafields as $n => $v) {
        $extrafield_sql .= " MAX(IF(muif.shortname = '" . $v->shortname . "', muid.data, NULL)) profile_field_" . $v->shortname . ",";
    }
    $extrafield_sql = rtrim($extrafield_sql, ",");
    $idstoload = $SESSION->bulk_users;
    $users = array();
    foreach (array_chunk($idstoload, 10000, true) as $user_id) {
        $userids = implode(",", $user_id);
        $users[] = $DB->get_records_sql("SELECT mu.*,\r\n                                {$extrafield_sql}\r\n                                FROM mdl_user AS mu\r\n                                LEFT JOIN mdl_user_info_data AS muid ON mu.id = muid.userid\r\n                                LEFT JOIN mdl_user_info_field AS muif ON muif.id = muid.fieldid\r\n                                WHERE mu.id IN ({$userids}) GROUP BY mu.id");
    }
    $row = 1;
    foreach ($users as $userdetails) {
        foreach ($userdetails as $user) {
            #if (!$user = $DB->get_record('user', array('id'=>$userid))) {
            #continue;
            #}
            $col = 0;
            #profile_load_data($user,$userfields);
            foreach ($fields as $field => $unused) {
                $worksheet[0]->write($row, $col, $user->{$field});
                $col++;
            }
            $row++;
        }
    }
    $workbook->close();
    die;
}
Example #3
0
/** Configurable Reports
 * A Moodle block for creating customizable reports
 * @package blocks
 * @author: Juan leyva <http://www.twitter.com/jleyvadelgado>
 * @date: 2009
 */
function export_report($report) {
    global $DB, $CFG;
    require_once($CFG->dirroot . '/lib/odslib.class.php');

    $table = $report->table;
    $matrix = array();
    $filename = 'report_' . (time()) . '.ods';

    if (!empty($table->head)) {
        $countcols = count($table->head);
        $keys = array_keys($table->head);
        $lastkey = end($keys);
        foreach ($table->head as $key => $heading) {
            $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading))));
        }
    }

    if (!empty($table->data)) {
        foreach ($table->data as $rkey => $row) {
            foreach ($row as $key => $item) {
                $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item))));
            }
        }
    }

    $downloadfilename = clean_filename($filename);
    /// Creating a workbook
    $workbook = new MoodleODSWorkbook("-");
    /// Sending HTTP headers
    $workbook->send($downloadfilename);
    /// Adding the worksheet
    $myxls = & $workbook->add_worksheet($filename);

    foreach ($matrix as $ri => $col) {
        foreach ($col as $ci => $cv) {
            $myxls->write_string($ri, $ci, $cv);
        }
    }

    $workbook->close();
    exit;
}
    $groupmode = groups_get_activity_groupmode($cm);
}
add_to_log($course->id, 'certificate', 'view', "report.php?id={$cm->id}", '$certificate->id', $cm->id);
// Ensure there are issues to display, if not display notice
if (!($users = certificate_get_issues($certificate->id, $DB->sql_fullname(), $groupmode, $cm))) {
    echo $OUTPUT->header();
    notify(get_string('nocertificatesissued', 'certificate'));
    echo $OUTPUT->footer($course);
    exit;
}
if ($download == "ods") {
    require_once "{$CFG->libdir}/odslib.class.php";
    // Calculate file name
    $filename = clean_filename("{$course->shortname} " . strip_tags(format_string($certificate->name, true))) . '.ods';
    // Creating a workbook
    $workbook = new MoodleODSWorkbook("-");
    // Send HTTP headers
    $workbook->send($filename);
    // Creating the first worksheet
    $myxls =& $workbook->add_worksheet($strreport);
    // Print names of all the fields
    $myxls->write_string(0, 0, get_string("lastname"));
    $myxls->write_string(0, 1, get_string("firstname"));
    $myxls->write_string(0, 2, get_string("idnumber"));
    $myxls->write_string(0, 3, get_string("group"));
    $myxls->write_string(0, 4, $strdate);
    $myxls->write_string(0, 5, $strgrade);
    $myxls->write_string(0, 6, $strcode);
    // Generate the data for the body of the spreadsheet
    $i = 0;
    $row = 1;
Example #5
0
 function Export_ODS(&$questions, $filename)
 {
     global $CFG;
     require_once "{$CFG->libdir}/odslib.class.php";
     /// Calculate file name
     $filename .= ".ods";
     /// Creating a workbook
     $workbook = new MoodleODSWorkbook("-");
     /// Sending HTTP headers
     $workbook->send($filename);
     /// Creating the first worksheet
     $sheettitle = get_string('reportanalysis', 'quiz_analysis');
     $myxls =& $workbook->add_worksheet($sheettitle);
     /// format types
     $format =& $workbook->add_format();
     $format->set_bold(0);
     $formatbc =& $workbook->add_format();
     $formatbc->set_bold(1);
     $formatb =& $workbook->add_format();
     $formatb->set_bold(1);
     $formaty =& $workbook->add_format();
     $formaty->set_bg_color('yellow');
     $formatyc =& $workbook->add_format();
     $formatyc->set_bg_color('yellow');
     //bold text on yellow bg
     $formatyc->set_bold(1);
     $formatyc->set_align('center');
     $formatc =& $workbook->add_format();
     $formatc->set_align('center');
     $formatbc->set_align('center');
     $formatbpct =& $workbook->add_format();
     $formatbpct->set_bold(1);
     $formatbpct->set_num_format('0.0%');
     $formatbrt =& $workbook->add_format();
     $formatbrt->set_bold(1);
     $formatbrt->set_align('right');
     $formatred =& $workbook->add_format();
     $formatred->set_bold(1);
     $formatred->set_color('red');
     $formatred->set_align('center');
     $formatblue =& $workbook->add_format();
     $formatblue->set_bold(1);
     $formatblue->set_color('blue');
     $formatblue->set_align('center');
     /// Here starts workshhet headers
     $myxls->write_string(0, 0, $sheettitle, $formatb);
     $headers = array(get_string('qidtitle', 'quiz_analysis'), get_string('qtypetitle', 'quiz_analysis'), get_string('qnametitle', 'quiz_analysis'), get_string('qtexttitle', 'quiz_analysis'), get_string('responsestitle', 'quiz_analysis'), get_string('rfractiontitle', 'quiz_analysis'), get_string('rcounttitle', 'quiz_analysis'), get_string('rpercenttitle', 'quiz_analysis'), get_string('qcounttitle', 'quiz_analysis'), get_string('facilitytitle', 'quiz_analysis'), get_string('stddevtitle', 'quiz_analysis'), get_string('dicsindextitle', 'quiz_analysis'), get_string('disccoefftitle', 'quiz_analysis'));
     foreach ($headers as $key => $header) {
         $headers[$key] = preg_replace('/<br[^>]*>/', ' ', $header);
     }
     $col = 0;
     foreach ($headers as $item) {
         $myxls->write(2, $col, $item, $formatbc);
         $col++;
     }
     $row = 3;
     foreach ($questions as $q) {
         $rows = $this->print_row_stats_data($q);
         foreach ($rows as $rowdata) {
             $col = 0;
             foreach ($rowdata as $item) {
                 $myxls->write($row, $col, $item, $format);
                 $col++;
             }
             $row++;
         }
     }
     /// Close the workbook
     $workbook->close();
     exit;
 }
Example #6
0
/**
 * @global object
 * @param array $export
 * @param string $dataname
 * @param int $count
 * @param string
 */
function data_export_ods($export, $dataname, $count) {
    global $CFG;
    require_once("$CFG->libdir/odslib.class.php");
    $filename = clean_filename("{$dataname}-{$count}_record");
    if ($count > 1) {
        $filename .= 's';
    }
    $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
    $filename .= '.ods';
    $filearg = '-';
    $workbook = new MoodleODSWorkbook($filearg);
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] =& $workbook->add_worksheet('');
    $rowno = 0;
    foreach ($export as $row) {
        $colno = 0;
        foreach($row as $col) {
            $worksheet[0]->write($rowno, $colno, $col);
            $colno++;
        }
        $rowno++;
    }
    $workbook->close();
    return $filename;
}
Example #7
0
function print_log_ods($course, $user, $date, $order = 'l.time DESC', $modname, $modid, $modaction, $groupid)
{
    global $CFG, $DB;
    require_once "{$CFG->libdir}/odslib.class.php";
    if (!($logs = build_logs_array($course, $user, $date, $order, '', '', $modname, $modid, $modaction, $groupid))) {
        return false;
    }
    $courses = array();
    if ($course->id == SITEID) {
        $courses[0] = '';
        if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
            foreach ($ccc as $cc) {
                $courses[$cc->id] = $cc->shortname;
            }
        }
    } else {
        $courses[$course->id] = $course->shortname;
    }
    $count = 0;
    $ldcache = array();
    $tt = getdate(time());
    $today = mktime(0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
    $strftimedatetime = get_string("strftimedatetime");
    $nroPages = ceil(count($logs) / (EXCELROWS - FIRSTUSEDEXCELROW + 1));
    $filename = 'logs_' . userdate(time(), get_string('backupnameformat', 'langconfig'), 99, false);
    $filename .= '.ods';
    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $headers = array(get_string('course'), get_string('time'), get_string('ip_address'), get_string('fullnameuser'), get_string('action'), get_string('info'));
    // Creating worksheets
    for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
        $sheettitle = get_string('logs') . ' ' . $wsnumber . '-' . $nroPages;
        $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
        $worksheet[$wsnumber]->set_column(1, 1, 30);
        $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat') . userdate(time(), $strftimedatetime));
        $col = 0;
        foreach ($headers as $item) {
            $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW - 1, $col, $item, '');
            $col++;
        }
    }
    if (empty($logs['logs'])) {
        $workbook->close();
        return true;
    }
    $formatDate =& $workbook->add_format();
    $formatDate->set_num_format(get_string('log_excel_date_format'));
    $row = FIRSTUSEDEXCELROW;
    $wsnumber = 1;
    $myxls =& $worksheet[$wsnumber];
    foreach ($logs['logs'] as $log) {
        if (isset($ldcache[$log->module][$log->action])) {
            $ld = $ldcache[$log->module][$log->action];
        } else {
            $ld = $DB->get_record('log_display', array('module' => $log->module, 'action' => $log->action));
            $ldcache[$log->module][$log->action] = $ld;
        }
        if ($ld && !empty($log->info)) {
            // ugly hack to make sure fullname is shown correctly
            if ($ld->mtable == 'user' and $ld->field == $DB->sql_concat('firstname', "' '", 'lastname')) {
                $log->info = fullname($DB->get_record($ld->mtable, array('id' => $log->info)), true);
            } else {
                $log->info = $DB->get_field($ld->mtable, $ld->field, array('id' => $log->info));
            }
        }
        // Filter log->info
        $log->info = format_string($log->info);
        $log->info = strip_tags(urldecode($log->info));
        // Some XSS protection
        if ($nroPages > 1) {
            if ($row > EXCELROWS) {
                $wsnumber++;
                $myxls =& $worksheet[$wsnumber];
                $row = FIRSTUSEDEXCELROW;
            }
        }
        $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
        $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
        $myxls->write_date($row, 1, $log->time);
        $myxls->write_string($row, 2, $log->ip);
        $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
        $myxls->write_string($row, 3, $fullname);
        $myxls->write_string($row, 4, $log->module . ' ' . $log->action);
        $myxls->write_string($row, 5, $log->info);
        $row++;
    }
    $workbook->close();
    return true;
}
Example #8
0
    /**
     * displays the full report
     * @param stdClass $scorm full SCORM object
     * @param stdClass $cm - full course_module object
     * @param stdClass $course - full course object
     * @param string $download - type of download being requested
     */
    function display($scorm, $cm, $course, $download) {
        global $CFG, $DB, $OUTPUT, $PAGE;
        $contextmodule = get_context_instance(CONTEXT_MODULE, $cm->id);
        $action = optional_param('action', '', PARAM_ALPHA);
        $attemptids = optional_param_array('attemptid', array(), PARAM_RAW);
        $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_ALL_STUDENTS, PARAM_INT);
        $PAGE->set_url(new moodle_url($PAGE->url, array('attemptsmode' => $attemptsmode)));

        if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) {
            if (scorm_delete_responses($attemptids, $scorm)) { //delete responses.
                add_to_log($course->id, 'scorm', 'delete attempts', 'report.php?id=' . $cm->id, implode(",", $attemptids), $cm->id);
                echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess');
            }
        }
        // find out current groups mode
        $currentgroup = groups_get_activity_group($cm, true);

        // detailed report
        $mform = new mod_scorm_report_interactions_settings($PAGE->url, compact('currentgroup'));
        if ($fromform = $mform->get_data()) {
            $pagesize = $fromform->pagesize;
            $includeqtext = $fromform->qtext;
            $includeresp = $fromform->resp;
            $includeright = $fromform->right;
            set_user_preference('scorm_report_pagesize', $pagesize);
            set_user_preference('scorm_report_interactions_qtext', $includeqtext);
            set_user_preference('scorm_report_interactions_resp', $includeresp);
            set_user_preference('scorm_report_interactions_right', $includeright);
        } else {
            $pagesize = get_user_preferences('scorm_report_pagesize', 0);
            $includeqtext = get_user_preferences('scorm_report_interactions_qtext', 0);
            $includeresp = get_user_preferences('scorm_report_interactions_resp', 1);
            $includeright = get_user_preferences('scorm_report_interactions_right', 0);
        }
        if ($pagesize < 1) {
            $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
        }

        // select group menu
        $displayoptions = array();
        $displayoptions['attemptsmode'] = $attemptsmode;
        $displayoptions['qtext'] = $includeqtext;
        $displayoptions['resp'] = $includeresp;
        $displayoptions['right'] = $includeright;

        $mform->set_data($displayoptions + array('pagesize' => $pagesize));
        if ($groupmode = groups_get_activity_groupmode($cm)) {   // Groups are being used
            if (!$download) {
                groups_print_activity_menu($cm, new moodle_url($PAGE->url, $displayoptions));
            }
        }
        $formattextoptions = array('context' => get_context_instance(CONTEXT_COURSE, $course->id));

        // We only want to show the checkbox to delete attempts
        // if the user has permissions and if the report mode is showing attempts.
        $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule)
                && ($attemptsmode != SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO);
        // select the students
        $nostudents = false;

        if (empty($currentgroup)) {
            // all users who can attempt scoes
            if (!$students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', '', '', false)) {
                echo $OUTPUT->notification(get_string('nostudentsyet'));
                $nostudents = true;
                $allowedlist = '';
            } else {
                $allowedlist = array_keys($students);
            }
        } else {
            // all users who can attempt scoes and who are in the currently selected group
            if (!$groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', $currentgroup, '', false)) {
                echo $OUTPUT->notification(get_string('nostudentsingroup'));
                $nostudents = true;
                $groupstudents = array();
            }
            $allowedlist = array_keys($groupstudents);
        }
        if ( !$nostudents ) {
            // Now check if asked download of data
            $coursecontext = context_course::instance($course->id);
            if ($download) {
                $filename = clean_filename("$course->shortname ".format_string($scorm->name, true,$formattextoptions));
            }

            // Define table columns
            $columns = array();
            $headers = array();
            if (!$download && $candelete) {
                $columns[] = 'checkbox';
                $headers[] = null;
            }
            if (!$download && $CFG->grade_report_showuserimage) {
                $columns[] = 'picture';
                $headers[] = '';
            }
            $columns[] = 'fullname';
            $headers[] = get_string('name');

            $extrafields = get_extra_user_fields($coursecontext);
            foreach ($extrafields as $field) {
                $columns[] = $field;
                $headers[] = get_user_field_name($field);
            }
            $columns[] = 'attempt';
            $headers[] = get_string('attempt', 'scorm');
            $columns[] = 'start';
            $headers[] = get_string('started', 'scorm');
            $columns[] = 'finish';
            $headers[] = get_string('last', 'scorm');
            $columns[] = 'score';
            $headers[] = get_string('score', 'scorm');
            $scoes = $DB->get_records('scorm_scoes', array("scorm"=>$scorm->id), 'id');
            foreach ($scoes as $sco) {
                if ($sco->launch != '') {
                    $columns[] = 'scograde'.$sco->id;
                    $headers[] = format_string($sco->title,'',$formattextoptions);
                }
            }

            $params = array();
            list($usql, $params) = $DB->get_in_or_equal($allowedlist, SQL_PARAMS_NAMED);
                                    // Construct the SQL
            $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
            $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
                    'u.id AS userid, u.idnumber, u.firstname, u.lastname, u.picture, u.imagealt, u.email'.
                    get_extra_user_fields_sql($coursecontext, 'u', '', array('idnumber')) . ' ';

            // This part is the same for all cases - join users and scorm_scoes_track tables
            $from = 'FROM {user} u ';
            $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
            switch ($attemptsmode) {
                case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
                    // Show only students with attempts
                    $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NOT NULL';
                    break;
                case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
                    // Show only students without attempts
                    $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NULL';
                    break;
                case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
                    // Show all students with or without attempts
                    $where = ' WHERE u.id ' .$usql. ' AND (st.userid IS NOT NULL OR st.userid IS NULL)';
                    break;
            }

            $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
            $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
            $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
            $countsql .= $from.$where;
            $attempts = $DB->get_records_sql($select.$from.$where, $params);
            $questioncount = get_scorm_question_count($scorm->id);
            for($id = 0; $id < $questioncount; $id++) {
                if ($displayoptions['qtext']) {
                    $columns[] = 'question' . $id;
                    $headers[] = get_string('questionx', 'scormreport_interactions', $id);
                }
                if ($displayoptions['resp']) {
                    $columns[] = 'response' . $id;
                    $headers[] = get_string('responsex', 'scormreport_interactions', $id);
                }
                if ($displayoptions['right']) {
                    $columns[] = 'right' . $id;
                    $headers[] = get_string('rightanswerx', 'scormreport_interactions', $id);
                }
            }

            if (!$download) {
                $table = new flexible_table('mod-scorm-report');

                $table->define_columns($columns);
                $table->define_headers($headers);
                $table->define_baseurl($PAGE->url);

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

                // This is done to prevent redundant data, when a user has multiple attempts
                $table->column_suppress('picture');
                $table->column_suppress('fullname');
                foreach ($extrafields as $field) {
                    $table->column_suppress($field);
                }

                $table->no_sorting('start');
                $table->no_sorting('finish');
                $table->no_sorting('score');

                foreach ($scoes as $sco) {
                    if ($sco->launch != '') {
                        $table->no_sorting('scograde'.$sco->id);
                    }
                }

                $table->column_class('picture', 'picture');
                $table->column_class('fullname', 'bold');
                $table->column_class('score', 'bold');

                $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 == 'ODS') {
                require_once("$CFG->libdir/odslib.class.php");

                $filename .= ".ods";
                // Creating a workbook
                $workbook = new MoodleODSWorkbook("-");
                // Sending HTTP headers
                $workbook->send($filename);
                // Creating the first worksheet
                $sheettitle = get_string('report', 'scorm');
                $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

                $colnum = 0;
                foreach ($headers as $item) {
                    $myxls->write(0, $colnum, $item, $formatbc);
                    $colnum++;
                }
                $rownum = 1;
            } 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('report', 'scorm');
                $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');

                $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");
                echo implode("\t", $headers)." \n";
            }

            if (!$download) {
                $sort = $table->get_sql_sort();
            } else {
                $sort = '';
            }
            // Fix some wired sorting
            if (empty($sort)) {
                $sort = ' ORDER BY uniqueid';
            } else {
                $sort = ' ORDER BY '.$sort;
            }

            if (!$download) {
                // Add extra limits due to initials bar
                list($twhere, $tparams) = $table->get_sql_where();
                if ($twhere) {
                    $where .= ' AND '.$twhere; //initial bar
                    $params = array_merge($params, $tparams);
                }

                if (!empty($countsql)) {
                    $count = $DB->get_record_sql($countsql,$params);
                    $totalinitials = $count->nbresults;
                    if ($twhere) {
                        $countsql .= ' AND '.$twhere;
                    }
                    $count = $DB->get_record_sql($countsql, $params);
                    $total  = $count->nbresults;
                }

                $table->pagesize($pagesize, $total);

                echo '<div class="quizattemptcounts">';
                if ( $count->nbresults == $count->nbattempts ) {
                    echo get_string('reportcountattempts', 'scorm', $count);
                } else if ( $count->nbattempts>0 ) {
                    echo get_string('reportcountallattempts', 'scorm', $count);
                } else {
                    echo $count->nbusers.' '.get_string('users');
                }
                echo '</div>';
            }

            // Fetch the attempts
            if (!$download) {
                $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
                $table->get_page_start(), $table->get_page_size());
                echo '<div id="scormtablecontainer">';
                if ($candelete) {
                    // Start form
                    $strreallydel  = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
                    echo '<form id="attemptsform" method="post" action="' . $PAGE->url->out(false) .
                         '" onsubmit="return confirm(\''.$strreallydel.'\');">';
                    echo '<input type="hidden" name="action" value="delete"/>';
                    echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
                    echo '<div style="display: none;">';
                    echo html_writer::input_hidden_params($PAGE->url);
                    echo '</div>';
                    echo '<div>';
                }
                $table->initialbars($totalinitials>20); // Build table rows
            } else {
                $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
            }
            if ($attempts) {
                foreach ($attempts as $scouser) {
                    $row = array();
                    if (!empty($scouser->attempt)) {
                        $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
                    } else {
                        $timetracks = '';
                    }
                    if (in_array('checkbox', $columns)) {
                        if ($candelete && !empty($timetracks->start)) {
                            $row[] = '<input type="checkbox" name="attemptid[]" value="'. $scouser->userid . ':' . $scouser->attempt . '" />';
                        } else if ($candelete) {
                            $row[] = '';
                        }
                    }
                    if (in_array('picture', $columns)) {
                        $user = (object)array(
                                    'id'=>$scouser->userid,
                                    'picture'=>$scouser->picture,
                                    'imagealt'=>$scouser->imagealt,
                                    'email'=>$scouser->email,
                                    'firstname'=>$scouser->firstname,
                                    'lastname'=>$scouser->lastname);
                        $row[] = $OUTPUT->user_picture($user, array('courseid'=>$course->id));
                    }
                    if (!$download) {
                        $row[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$scouser->userid.'&amp;course='.$course->id.'">'.fullname($scouser).'</a>';
                    } else {
                        $row[] = fullname($scouser);
                    }
                    foreach ($extrafields as $field) {
                        $row[] = s($scouser->{$field});
                    }
                    if (empty($timetracks->start)) {
                        $row[] = '-';
                        $row[] = '-';
                        $row[] = '-';
                        $row[] = '-';
                    } else {
                        if (!$download) {
                            $row[] = '<a href="userreport.php?a='.$scorm->id.'&amp;user='******'&amp;attempt='.$scouser->attempt.'">'.$scouser->attempt.'</a>';
                        } else {
                            $row[] = $scouser->attempt;
                        }
                        if ($download =='ODS' || $download =='Excel' ) {
                            $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
                        } else {
                            $row[] = userdate($timetracks->start);
                        }
                        if ($download =='ODS' || $download =='Excel' ) {
                            $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
                        } else {
                            $row[] = userdate($timetracks->finish);
                        }
                        $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
                    }
                    // print out all scores of attempt
                    foreach ($scoes as $sco) {
                        if ($sco->launch != '') {
                            if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
                                if ($trackdata->status == '') {
                                    $trackdata->status = 'notattempted';
                                }
                                $strstatus = get_string($trackdata->status, 'scorm');
                                // if raw score exists, print it
                                if ($trackdata->score_raw != '') {
                                    $score = $trackdata->score_raw;
                                    // add max score if it exists
                                    if ($scorm->version == 'SCORM_1.3') {
                                        $maxkey = 'cmi.score.max';
                                    } else {
                                        $maxkey = 'cmi.core.score.max';
                                    }
                                    if (isset($trackdata->$maxkey)) {
                                        $score .= '/'.$trackdata->$maxkey;
                                    }
                                // else print out status
                                } else {
                                    $score = $strstatus;
                                }
                                if (!$download) {
                                    $row[] = '<img src="'.$OUTPUT->pix_url($trackdata->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>
                                            <a href="userreport.php?b='.$sco->id.'&amp;user='******'&amp;attempt='.$scouser->attempt.
                                            '" title="'.get_string('details', 'scorm').'">'.$score.'</a>';
                                } else {
                                    $row[] = $score;
                                }
                                // interaction data
                                $i=0;
                                $element='cmi.interactions_'.$i.'.id';
                                while(isset($trackdata->$element)) {
                                    if ($displayoptions['qtext']) {
                                        $element='cmi.interactions_'.$i.'.id';
                                        if (isset($trackdata->$element)) {
                                            $row[] = s($trackdata->$element);
                                        } else {
                                            $row[] = '&nbsp;';
                                        }
                                    }
                                    if ($displayoptions['resp']) {
                                        $element='cmi.interactions_'.$i.'.student_response';
                                        if (isset($trackdata->$element)) {
                                            $row[] = s($trackdata->$element);
                                        } else {
                                            $row[] = '&nbsp;';
                                        }
                                    }
                                    if ($displayoptions['right']) {
                                        $j=0;
                                        $element = 'cmi.interactions_'.$i.'.correct_responses_'.$j.'.pattern';
                                        $rightans = '';
                                        if (isset($trackdata->$element)) {
                                            while(isset($trackdata->$element)) {
                                                if($j>0) {
                                                    $rightans .= ',';
                                                }
                                                $rightans .= s($trackdata->$element);
                                                $j++;
                                                $element = 'cmi.interactions_'.$i.'.correct_responses_'.$j.'.pattern';
                                            }
                                            $row[] = $rightans;
                                        } else {
                                            $row[] = '&nbsp;';
                                        }
                                    }
                                    $i++;
                                    $element = 'cmi.interactions_'.$i.'.id';
                                }
                            //---end of interaction data*/
                            } else {
                                // if we don't have track data, we haven't attempted yet
                                $strstatus = get_string('notattempted', 'scorm');
                                if (!$download) {
                                    $row[] = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>'.$strstatus;
                                } else {
                                    $row[] = $strstatus;
                                }
                            }
                        }
                    }

                    if (!$download) {
                        $table->add_data($row);
                    } else if ($download == 'Excel' or $download == 'ODS') {
                        $colnum = 0;
                        foreach ($row as $item) {
                            $myxls->write($rownum, $colnum, $item, $format);
                            $colnum++;
                        }
                        $rownum++;
                    } else if ($download == 'CSV') {
                        $text = implode("\t", $row);
                        echo $text." \n";
                    }
                }
                if (!$download) {
                    $table->finish_output();
                    if ($candelete) {
                        echo '<table id="commands">';
                        echo '<tr><td>';
                        echo '<a href="javascript:select_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
                             get_string('selectall', 'scorm').'</a> / ';
                        echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
                             get_string('selectnone', 'scorm').'</a> ';
                        echo '&nbsp;&nbsp;';
                        echo '<input type="submit" value="'.get_string('deleteselected', 'quiz_overview').'"/>';
                        echo '</td></tr></table>';
                        // Close form
                        echo '</div>';
                        echo '</form>';
                    }
                    echo '</div>';
                    if (!empty($attempts)) {
                        echo '<table class="boxaligncenter"><tr>';
                        echo '<td>';
                        echo $OUTPUT->single_button(new moodle_url($PAGE->url,
                                                                   array('download'=>'ODS') + $displayoptions),
                                                                   get_string('downloadods'));
                        echo "</td>\n";
                        echo '<td>';
                        echo $OUTPUT->single_button(new moodle_url($PAGE->url,
                                                                   array('download'=>'Excel') + $displayoptions),
                                                                   get_string('downloadexcel'));
                        echo "</td>\n";
                        echo '<td>';
                        echo $OUTPUT->single_button(new moodle_url($PAGE->url,
                                                                   array('download'=>'CSV') + $displayoptions),
                                                                   get_string('downloadtext'));
                        echo "</td>\n";
                        echo "<td>";
                        echo "</td>\n";
                        echo '</tr></table>';
                    }
                }
            } else {
                if ($candelete && !$download) {
                    echo '</div>';
                    echo '</form>';
                    $table->finish_output();
                }
                echo '</div>';
            }
            // Show preferences form irrespective of attempts are there to report or not
            if (!$download) {
                $mform->set_data(compact('detailedrep', 'pagesize', 'attemptsmode'));
                $mform->display();
            }
            if ($download == 'Excel' or $download == 'ODS') {
                $workbook->close();
                exit;
            } else if ($download == 'CSV') {
                exit;
            }
        } else {
            echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
        }
    }// function ends
 /**
  * Display the report.
  */
 public function display($game, $cm, $course)
 {
     global $CFG, $SESSION, $DB;
     // Define some strings.
     $strreallydel = addslashes(get_string('deleteattemptcheck', 'game'));
     $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, $game, $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('game_attempts', 'id', $attemptid))) {
                     delete_records('game_attempts', 'id', $attemptid);
                     delete_records('game_queries', 'attemptid', $attemptid);
                     // Search game_attempts for other instances by this user.
                     // If none, then delete record for this game, this user from game_grades.
                     // else recalculate best grade.
                     $userid = $todelete->userid;
                     if (!record_exists('game_attempts', 'userid', $userid, 'gameid', $game->id)) {
                         delete_records('game_grades', 'userid', $userid, 'gameid', $game->id);
                     } else {
                         game_save_best_score($game, $userid);
                     }
                 }
             }
             break;
     }
     // Print information on the number of existing attempts.
     if (!$download) {
         // Do not print notices when downloading.
         if ($attemptnum = count_records('game_attempts', 'gameid', $game->id)) {
             $a = new stdClass();
             $a->attemptnum = $attemptnum;
             $a->studentnum = count_records_select('game_attempts', "gameid = '{$game->id}' AND preview = '0'", 'COUNT(DISTINCT userid)');
             $a->studentstring = $course->students;
             notify(get_string('numattempts', 'game', $a));
         }
     }
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     // Find out current groups mode.
     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 {
             $currentgroup = get_and_set_current_group($course, $groupmode);
         }
     } else {
         $currentgroup = get_and_set_current_group($course, $groupmode);
     }
     // 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 = game_has_feedback($game->id) && $game->grade > 1.0E-7;
     if ($pagesize < 1) {
         $pagesize = 10;
     }
     // Now check if asked download of data.
     if ($download) {
         $filename = clean_filename("{$course->shortname} " . format_string($game->name, true));
         $sort = '';
     }
     // Define table columns.
     $tablecolumns = array('checkbox', 'picture', 'fullname', 'timestart', 'timefinish', 'duration');
     $tableheaders = array(null, '', get_string('fullname'), get_string('startedon', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
     if ($game->grade) {
         $tablecolumns[] = 'grade';
         $tableheaders[] = get_string('grade', 'game') . '/' . $game->grade;
     }
     if ($detailedmarks) {
         // We want to display marks for all questions.
         // Start by getting all questions.
         $questionlist = game_questions_in_game($game->questions);
         $questionids = explode(',', $questionlist);
         $sql = "SELECT q.*, i.score AS maxgrade, i.id AS instance" . "  FROM {question} q," . "       {game_queries} i" . " WHERE i.gameid = '{$game->id}' AND q.id = i.questionid" . "   AND q.id IN ({$questionlist})";
         if (!($questions = get_records_sql($sql))) {
             print_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[] = 'feedbacktext';
         $tableheaders[] = get_string('feedback', 'game');
     }
     if (!$download) {
         // Set up the table.
         $table = new flexible_table('mod-game-report-overview-report');
         $table->define_columns($tablecolumns);
         $table->define_headers($tableheaders);
         $table->define_baseurl($CFG->wwwroot . '/mod/game/report.php?mode=overview&amp;id=' . $cm->id . '&amp;noattempts=' . $noattempts . '&amp;detailedmarks=' . $detailedmarks . '&amp;pagesize=' . $pagesize);
         $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 == 'ODS') {
             require_once "{$CFG->libdir}/odslib.class.php";
             $filename .= ".ods";
             // Creating a workbook.
             $workbook = new MoodleODSWorkbook("-");
             // Sending HTTP headers.
             $workbook->send($filename);
             // Creating the first worksheet.
             $sheettitle = get_string('reportoverview', 'game');
             $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', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
             if ($game->grade) {
                 $headers[] = get_string('grade', 'game') . '/' . $game->grade;
             }
             if ($detailedmarks) {
                 foreach ($questionids as $id) {
                     $headers[] = '#' . $questions[$id]->number;
                 }
             }
             if ($hasfeedback) {
                 $headers[] = get_string('feedback', 'game');
             }
             $colnum = 0;
             foreach ($headers as $item) {
                 $myxls->write(0, $colnum, $item, $formatbc);
                 $colnum++;
             }
             $rownum = 1;
         } 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', 'game');
                 $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', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
                 if ($game->grade) {
                     $headers[] = get_string('grade', 'game') . '/' . $game->grade;
                 }
                 if ($detailedmarks) {
                     foreach ($questionids as $id) {
                         $headers[] = '#' . $questions[$id]->number;
                     }
                 }
                 if ($hasfeedback) {
                     $headers[] = get_string('feedback', 'game');
                 }
                 $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', 'game') . "\t" . get_string('timecompleted', 'game') . "\t" . get_string('attemptduration', 'game');
                     if ($game->grade) {
                         $headers .= "\t" . get_string('grade', 'game') . "/" . $game->grade;
                     }
                     if ($detailedmarks) {
                         foreach ($questionids as $id) {
                             $headers .= "\t#" . $questions[$id]->number;
                         }
                     }
                     if ($hasfeedback) {
                         $headers .= "\t" . get_string('feedback', 'game');
                     }
                     echo $headers . " \n";
                 }
             }
         }
     }
     $contextlists = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $course->id));
     // Construct the SQL.
     $select = 'SELECT qa.id,' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ' AS uniqueid, ' . 'qa.id as attemptuniqueid, qa.id AS attempt, u.id AS userid, u.firstname, u.lastname, u.picture, ' . 'qa.score, 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 {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . groups_members_join_sql() . 'JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
             $where = ' WHERE ra.contextid ' . $contextlists . ' AND ' . groups_members_where_sql($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 {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . groups_members_join_sql() . 'LEFT JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
                 $where = ' WHERE ra.contextid ' . $contextlists . ' AND ' . groups_members_where_sql($currentgroup);
                 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.
                 } else {
                     // We are including attempts, so exclude previews.
                     $where .= ' AND qa.preview = 0';
                 }
             } 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 {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . ' LEFT JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
                     $where = " WHERE ra.contextid {$contextlists}";
                     if (empty($noattempts)) {
                         // Show ONLY students with attempts.
                         $where .= ' AND qa.userid IS NOT NULL AND qa.preview = 0';
                     } else {
                         if ($noattempts == 1) {
                             // The noattempts = 1 means only no attempts,.
                             // So make the left join ask for only records where the right is null (no attempts).
                             // Show ONLY students without attempts.
                             $where .= ' AND qa.userid IS NULL';
                         } else {
                             if ($noattempts == 3) {
                                 // We want all attempts.
                                 $from = 'FROM {user} u JOIN {game_attempts} qa ON u.id = qa.userid ';
                                 $where = ' WHERE qa.gameid = ' . $game->id . ' AND qa.preview = 0';
                             }
                         }
                     }
                     // The noattempts = 2 means we want all students, with or without attempts.
                 }
             }
         }
         $countsql = 'SELECT COUNT(DISTINCT(' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ')) ' . $from . $where;
     } else {
         if (empty($noattempts)) {
             $from = 'FROM {user} u JOIN {game_attempts} qa ON u.id = qa.userid ';
             $where = ' WHERE qa.gameid = ' . $game->id . ' AND qa.preview = 0';
             $countsql = 'SELECT COUNT(DISTINCT(' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ')) ' . $from . $where;
         }
     }
     if (!$download) {
         // Add extra limits due to initials bar.
         if ($table->get_sql_where()) {
             $where .= ' AND ' . $table->get_sql_where();
         }
         // Count the records NOW, before funky question grade sorting messes up $from.
         if (!empty($countsql)) {
             $totalinitials = count_records_sql($countsql);
             if ($table->get_sql_where()) {
                 $countsql .= ' AND ' . $table->get_sql_where();
             }
             $total = count_records_sql($countsql);
         }
         // Add extra limits due to sorting by question grade.
         if ($sort = $table->get_sql_sort()) {
             $sortparts = explode(',', $sort);
             $newsort = array();
             $questionsort = false;
             foreach ($sortparts as $sortpart) {
                 $sortpart = trim($sortpart);
                 if (substr($sortpart, 0, 1) == '$') {
                     if (!$questionsort) {
                         $qid = intval(substr($sortpart, 1));
                         $select .= ', grade ';
                         $from .= ' LEFT JOIN {question_sessions} qns ON qns.attemptid = qa.id ' . 'LEFT JOIN {question_states} qs ON qs.id = qns.newgraded ';
                         $where .= ' AND (' . sql_isnull('qns.questionid') . ' OR qns.questionid = ' . $qid . ')';
                         $newsort[] = 'grade ' . (strpos($sortpart, 'ASC') ? 'ASC' : 'DESC');
                         $questionsort = true;
                     }
                 } else {
                     $newsort[] = $sortpart;
                 }
             }
             // Reconstruct the sort string.
             $sort = ' ORDER BY ' . implode(', ', $newsort);
         }
         // Fix some wired sorting.
         if (empty($sort)) {
             $sort = ' ORDER BY qa.id';
         }
         $table->pagesize($pagesize, $total);
     }
     // If there is feedback, include it in the query.
     if ($hasfeedback) {
         $select .= ', qf.feedbacktext ';
         $from .= " JOIN {game_feedback} qf ON " . "qf.gameid = {$game->id} AND qf.mingrade <= qa.score * {$game->grade}  AND qa.score * {$game->grade} < qf.maxgrade";
     }
     // Fetch the attempts.
     if (!empty($from)) {
         // If we're in the site course and displaying no attempts, it makes no sense to do the query.
         if (!$download) {
             $attempts = get_records_sql($select . $from . $where . $sort, $table->get_page_start(), $table->get_page_size());
         } else {
             $attempts = get_records_sql($select . $from . $where . $sort);
         }
     } else {
         $attempts = array();
     }
     // Build table rows.
     if (!$download) {
         $table->initialbars($totalinitials > 20);
     }
     if (!empty($attempts) || !empty($noattempts)) {
         if ($attempts) {
             foreach ($attempts as $attempt) {
                 $picture = print_user_picture($attempt->userid, $course->id, $attempt->picture, false, true);
                 /* Uncomment the commented lines below if you are choosing to show unenrolled users and
                  * have uncommented the corresponding lines earlier in this script
                  * if (in_array($attempt->userid, $unenrolledusers)) {
                  *    $userlink = '<a class="dimmed" href="'.$CFG->wwwroot.
                  *       '/user/view.php?id='.$attempt->userid.'&amp;course='.$course->id.'">'.fullname($attempt).'</a>';
                  *}
                  *else {
                  *   $userlink = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
                  *      $attempt->userid.'&amp;course='.$course->id.'">'.fullname($attempt).'</a>';
                  *}
                  */
                 if (!$download) {
                     $row = array('<input type="checkbox" name="attemptid[]" value="' . $attempt->attempt . '" />', $picture, $userlink, empty($attempt->attempt) ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . userdate($attempt->timestart, $strtimeformat) . '</a>', empty($attempt->timefinish) ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . userdate($attempt->timefinish, $strtimeformat) . '</a>', empty($attempt->attempt) ? '-' : (empty($attempt->timefinish) ? get_string('unfinished', 'game') : format_time($attempt->duration)));
                 } else {
                     $row = array(fullname($attempt), empty($attempt->attempt) ? '-' : userdate($attempt->timestart, $strtimeformat), empty($attempt->timefinish) ? '-' : userdate($attempt->timefinish, $strtimeformat), empty($attempt->attempt) ? '-' : (empty($attempt->timefinish) ? get_string('unfinished', 'game') : format_time($attempt->duration)));
                 }
                 if ($game->grade) {
                     if (!$download) {
                         $row[] = $attempt->score === null ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . round($attempt->score * $game->grade, $game->decimalpoints) . '</a>';
                     } else {
                         $row[] = $attempt->score === null ? '-' : round($attempt->score * $game->grade, $game->decimalpoints);
                     }
                 }
                 if ($detailedmarks) {
                     if (empty($attempt->attempt)) {
                         foreach ($questionids as $questionid) {
                             $row[] = '-';
                         }
                     } else {
                         foreach ($questionids as $questionid) {
                             if ($gradedstateid = get_field('question_sessions', 'newgraded', 'attemptid', $attempt->attemptuniqueid, 'questionid', $questionid)) {
                                 $grade = round(get_field('question_states', 'grade', 'id', $gradedstateid), $game->decimalpoints);
                             } else {
                                 $grade = '--';
                             }
                             if (!$download) {
                                 $row[] = link_to_popup_window('/mod/game/reviewquestion.php?state=' . $gradedstateid . '&amp;number=' . $questions[$questionid]->number, 'reviewquestion', $grade, 450, 650, $strreviewquestion, 'none', true);
                             } else {
                                 $row[] = $grade;
                             }
                         }
                     }
                 }
                 if ($hasfeedback) {
                     if ($attempt->timefinish) {
                         $row[] = $attempt->feedbacktext;
                     } else {
                         $row[] = '-';
                     }
                 }
                 if (!$download) {
                     $table->add_data($row);
                 } else {
                     if ($download == 'Excel' or $download == 'ODS') {
                         $colnum = 0;
                         foreach ($row as $item) {
                             $myxls->write($rownum, $colnum, $item, $format);
                             $colnum++;
                         }
                         $rownum++;
                     } else {
                         if ($download == 'CSV') {
                             $text = implode("\t", $row);
                             echo $text . " \n";
                         }
                     }
                 }
             }
         }
         if (!$download) {
             // Start form.
             echo '<div id="tablecontainer">';
             echo '<form id="attemptsform" method="post" action="report.php" ' . 'onsubmit="var menu = document.getElementById(\'menuaction\'); ' . 'return (menu.options[menu.selectedIndex].value == \'delete\' ? confirm(\'' . $strreallydel . '\') : true);">';
             echo '<div>';
             echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
             echo '<input type="hidden" name="mode" value="overview" />';
             // Print table.
             $table->print_html();
             // Print "Select all" etc..
             if (!empty($attempts)) {
                 echo '<table id="commands">';
                 echo '<tr><td>';
                 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectall', 'game') . '</a> / ';
                 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectnone', 'game') . '</a> ';
                 echo '&nbsp;&nbsp;';
                 $options = array('delete' => get_string('delete'));
                 echo choose_from_menu($options, 'action', '', get_string('withselected', 'game'), 'if(this.selectedIndex > 0) submitFormById(\'attemptsform\');', '', true);
                 echo '<noscript id="noscriptmenuaction" style="display: inline;"><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></tr></table>';
             }
             // Close form.
             echo '</div>';
             echo '</form></div>';
             if (!empty($attempts)) {
                 echo '<table class="boxaligncenter"><tr>';
                 $options = array();
                 $options["id"] = "{$cm->id}";
                 $options["q"] = "{$game->id}";
                 $options["mode"] = "overview";
                 $options['sesskey'] = sesskey();
                 $options["noheader"] = "yes";
                 $options['noattempts'] = $noattempts;
                 $options['detailedmarks'] = $detailedmarks;
                 echo '<td>';
                 $options["download"] = "ODS";
                 print_single_button("report.php", $options, get_string("downloadods", 'game'));
                 echo "</td>\n";
                 echo '<td>';
                 $options["download"] = "Excel";
                 print_single_button("report.php", $options, get_string("downloadexcel"));
                 echo "</td>\n";
                 echo '<td>';
                 $options["download"] = "CSV";
                 print_single_button('report.php', $options, get_string("downloadtext"));
                 echo "</td>\n";
                 echo "<td>";
                 helpbutton('overviewdownload', get_string('overviewdownload', 'quiz'), 'game');
                 echo "</td>\n";
                 echo '</tr></table>';
             }
         } else {
             if ($download == 'Excel' or $download == 'ODS') {
                 $workbook->close();
                 exit;
             } else {
                 if ($download == 'CSV') {
                     exit;
                 }
             }
         }
     } else {
         if (!$download) {
             $table->print_html();
         }
     }
     // Print display options.
     echo '<div class="controls">';
     echo '<form id="options" action="report.php" method="get">';
     echo '<div>';
     echo '<p>' . get_string('displayoptions', 'game') . ': </p>';
     echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
     echo '<input type="hidden" name="q" value="' . $game->id . '" />';
     echo '<input type="hidden" name="mode" value="overview" />';
     echo '<input type="hidden" name="noattempts" value="0" />';
     echo '<input type="hidden" name="detailedmarks" value="0" />';
     echo '<table id="overview-options" class="boxaligncenter">';
     echo '<tr align="left">';
     echo '<td><label for="pagesize">' . get_string('pagesize', 'game') . '</label></td>';
     echo '<td><input type="text" id="pagesize" name="pagesize" size="3" value="' . $pagesize . '" /></td>';
     echo '</tr>';
     echo '<tr align="left">';
     echo '<td colspan="2">';
     $options = array(0 => get_string('attemptsonly', 'game', $course->students));
     if ($course->id != SITEID) {
         $options[1] = get_string('noattemptsonly', 'game', $course->students);
         $options[2] = get_string('allstudents', 'game', $course->students);
         $options[3] = get_string('allattempts', 'game');
     }
     choose_from_menu($options, 'noattempts', $noattempts, '');
     echo '</td></tr>';
     echo '<tr align="left">';
     echo '<td colspan="2"><input type="checkbox" id="checkdetailedmarks" name="detailedmarks" ' . ($detailedmarks ? 'checked="checked" ' : '') . 'value="1" /> <label for="checkdetailedmarks">' . get_string('showdetailedmarks', 'game') . '</label> ';
     echo '</td></tr>';
     echo '<tr><td colspan="2" align="center">';
     echo '<input type="submit" value="' . get_string('go') . '" />';
     echo '</td></tr></table>';
     echo '</div>';
     echo '</form>';
     echo '</div>';
     echo "\n";
     return true;
 }
 /**
  * To be implemented by child classes
  */
 function print_grades()
 {
     global $CFG;
     require_once $CFG->dirroot . '/lib/odslib.class.php';
     $export_tracking = $this->track_exports();
     $strgrades = get_string('grades');
     $shortname = format_string($this->course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $this->course->id)));
     /// Calculate file name
     $downloadfilename = clean_filename("{$shortname} {$strgrades}.ods");
     /// Creating a workbook
     $workbook = new MoodleODSWorkbook("-");
     /// Sending HTTP headers
     $workbook->send($downloadfilename);
     /// Adding the worksheet
     $myxls = $workbook->add_worksheet($strgrades);
     /// Print names of all the fields
     $myxls->write_string(0, 0, get_string("firstname"));
     $myxls->write_string(0, 1, get_string("lastname"));
     $myxls->write_string(0, 2, get_string("idnumber"));
     $myxls->write_string(0, 3, get_string("institution"));
     $myxls->write_string(0, 4, get_string("department"));
     $myxls->write_string(0, 5, get_string("email"));
     $pos = 6;
     foreach ($this->columns as $grade_item) {
         $myxls->write_string(0, $pos++, $this->format_column_name($grade_item));
         /// add a column_feedback column
         if ($this->export_feedback) {
             $myxls->write_string(0, $pos++, $this->format_column_name($grade_item, true));
         }
     }
     /// Print all the lines of data.
     $i = 0;
     $geub = new grade_export_update_buffer();
     $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
     $gui->require_active_enrolment($this->onlyactive);
     $gui->init();
     while ($userdata = $gui->next_user()) {
         $i++;
         $user = $userdata->user;
         $myxls->write_string($i, 0, $user->firstname);
         $myxls->write_string($i, 1, $user->lastname);
         $myxls->write_string($i, 2, $user->idnumber);
         $myxls->write_string($i, 3, $user->institution);
         $myxls->write_string($i, 4, $user->department);
         $myxls->write_string($i, 5, $user->email);
         $j = 6;
         foreach ($userdata->grades as $itemid => $grade) {
             if ($export_tracking) {
                 $status = $geub->track($grade);
             }
             $gradestr = $this->format_grade($grade);
             if (is_numeric($gradestr)) {
                 $myxls->write_number($i, $j++, $gradestr);
             } else {
                 $myxls->write_string($i, $j++, $gradestr);
             }
             // writing feedback if requested
             if ($this->export_feedback) {
                 $myxls->write_string($i, $j++, $this->format_feedback($userdata->feedbacks[$itemid]));
             }
         }
     }
     $gui->close();
     $geub->close();
     /// Close the workbook
     $workbook->close();
     exit;
 }
Example #11
0
* Excel 2007 borders appear too thick in LibreOffice
* Excel 2007 can not be opened in Calligra Suite
';
    echo markdown_to_html($notes);
    echo $OUTPUT->box_end();
    echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('type' => 'excel2007')), 'Test Excel 2007 format');
    echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('type' => 'ods')), 'Test ODS format');
    echo $OUTPUT->footer();
    die;
}
if ($type === 'excel2007') {
    $workbook = new MoodleExcelWorkbook('moodletest.xlsx', 'Excel2007');
} else {
    if ($type === 'ods') {
        $workbook = new MoodleODSWorkbook('moodletest.ods');
    }
}
$worksheet = array();
$worksheet = $workbook->add_worksheet('Supported');
$worksheet->hide_screen_gridlines();
$worksheet->write_string(0, 0, 'Moodle worksheet export test', $workbook->add_format(array('color' => 'red', 'size' => 20, 'bold' => 1, 'italic' => 1)));
$worksheet->set_row(0, 25);
$worksheet->write(1, 0, 'Moodle release: ' . $CFG->release, $workbook->add_format(array('size' => 8, 'italic' => 1)));
$worksheet->set_column(0, 0, 20);
$worksheet->set_column(1, 1, 30);
$worksheet->set_column(2, 2, 5);
$worksheet->set_column(3, 3, 30);
$worksheet->set_column(4, 4, 20);
$miniheading = $workbook->add_format(array('size' => 15, 'bold' => 1, 'italic' => 1, 'underline' => 1));
$worksheet->write(2, 0, 'Cell types', $miniheading);
Example #12
0
function grade_download($download, $id)
{
    global $CFG;
    require_login();
    if (!($course = get_record("course", "id", $id))) {
        error("Course ID was incorrect");
    }
    require_capability('moodle/course:viewcoursegrades', get_context_instance(CONTEXT_COURSE, $id));
    $strgrades = get_string("grades");
    $strgrade = get_string("grade");
    $strmax = get_string("maximumshort");
    $stractivityreport = get_string("activityreport");
    /// Check to see if groups are being used in this course
    $currentgroup = get_current_group($course->id);
    if (($currentgroup = get_current_group($course->id)) && groupmode($course) != 0) {
        $students = get_group_students($currentgroup, "u.lastname ASC");
    } else {
        $students = grade_get_course_students($course->id);
    }
    if (!empty($students)) {
        foreach ($students as $student) {
            $grades[$student->id] = array();
            // Collect all grades in this array
            $gradeshtml[$student->id] = array();
            // Collect all grades html formatted in this array
            $totals[$student->id] = array();
            // Collect all totals in this array
        }
    }
    $columns = array();
    // Accumulate column names in this array.
    $columnhtml = array();
    // Accumulate column html in this array.
    /// Collect modules data
    get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
    /// Search through all the modules, pulling out grade data
    $sections = get_all_sections($course->id);
    // Sort everything the same as the course
    for ($i = 0; $i <= $course->numsections; $i++) {
        if (isset($sections[$i])) {
            // should always be true
            $section = $sections[$i];
            if ($section->sequence) {
                $sectionmods = explode(",", $section->sequence);
                foreach ($sectionmods as $sectionmod) {
                    $mod = $mods[$sectionmod];
                    $instance = get_record("{$mod->modname}", "id", "{$mod->instance}");
                    $libfile = "{$CFG->dirroot}/mod/{$mod->modname}/lib.php";
                    if (file_exists($libfile)) {
                        require_once $libfile;
                        $gradefunction = $mod->modname . "_grades";
                        if (function_exists($gradefunction)) {
                            // Skip modules without grade function
                            if ($modgrades = $gradefunction($mod->instance)) {
                                if (!empty($modgrades->maxgrade)) {
                                    if ($mod->visible) {
                                        $maxgrade = "{$strmax}: {$modgrades->maxgrade}";
                                    } else {
                                        $maxgrade = "{$strmax}: {$modgrades->maxgrade}";
                                    }
                                } else {
                                    $maxgrade = "";
                                }
                                $columns[] = "{$mod->modfullname}: " . format_string($instance->name, true) . " - {$maxgrade}";
                                if (!empty($students)) {
                                    foreach ($students as $student) {
                                        if (!empty($modgrades->grades[$student->id])) {
                                            $grades[$student->id][] = $currentstudentgrade = $modgrades->grades[$student->id];
                                        } else {
                                            $grades[$student->id][] = $currentstudentgrade = "";
                                            $gradeshtml[$student->id][] = "";
                                        }
                                        if (!empty($modgrades->maxgrade)) {
                                            $totals[$student->id] = (double) $totals[$student->id] + (double) $currentstudentgrade;
                                        } else {
                                            $totals[$student->id] = (double) $totals[$student->id] + 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // a new Moodle nesting record? ;-)
    /// OK, we have all the data, now present it to the user
    /// OK, we have all the data, now present it to the user
    if ($download == "ods" and confirm_sesskey()) {
        require_once "../lib/odslib.class.php";
        /// Calculate file name
        $downloadfilename = clean_filename("{$course->shortname} {$strgrades}.ods");
        /// Creating a workbook
        $workbook = new MoodleODSWorkbook("-");
        /// Sending HTTP headers
        $workbook->send($downloadfilename);
        /// Adding the worksheet
        $myxls =& $workbook->add_worksheet($strgrades);
        /// Print names of all the fields
        $myxls->write_string(0, 0, get_string("firstname"));
        $myxls->write_string(0, 1, get_string("lastname"));
        $myxls->write_string(0, 2, get_string("idnumber"));
        $myxls->write_string(0, 3, get_string("institution"));
        $myxls->write_string(0, 4, get_string("department"));
        $myxls->write_string(0, 5, get_string("email"));
        $pos = 6;
        foreach ($columns as $column) {
            $myxls->write_string(0, $pos++, strip_tags($column));
        }
        $myxls->write_string(0, $pos, get_string("total"));
        /// Print all the lines of data.
        $i = 0;
        if (!empty($grades)) {
            foreach ($grades as $studentid => $studentgrades) {
                $i++;
                $student = $students[$studentid];
                if (empty($totals[$student->id])) {
                    $totals[$student->id] = '';
                }
                $myxls->write_string($i, 0, $student->firstname);
                $myxls->write_string($i, 1, $student->lastname);
                $myxls->write_string($i, 2, $student->idnumber);
                $myxls->write_string($i, 3, $student->institution);
                $myxls->write_string($i, 4, $student->department);
                $myxls->write_string($i, 5, $student->email);
                $j = 6;
                foreach ($studentgrades as $grade) {
                    if (is_numeric($grade)) {
                        $myxls->write_number($i, $j++, strip_tags($grade));
                    } else {
                        $myxls->write_string($i, $j++, strip_tags($grade));
                    }
                }
                $myxls->write_number($i, $j, $totals[$student->id]);
            }
        }
        /// Close the workbook
        $workbook->close();
        exit;
    } else {
        if ($download == "xls" and confirm_sesskey()) {
            require_once "../lib/excellib.class.php";
            /// Calculate file name
            $downloadfilename = clean_filename("{$course->shortname} {$strgrades}.xls");
            /// Creating a workbook
            $workbook = new MoodleExcelWorkbook("-");
            /// Sending HTTP headers
            $workbook->send($downloadfilename);
            /// Adding the worksheet
            $myxls =& $workbook->add_worksheet($strgrades);
            /// Print names of all the fields
            $myxls->write_string(0, 0, get_string("firstname"));
            $myxls->write_string(0, 1, get_string("lastname"));
            $myxls->write_string(0, 2, get_string("idnumber"));
            $myxls->write_string(0, 3, get_string("institution"));
            $myxls->write_string(0, 4, get_string("department"));
            $myxls->write_string(0, 5, get_string("email"));
            $pos = 6;
            foreach ($columns as $column) {
                $myxls->write_string(0, $pos++, strip_tags($column));
            }
            $myxls->write_string(0, $pos, get_string("total"));
            /// Print all the lines of data.
            $i = 0;
            if (!empty($grades)) {
                foreach ($grades as $studentid => $studentgrades) {
                    $i++;
                    $student = $students[$studentid];
                    if (empty($totals[$student->id])) {
                        $totals[$student->id] = '';
                    }
                    $myxls->write_string($i, 0, $student->firstname);
                    $myxls->write_string($i, 1, $student->lastname);
                    $myxls->write_string($i, 2, $student->idnumber);
                    $myxls->write_string($i, 3, $student->institution);
                    $myxls->write_string($i, 4, $student->department);
                    $myxls->write_string($i, 5, $student->email);
                    $j = 6;
                    foreach ($studentgrades as $grade) {
                        if (is_numeric($grade)) {
                            $myxls->write_number($i, $j++, strip_tags($grade));
                        } else {
                            $myxls->write_string($i, $j++, strip_tags($grade));
                        }
                    }
                    $myxls->write_number($i, $j, $totals[$student->id]);
                }
            }
            /// Close the workbook
            $workbook->close();
            exit;
        } else {
            if ($download == "txt" and confirm_sesskey()) {
                /// Print header to force download
                header("Content-Type: application/download\n");
                $downloadfilename = clean_filename("{$course->shortname} {$strgrades}");
                header("Content-Disposition: attachment; filename=\"{$downloadfilename}.txt\"");
                /// Print names of all the fields
                echo get_string("firstname") . "\t" . get_string("lastname") . "\t" . get_string("idnumber") . "\t" . get_string("institution") . "\t" . get_string("department") . "\t" . get_string("email");
                foreach ($columns as $column) {
                    $column = strip_tags($column);
                    echo "\t{$column}";
                }
                echo "\t" . get_string("total") . "\n";
                /// Print all the lines of data.
                foreach ($grades as $studentid => $studentgrades) {
                    $student = $students[$studentid];
                    if (empty($totals[$student->id])) {
                        $totals[$student->id] = '';
                    }
                    echo "{$student->firstname}\t{$student->lastname}\t{$student->idnumber}\t{$student->institution}\t{$student->department}\t{$student->email}";
                    foreach ($studentgrades as $grade) {
                        $grade = strip_tags($grade);
                        echo "\t{$grade}";
                    }
                    echo "\t" . $totals[$student->id];
                    echo "\n";
                }
                exit;
            } else {
                if ($download == '' and confirm_sesskey()) {
                    error("No file type specified");
                    exit;
                }
            }
        }
    }
}
        $cm = get_coursemodule_from_instance('scormfull', $scormfull->id, $course->id, false, MUST_EXIST);
    } else {
        error('You must specify a course_module ID or an scormfull ID');
    }
}
$quiz = $DB->get_record('quiz', array("id" => $scormfull->quid), '*', MUST_EXIST);
require_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!has_capability('mod/scormfull:manage', $context)) {
    redirect("{$CFG->wwwroot}/mod/scormfull/user.php?id={$id}");
}
$tt = getdate(time());
$today = mktime(0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
$filename = 'scormfull' . userdate(time(), get_string('backupnameformat'), 99, false);
$filename .= '.ods';
$workbook = new MoodleODSWorkbook('-');
$workbook->send($filename);
$worksheet = array();
$sheettitle = 'scormfull';
$worksheet =& $workbook->add_worksheet($sheettitle);
$struen_name = get_string('struen_name', 'scormfull');
$strthreshold_boo = get_string('threshold_boo', 'scormfull');
$Thresholdvalue = get_string('Thresholdvalue', 'scormfull');
$scrom_name = get_string('scrom_name', 'scormfull');
$starnopass = get_string('starnopass', 'scormfull');
$connected_exam = get_string('connected_exam', 'scormfull');
$strsetvalue = get_string('strsetvalue', 'scormfull');
$cssting = get_string('curriculum_standards_setting', 'scormfull');
$hours_of_the_event = get_string('hours_of_the_event', 'scormfull');
$through_standard_assessment = get_string('through_standard_assessment', 'scormfull');
$scorm_quiz_score = get_string('scorm_quiz_score', 'scormfull');
function print_coursereport_ods($coursereport_ods)
{
    global $CFG;
    require_once "{$CFG->libdir}/odslib.class.php";
    //release coursereport ods data
    $courseID = $coursereport_ods->courseID;
    $courseName = $coursereport_ods->courseName;
    $categoryName = $coursereport_ods->categoryName;
    $userIDDataArray = $coursereport_ods->userIDDataArray;
    $actionIDNameArray = $coursereport_ods->actionIDNameArray;
    $courseUserArray = $coursereport_ods->courseUserArray;
    $userPassArray = $coursereport_ods->userPassArray;
    $tt = getdate(time());
    $today = mktime(0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
    $filename = 'course_reports_' . userdate(time(), get_string('backupnameformat', 'langconfig'), 99, false);
    $filename .= '.ods';
    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    // Creating worksheets
    $sheettitle = 'course_report';
    //紀錄1-1
    $worksheet =& $workbook->add_worksheet($sheettitle);
    $worksheet->set_column(1, 1, 60);
    $worksheet->write_string(0, 0, $categoryName);
    $worksheet->write_string(1, 0, $courseName);
    $col = 0;
    $row = 4;
    $headerArray = processCourseReportHeader($courseUserArray, $actionIDNameArray);
    foreach ($headerArray as $item) {
        $worksheet->write($row - 1, $col, $item, '');
        $col++;
    }
    $myxls =& $worksheet;
    foreach ($courseUserArray as $userID => $actionInfo) {
        $col = 0;
        $myxls->write_string($row, $col, $userIDDataArray[$userID]['name']);
        $col++;
        $myxls->write_string($row, $col, $userIDDataArray[$userID]['description']);
        $col++;
        $myxls->write_string($row, $col, $userIDDataArray[$userID]['email']);
        $col++;
        foreach ($actionInfo as $actionID => $actionContent) {
            if ($actionContent['timeEnable']) {
                $myxls->write_string($row, $col, $actionContent['time']);
                $col++;
            }
            if ($actionContent['scoreEnable']) {
                $myxls->write_string($row, $col, $actionContent['score']);
                $col++;
            }
            if ($actionContent['timePass'] and $actionContent['scorePass']) {
                $myxls->write_string($row, $col, '通過');
                $col++;
            } else {
                $myxls->write_string($row, $col, '不通過');
                $col++;
            }
        }
        $myxls->write_string($row, $col, $userPassArray[$userID] ? '通過' : '不通過');
        $col++;
        $row++;
    }
    $workbook->close();
    return true;
}
Example #15
0
 /**
  * To be implemented by child classes
  */
 function print_grades()
 {
     global $CFG;
     require_once $CFG->dirroot . '/lib/odslib.class.php';
     $export_tracking = $this->track_exports();
     $strgrades = get_string('grades');
     $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id)));
     // Calculate file name
     $downloadfilename = clean_filename("{$shortname} {$strgrades}.ods");
     // Creating a workbook
     $workbook = new MoodleODSWorkbook("-");
     // Sending HTTP headers
     $workbook->send($downloadfilename);
     // Adding the worksheet
     $myxls = $workbook->add_worksheet($strgrades);
     // Print names of all the fields.
     $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
     foreach ($profilefields as $id => $field) {
         $myxls->write_string(0, $id, $field->fullname);
     }
     $pos = count($profilefields);
     if (!$this->onlyactive) {
         $myxls->write_string(0, $pos++, get_string("suspended"));
     }
     foreach ($this->columns as $grade_item) {
         $myxls->write_string(0, $pos++, $this->format_column_name($grade_item));
         // Add a column_feedback column.
         if ($this->export_feedback) {
             $myxls->write_string(0, $pos++, $this->format_column_name($grade_item, true));
         }
     }
     // Print all the lines of data.
     $i = 0;
     $geub = new grade_export_update_buffer();
     $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
     $gui->require_active_enrolment($this->onlyactive);
     $gui->allow_user_custom_fields($this->usercustomfields);
     $gui->init();
     while ($userdata = $gui->next_user()) {
         $i++;
         $user = $userdata->user;
         foreach ($profilefields as $id => $field) {
             $fieldvalue = grade_helper::get_user_field_value($user, $field);
             $myxls->write_string($i, $id, $fieldvalue);
         }
         $j = count($profilefields);
         if (!$this->onlyactive) {
             $issuspended = $user->suspendedenrolment ? get_string('yes') : '';
             $myxls->write_string($i, $j++, $issuspended);
         }
         foreach ($userdata->grades as $itemid => $grade) {
             if ($export_tracking) {
                 $status = $geub->track($grade);
             }
             $gradestr = $this->format_grade($grade);
             if (is_numeric($gradestr)) {
                 $myxls->write_number($i, $j++, $gradestr);
             } else {
                 $myxls->write_string($i, $j++, $gradestr);
             }
             // writing feedback if requested
             if ($this->export_feedback) {
                 $myxls->write_string($i, $j++, $this->format_feedback($userdata->feedbacks[$itemid]));
             }
         }
     }
     $gui->close();
     $geub->close();
     // Close the workbook.
     $workbook->close();
     exit;
 }
Example #16
0
 /**
  * displays the full report
  * @param \stdClass $scorm full SCORM object
  * @param \stdClass $cm - full course_module object
  * @param \stdClass $course - full course object
  * @param string $download - type of download being requested
  */
 public function display($scorm, $cm, $course, $download)
 {
     global $CFG, $DB, $OUTPUT, $PAGE;
     $contextmodule = \context_module::instance($cm->id);
     $action = optional_param('action', '', PARAM_ALPHA);
     $attemptids = optional_param_array('attemptid', array(), PARAM_RAW);
     $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_ALL_STUDENTS, PARAM_INT);
     $PAGE->set_url(new \moodle_url($PAGE->url, array('attemptsmode' => $attemptsmode)));
     if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) {
         if (scorm_delete_responses($attemptids, $scorm)) {
             // Delete responses.
             echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess');
         }
     }
     // Find out current groups mode.
     $currentgroup = groups_get_activity_group($cm, true);
     // Detailed report.
     $mform = new \mod_scorm_report_objectives_settings($PAGE->url, compact('currentgroup'));
     if ($fromform = $mform->get_data()) {
         $pagesize = $fromform->pagesize;
         $showobjectivescore = $fromform->objectivescore;
         set_user_preference('scorm_report_pagesize', $pagesize);
         set_user_preference('scorm_report_objectives_score', $showobjectivescore);
     } else {
         $pagesize = get_user_preferences('scorm_report_pagesize', 0);
         $showobjectivescore = get_user_preferences('scorm_report_objectives_score', 0);
     }
     if ($pagesize < 1) {
         $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
     }
     // Select group menu.
     $displayoptions = array();
     $displayoptions['attemptsmode'] = $attemptsmode;
     $displayoptions['objectivescore'] = $showobjectivescore;
     $mform->set_data($displayoptions + array('pagesize' => $pagesize));
     if ($groupmode = groups_get_activity_groupmode($cm)) {
         // Groups are being used.
         if (!$download) {
             groups_print_activity_menu($cm, new \moodle_url($PAGE->url, $displayoptions));
         }
     }
     $formattextoptions = array('context' => \context_course::instance($course->id));
     // We only want to show the checkbox to delete attempts
     // if the user has permissions and if the report mode is showing attempts.
     $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule) && $attemptsmode != SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO;
     // Select the students.
     $nostudents = false;
     if (empty($currentgroup)) {
         // All users who can attempt scoes.
         if (!($students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', 'u.id', '', '', '', '', '', false))) {
             echo $OUTPUT->notification(get_string('nostudentsyet'));
             $nostudents = true;
             $allowedlist = '';
         } else {
             $allowedlist = array_keys($students);
         }
         unset($students);
     } else {
         // All users who can attempt scoes and who are in the currently selected group.
         $groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', 'u.id', '', '', '', $currentgroup, '', false);
         if (!$groupstudents) {
             echo $OUTPUT->notification(get_string('nostudentsingroup'));
             $nostudents = true;
             $groupstudents = array();
         }
         $allowedlist = array_keys($groupstudents);
         unset($groupstudents);
     }
     if (!$nostudents) {
         // Now check if asked download of data.
         $coursecontext = \context_course::instance($course->id);
         if ($download) {
             $filename = clean_filename("{$course->shortname} " . format_string($scorm->name, true, $formattextoptions));
         }
         // Define table columns.
         $columns = array();
         $headers = array();
         if (!$download && $candelete) {
             $columns[] = 'checkbox';
             $headers[] = null;
         }
         if (!$download && $CFG->grade_report_showuserimage) {
             $columns[] = 'picture';
             $headers[] = '';
         }
         $columns[] = 'fullname';
         $headers[] = get_string('name');
         $extrafields = get_extra_user_fields($coursecontext);
         foreach ($extrafields as $field) {
             $columns[] = $field;
             $headers[] = get_user_field_name($field);
         }
         $columns[] = 'attempt';
         $headers[] = get_string('attempt', 'scorm');
         $columns[] = 'start';
         $headers[] = get_string('started', 'scorm');
         $columns[] = 'finish';
         $headers[] = get_string('last', 'scorm');
         $columns[] = 'score';
         $headers[] = get_string('score', 'scorm');
         $scoes = $DB->get_records('scorm_scoes', array("scorm" => $scorm->id), 'sortorder, id');
         foreach ($scoes as $sco) {
             if ($sco->launch != '') {
                 $columns[] = 'scograde' . $sco->id;
                 $headers[] = format_string($sco->title, '', $formattextoptions);
             }
         }
         $params = array();
         list($usql, $params) = $DB->get_in_or_equal($allowedlist, SQL_PARAMS_NAMED);
         // Construct the SQL.
         $select = 'SELECT DISTINCT ' . $DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)') . ' AS uniqueid, ';
         $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' . \user_picture::fields('u', array('idnumber'), 'userid') . get_extra_user_fields_sql($coursecontext, 'u', '', array('email', 'idnumber')) . ' ';
         // This part is the same for all cases - join users and scorm_scoes_track tables.
         $from = 'FROM {user} u ';
         $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = ' . $scorm->id;
         switch ($attemptsmode) {
             case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
                 // Show only students with attempts.
                 $where = ' WHERE u.id ' . $usql . ' AND st.userid IS NOT NULL';
                 break;
             case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
                 // Show only students without attempts.
                 $where = ' WHERE u.id ' . $usql . ' AND st.userid IS NULL';
                 break;
             case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
                 // Show all students with or without attempts.
                 $where = ' WHERE u.id ' . $usql . ' AND (st.userid IS NOT NULL OR st.userid IS NULL)';
                 break;
         }
         $countsql = 'SELECT COUNT(DISTINCT(' . $DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)') . ')) AS nbresults, ';
         $countsql .= 'COUNT(DISTINCT(' . $DB->sql_concat('u.id', '\'#\'', 'st.attempt') . ')) AS nbattempts, ';
         $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
         $countsql .= $from . $where;
         $nbmaincolumns = count($columns);
         // Get number of main columns used.
         $objectives = get_scorm_objectives($scorm->id);
         $nosort = array();
         foreach ($objectives as $scoid => $sco) {
             foreach ($sco as $id => $objectivename) {
                 $colid = $scoid . 'objectivestatus' . $id;
                 $columns[] = $colid;
                 $nosort[] = $colid;
                 if (!$displayoptions['objectivescore']) {
                     // Display the objective name only.
                     $headers[] = $objectivename;
                 } else {
                     // Display the objective status header with a "status" suffix to avoid confusion.
                     $headers[] = $objectivename . ' ' . get_string('status', 'scormreport_objectives');
                     // Now print objective score headers.
                     $colid = $scoid . 'objectivescore' . $id;
                     $columns[] = $colid;
                     $nosort[] = $colid;
                     $headers[] = $objectivename . ' ' . get_string('score', 'scormreport_objectives');
                 }
             }
         }
         $emptycell = '';
         // Used when an empty cell is being printed - in html we add a space.
         if (!$download) {
             $emptycell = '&nbsp;';
             $table = new \flexible_table('mod-scorm-report');
             $table->define_columns($columns);
             $table->define_headers($headers);
             $table->define_baseurl($PAGE->url);
             $table->sortable(true);
             $table->collapsible(true);
             // This is done to prevent redundant data, when a user has multiple attempts.
             $table->column_suppress('picture');
             $table->column_suppress('fullname');
             foreach ($extrafields as $field) {
                 $table->column_suppress($field);
             }
             foreach ($nosort as $field) {
                 $table->no_sorting($field);
             }
             $table->no_sorting('start');
             $table->no_sorting('finish');
             $table->no_sorting('score');
             $table->no_sorting('checkbox');
             $table->no_sorting('picture');
             foreach ($scoes as $sco) {
                 if ($sco->launch != '') {
                     $table->no_sorting('scograde' . $sco->id);
                 }
             }
             $table->column_class('picture', 'picture');
             $table->column_class('fullname', 'bold');
             $table->column_class('score', 'bold');
             $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 == 'ODS') {
                 require_once "{$CFG->libdir}/odslib.class.php";
                 $filename .= ".ods";
                 // Creating a workbook.
                 $workbook = new \MoodleODSWorkbook("-");
                 // Sending HTTP headers.
                 $workbook->send($filename);
                 // Creating the first worksheet.
                 $sheettitle = get_string('report', 'scorm');
                 $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.
                 $colnum = 0;
                 foreach ($headers as $item) {
                     $myxls->write(0, $colnum, $item, $formatbc);
                     $colnum++;
                 }
                 $rownum = 1;
             } 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('report', 'scorm');
                     $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');
                     $colnum = 0;
                     foreach ($headers as $item) {
                         $myxls->write(0, $colnum, $item, $formatbc);
                         $colnum++;
                     }
                     $rownum = 1;
                 } else {
                     if ($download == 'CSV') {
                         $csvexport = new \csv_export_writer("tab");
                         $csvexport->set_filename($filename, ".txt");
                         $csvexport->add_data($headers);
                     }
                 }
             }
         }
         if (!$download) {
             $sort = $table->get_sql_sort();
         } else {
             $sort = '';
         }
         // Fix some wired sorting.
         if (empty($sort)) {
             $sort = ' ORDER BY uniqueid';
         } else {
             $sort = ' ORDER BY ' . $sort;
         }
         if (!$download) {
             // Add extra limits due to initials bar.
             list($twhere, $tparams) = $table->get_sql_where();
             if ($twhere) {
                 $where .= ' AND ' . $twhere;
                 // Initial bar.
                 $params = array_merge($params, $tparams);
             }
             if (!empty($countsql)) {
                 $count = $DB->get_record_sql($countsql, $params);
                 $totalinitials = $count->nbresults;
                 if ($twhere) {
                     $countsql .= ' AND ' . $twhere;
                 }
                 $count = $DB->get_record_sql($countsql, $params);
                 $total = $count->nbresults;
             }
             $table->pagesize($pagesize, $total);
             echo \html_writer::start_div('scormattemptcounts');
             if ($count->nbresults == $count->nbattempts) {
                 echo get_string('reportcountattempts', 'scorm', $count);
             } else {
                 if ($count->nbattempts > 0) {
                     echo get_string('reportcountallattempts', 'scorm', $count);
                 } else {
                     echo $count->nbusers . ' ' . get_string('users');
                 }
             }
             echo \html_writer::end_div();
         }
         // Fetch the attempts.
         if (!$download) {
             $attempts = $DB->get_records_sql($select . $from . $where . $sort, $params, $table->get_page_start(), $table->get_page_size());
             echo \html_writer::start_div('', array('id' => 'scormtablecontainer'));
             if ($candelete) {
                 // Start form.
                 $strreallydel = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
                 echo \html_writer::start_tag('form', array('id' => 'attemptsform', 'method' => 'post', 'action' => $PAGE->url->out(false), 'onsubmit' => 'return confirm("' . $strreallydel . '");'));
                 echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'action', 'value' => 'delete'));
                 echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
                 echo \html_writer::start_div('', array('style' => 'display: none;'));
                 echo \html_writer::input_hidden_params($PAGE->url);
                 echo \html_writer::end_div();
                 echo \html_writer::start_div();
             }
             $table->initialbars($totalinitials > 20);
             // Build table rows.
         } else {
             $attempts = $DB->get_records_sql($select . $from . $where . $sort, $params);
         }
         if ($attempts) {
             foreach ($attempts as $scouser) {
                 $row = array();
                 if (!empty($scouser->attempt)) {
                     $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
                 } else {
                     $timetracks = '';
                 }
                 if (in_array('checkbox', $columns)) {
                     if ($candelete && !empty($timetracks->start)) {
                         $row[] = \html_writer::checkbox('attemptid[]', $scouser->userid . ':' . $scouser->attempt, false);
                     } else {
                         if ($candelete) {
                             $row[] = '';
                         }
                     }
                 }
                 if (in_array('picture', $columns)) {
                     $user = new \stdClass();
                     $additionalfields = explode(',', \user_picture::fields());
                     $user = username_load_fields_from_object($user, $scouser, null, $additionalfields);
                     $user->id = $scouser->userid;
                     $row[] = $OUTPUT->user_picture($user, array('courseid' => $course->id));
                 }
                 if (!$download) {
                     $url = new \moodle_url('/user/view.php', array('id' => $scouser->userid, 'course' => $course->id));
                     $row[] = \html_writer::link($url, fullname($scouser));
                 } else {
                     $row[] = fullname($scouser);
                 }
                 foreach ($extrafields as $field) {
                     $row[] = s($scouser->{$field});
                 }
                 if (empty($timetracks->start)) {
                     $row[] = '-';
                     $row[] = '-';
                     $row[] = '-';
                     $row[] = '-';
                 } else {
                     if (!$download) {
                         $url = new \moodle_url('/mod/scorm/report/userreport.php', array('id' => $cm->id, 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
                         $row[] = \html_writer::link($url, $scouser->attempt);
                     } else {
                         $row[] = $scouser->attempt;
                     }
                     if ($download == 'ODS' || $download == 'Excel') {
                         $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
                     } else {
                         $row[] = userdate($timetracks->start);
                     }
                     if ($download == 'ODS' || $download == 'Excel') {
                         $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
                     } else {
                         $row[] = userdate($timetracks->finish);
                     }
                     $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
                 }
                 // Print out all scores of attempt.
                 foreach ($scoes as $sco) {
                     if ($sco->launch != '') {
                         if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
                             if ($trackdata->status == '') {
                                 $trackdata->status = 'notattempted';
                             }
                             $strstatus = get_string($trackdata->status, 'scorm');
                             if ($trackdata->score_raw != '') {
                                 // If raw score exists, print it.
                                 $score = $trackdata->score_raw;
                                 // Add max score if it exists.
                                 if (isset($trackdata->score_max)) {
                                     $score .= '/' . $trackdata->score_max;
                                 }
                             } else {
                                 // ...else print out status.
                                 $score = $strstatus;
                             }
                             if (!$download) {
                                 $url = new \moodle_url('/mod/scorm/report/userreporttracks.php', array('id' => $cm->id, 'scoid' => $sco->id, 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
                                 $row[] = \html_writer::img($OUTPUT->pix_url($trackdata->status, 'scorm'), $strstatus, array('title' => $strstatus)) . \html_writer::empty_tag('br') . \html_writer::link($url, $score, array('title' => get_string('details', 'scorm')));
                             } else {
                                 $row[] = $score;
                             }
                             // Iterate over tracks and match objective id against values.
                             $scorm2004 = false;
                             if (scorm_version_check($scorm->version, SCORM_13)) {
                                 $scorm2004 = true;
                                 $objectiveprefix = "cmi.objectives.";
                             } else {
                                 $objectiveprefix = "cmi.objectives_";
                             }
                             $keywords = array(".id", $objectiveprefix);
                             $objectivestatus = array();
                             $objectivescore = array();
                             foreach ($trackdata as $name => $value) {
                                 if (strpos($name, $objectiveprefix) === 0 && strrpos($name, '.id') !== false) {
                                     $num = trim(str_ireplace($keywords, '', $name));
                                     if (is_numeric($num)) {
                                         if ($scorm2004) {
                                             $element = $objectiveprefix . $num . '.completion_status';
                                         } else {
                                             $element = $objectiveprefix . $num . '.status';
                                         }
                                         if (isset($trackdata->{$element})) {
                                             $objectivestatus[$value] = $trackdata->{$element};
                                         } else {
                                             $objectivestatus[$value] = '';
                                         }
                                         if ($displayoptions['objectivescore']) {
                                             $element = $objectiveprefix . $num . '.score.raw';
                                             if (isset($trackdata->{$element})) {
                                                 $objectivescore[$value] = $trackdata->{$element};
                                             } else {
                                                 $objectivescore[$value] = '';
                                             }
                                         }
                                     }
                                 }
                             }
                             // Interaction data.
                             if (!empty($objectives[$trackdata->scoid])) {
                                 foreach ($objectives[$trackdata->scoid] as $name) {
                                     if (isset($objectivestatus[$name])) {
                                         $row[] = s($objectivestatus[$name]);
                                     } else {
                                         $row[] = $emptycell;
                                     }
                                     if ($displayoptions['objectivescore']) {
                                         if (isset($objectivescore[$name])) {
                                             $row[] = s($objectivescore[$name]);
                                         } else {
                                             $row[] = $emptycell;
                                         }
                                     }
                                 }
                             }
                             // End of interaction data.
                         } else {
                             // If we don't have track data, we haven't attempted yet.
                             $strstatus = get_string('notattempted', 'scorm');
                             if (!$download) {
                                 $row[] = \html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'), $strstatus, array('title' => $strstatus)) . \html_writer::empty_tag('br') . $strstatus;
                             } else {
                                 $row[] = $strstatus;
                             }
                             // Complete the empty cells.
                             for ($i = 0; $i < count($columns) - $nbmaincolumns; $i++) {
                                 $row[] = $emptycell;
                             }
                         }
                     }
                 }
                 if (!$download) {
                     $table->add_data($row);
                 } else {
                     if ($download == 'Excel' or $download == 'ODS') {
                         $colnum = 0;
                         foreach ($row as $item) {
                             $myxls->write($rownum, $colnum, $item, $format);
                             $colnum++;
                         }
                         $rownum++;
                     } else {
                         if ($download == 'CSV') {
                             $csvexport->add_data($row);
                         }
                     }
                 }
             }
             if (!$download) {
                 $table->finish_output();
                 if ($candelete) {
                     echo \html_writer::start_tag('table', array('id' => 'commands'));
                     echo \html_writer::start_tag('tr') . \html_writer::start_tag('td');
                     echo \html_writer::link('javascript:select_all_in(\'DIV\', null, \'scormtablecontainer\');', get_string('selectall', 'scorm')) . ' / ';
                     echo \html_writer::link('javascript:deselect_all_in(\'DIV\', null, \'scormtablecontainer\');', get_string('selectnone', 'scorm'));
                     echo '&nbsp;&nbsp;';
                     echo \html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('deleteselected', 'scorm'), 'class' => 'btn btn-secondary'));
                     echo \html_writer::end_tag('td') . \html_writer::end_tag('tr') . \html_writer::end_tag('table');
                     // Close form.
                     echo \html_writer::end_tag('div');
                     echo \html_writer::end_tag('form');
                 }
                 echo \html_writer::end_div();
                 if (!empty($attempts)) {
                     echo \html_writer::start_tag('table', array('class' => 'boxaligncenter')) . \html_writer::start_tag('tr');
                     echo \html_writer::start_tag('td');
                     echo $OUTPUT->single_button(new \moodle_url($PAGE->url, array('download' => 'ODS') + $displayoptions), get_string('downloadods'), 'post', ['class' => 'm-t-1']);
                     echo \html_writer::end_tag('td');
                     echo \html_writer::start_tag('td');
                     echo $OUTPUT->single_button(new \moodle_url($PAGE->url, array('download' => 'Excel') + $displayoptions), get_string('downloadexcel'), 'post', ['class' => 'm-t-1']);
                     echo \html_writer::end_tag('td');
                     echo \html_writer::start_tag('td');
                     echo $OUTPUT->single_button(new \moodle_url($PAGE->url, array('download' => 'CSV') + $displayoptions), get_string('downloadtext'), 'post', ['class' => 'm-t-1']);
                     echo \html_writer::end_tag('td');
                     echo \html_writer::start_tag('td');
                     echo \html_writer::end_tag('td');
                     echo \html_writer::end_tag('tr') . \html_writer::end_tag('table');
                 }
             }
         } else {
             if ($candelete && !$download) {
                 echo \html_writer::end_div();
                 echo \html_writer::end_tag('form');
                 $table->finish_output();
             }
             echo \html_writer::end_div();
         }
         // Show preferences form irrespective of attempts are there to report or not.
         if (!$download) {
             $mform->set_data(compact('detailedrep', 'pagesize', 'attemptsmode'));
             $mform->display();
         }
         if ($download == 'Excel' or $download == 'ODS') {
             $workbook->close();
             exit;
         } else {
             if ($download == 'CSV') {
                 $csvexport->download_file();
                 exit;
             }
         }
     } else {
         echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
     }
 }
Example #17
0
    function export_ods($report, $filename = null) {
        global $DB, $CFG;
        require_once($CFG->dirroot . '/lib/odslib.class.php');

        $table = $report->table;
        $matrix = array();
        //!$fname? $filename = 'report_'.(time()).'.ods':
        $filename = $filename . '.ods';

        if (!empty($table->head)) {
            $countcols = count($table->head);
            $keys = array_keys($table->head);
            $lastkey = end($keys);
            foreach ($table->head as $key => $heading) {
                $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading))));
            }
        }

        if (!empty($table->data)) {
            foreach ($table->data as $rkey => $row) {
                foreach ($row as $key => $item) {
                    $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item))));
                }
            }
        }
        $workbook = new MoodleODSWorkbook($filename);

        $myxls = array();

        $myxls[0] = $workbook->add_worksheet('');
        foreach ($matrix as $ri => $col) {
            foreach ($col as $ci => $cv) {
                $myxls[0]->write($ri, $ci, $cv);
            }
        }
        $writer = new MoodleODSWriter($myxls);
        $contents = $writer->get_file_content();
        $handle = fopen($filename, 'w');
        fwrite($handle, $contents);
        fclose($handle);
    }
Example #18
0
/** Download data in ODS format
  *
  * @param array $fields Array of column headings
  * @param string $datarows Array of data to populate table with
  * @param string $file Name of file for exportig
  * @return Returns the ODS file
 */
function facetoface_download_ods($fields, $datarows, $file=null) {
    global $CFG, $DB;

    require_once("$CFG->libdir/odslib.class.php");
    $filename = clean_filename($file . '.ods');

    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");

    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    if (!empty($fields)) {
        $countcols = count($fields);
        $keys = array_keys($fields);
        $lastkey = end($keys);
        foreach ($fields as $key => $heading) {
            $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading))));
        }
    }

    if (!empty($datarows)) {
        foreach ($datarows as $rkey => $row) {
            foreach ($row as $key => $item) {
                $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item))));
            }
        }
    }
    $myxls = & $workbook->add_worksheet($filename);

    foreach ($matrix as $ri => $col) {
        foreach ($col as $ci => $cv) {
            $myxls->write_string($ri, $ci, $cv);
        }
    }
    //$worksheet[0] = $workbook->add_worksheet('');
    //$row = 0;
    //$col = 0;
    //
    //foreach ($fields as $field) {
    //     $myxls->write_string($ri, $ci, $cv);
    //    $col++;
    //}
    //$row++;
    //
    //$numfields = count($fields);
    //
    //foreach ($datarows as $record) {
    //    for($col=0; $col<$numfields; $col++) {
    //        if (isset($record[$col])) {
    //            $worksheet[0]->write($row, $col, html_entity_decode($record[$col], ENT_COMPAT, 'UTF-8'));
    //        }
    //    }
    //    $row++;
    //}

    $workbook->close();
    exit;
}
/**
 * Serves a list of participants as a file.
 *
 * @param unknown_type $offlinequiz
 * @param unknown_type $fileformat
 * @param unknown_type $coursecontext
 * @param unknown_type $systemcontext
 */
function offlinequiz_download_partlist($offlinequiz, $fileformat, &$coursecontext, &$systemcontext)
{
    global $CFG, $DB, $COURSE;
    offlinequiz_load_useridentification();
    $offlinequizconfig = get_config('offlinequiz');
    $filename = clean_filename(get_string('participants', 'offlinequiz') . $offlinequiz->id);
    // First get roleids for students from leagcy.
    if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
        print_error("No roles with capability 'mod/offlinequiz:attempt' defined in system context");
    }
    $roleids = array();
    foreach ($roles as $role) {
        $roleids[] = $role->id;
    }
    list($csql, $cparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
    list($rsql, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
    $params = array_merge($cparams, $rparams);
    $sql = "SELECT p.id, p.userid, p.listid, u." . $offlinequizconfig->ID_field . ", u.firstname, u.lastname,\n                   u.alternatename, u.middlename, u.firstnamephonetic, u.lastnamephonetic,\n                   u.picture, p.checked\n             FROM {offlinequiz_participants} p,\n                  {offlinequiz_p_lists} pl,\n                  {user} u,\n                  {role_assignments} ra\n            WHERE p.listid = pl.id\n              AND p.userid = u.id\n              AND ra.userid=u.id\n              AND pl.offlinequizid = :offlinequizid\n              AND ra.contextid {$csql}\n              AND ra.roleid {$rsql}";
    $params['offlinequizid'] = $offlinequiz->id;
    // Define table headers.
    $tableheaders = array(get_string('fullname'), get_string($offlinequizconfig->ID_field), get_string('participantslist', 'offlinequiz'), get_string('attemptexists', 'offlinequiz'), get_string('present', 'offlinequiz'));
    if ($fileformat == 'ODS') {
        require_once "{$CFG->libdir}/odslib.class.php";
        $filename .= ".ods";
        // Creating a workbook.
        $workbook = new MoodleODSWorkbook("-");
        // Sending HTTP headers.
        $workbook->send($filename);
        // Creating the first worksheet.
        $sheettitle = get_string('participants', 'offlinequiz');
        $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');
        // Print worksheet headers.
        $colnum = 0;
        foreach ($tableheaders as $item) {
            $myxls->write(0, $colnum, $item, $formatbc);
            $colnum++;
        }
        $rownum = 1;
    } else {
        if ($fileformat == '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('participants', 'offlinequiz');
            $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 = new StdClass();
            $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');
            // Print worksheet headers.
            $colnum = 0;
            foreach ($tableheaders as $item) {
                $myxls->write(0, $colnum, $item, $formatbc);
                $colnum++;
            }
            $rownum = 1;
        } else {
            if ($fileformat == '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 = implode(", ", $tableheaders);
                echo $headers . " \n";
            }
        }
    }
    $lists = $DB->get_records('offlinequiz_p_lists', array('offlinequizid' => $offlinequiz->id));
    $participants = $DB->get_records_sql($sql, $params);
    if ($participants) {
        foreach ($participants as $participant) {
            $userid = $participant->userid;
            $attempt = false;
            $sql = "SELECT COUNT(*)\n                      FROM {offlinequiz_results}\n                     WHERE userid = :userid\n                       AND offlinequizid = :offlinequizid\n                       AND status = 'complete'";
            if ($DB->count_records_sql($sql, array('userid' => $userid, 'offlinequizid' => $offlinequiz->id)) > 0) {
                $attempt = true;
            }
            $row = array(fullname($participant), $participant->{$offlinequizconfig->ID_field}, $lists[$participant->listid]->name, $attempt ? get_string('yes') : get_string('no'), $participant->checked ? get_string('yes') : get_string('no'));
            if ($fileformat == 'Excel' or $fileformat == 'ODS') {
                $colnum = 0;
                foreach ($row as $item) {
                    $myxls->write($rownum, $colnum, $item, $format);
                    $colnum++;
                }
                $rownum++;
            } else {
                if ($fileformat == 'CSV') {
                    $text = implode(", ", $row);
                    echo $text . "\n";
                }
            }
        }
    }
    if ($fileformat == 'Excel' or $fileformat == 'ODS') {
        $workbook->close();
    }
    exit;
}
 /**
  * (non-PHPdoc)
  *
  * @see offlinequiz_default_report::display()
  */
 public function display($offlinequiz, $cm, $course)
 {
     global $CFG, $OUTPUT, $SESSION, $DB;
     // Define some strings.
     $strtimeformat = get_string('strftimedatetime');
     $letterstr = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     offlinequiz_load_useridentification();
     $offlinequizconfig = get_config('offlinequiz');
     // Deal with actions.
     $action = optional_param('action', '', PARAM_ACTION);
     // Only print headers if not asked to download data or delete data.
     if (!($download = optional_param('download', null, PARAM_TEXT)) && !$action == 'delete') {
         $this->print_header_and_tabs($cm, $course, $offlinequiz, 'overview');
         echo $OUTPUT->box_start('linkbox');
         echo $OUTPUT->heading(format_string($offlinequiz->name));
         echo $OUTPUT->heading(get_string('results', 'offlinequiz'));
         require_once $CFG->libdir . '/grouplib.php';
         echo groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/offlinequiz/report.php?id=' . $cm->id . '&mode=overview', true);
         echo $OUTPUT->box_end();
         echo '<br/>';
     }
     $context = context_module::instance($cm->id);
     $systemcontext = context_system::instance();
     // Set table options.
     $noresults = optional_param('noresults', 0, PARAM_INT);
     $pagesize = optional_param('pagesize', 10, PARAM_INT);
     $groupid = optional_param('group', 0, PARAM_INT);
     if ($pagesize < 1) {
         $pagesize = 10;
     }
     $answerletters = 'abcdefghijklmnopqrstuvwxyz';
     if ($action == 'delete' && confirm_sesskey()) {
         $selectedresultids = array();
         $params = (array) data_submitted();
         foreach ($params as $key => $value) {
             if (preg_match('!^s([0-9]+)$!', $key, $matches)) {
                 $selectedresultids[] = $matches[1];
             }
         }
         if ($selectedresultids) {
             foreach ($selectedresultids as $resultid) {
                 if ($resultid && ($todelete = $DB->get_record('offlinequiz_results', array('id' => $resultid)))) {
                     offlinequiz_delete_result($resultid, $context);
                     // Log this event.
                     $params = array('objectid' => $resultid, 'relateduserid' => $todelete->userid, 'context' => context_module::instance($cm->id), 'other' => array('mode' => 'overview'));
                     $event = \mod_offlinequiz\event\attempt_deleted::create($params);
                     $event->trigger();
                     // Change the status of all related pages with error 'resultexists' to 'suspended'.
                     $user = $DB->get_record('user', array('id' => $todelete->userid));
                     $group = $DB->get_record('offlinequiz_groups', array('id' => $todelete->offlinegroupid));
                     $sql = "SELECT id\n                                  FROM {offlinequiz_scanned_pages}\n                                 WHERE offlinequizid = :offlinequizid\n                                   AND userkey = :userkey\n                                   AND groupnumber = :groupnumber\n                                   AND status = 'error'\n                                   AND (error = 'resultexists' OR error = 'differentresultexists')";
                     $params = array('offlinequizid' => $offlinequiz->id, 'userkey' => $user->{$offlinequizconfig->ID_field}, 'groupnumber' => $group->number);
                     $otherpages = $DB->get_records_sql($sql, $params);
                     foreach ($otherpages as $page) {
                         $DB->set_field('offlinequiz_scanned_pages', 'status', 'suspended', array('id' => $page->id));
                         $DB->set_field('offlinequiz_scanned_pages', 'error', '', array('id' => $page->id));
                     }
                 }
             }
             offlinequiz_grade_item_update($offlinequiz, 'reset');
             offlinequiz_update_grades($offlinequiz);
             redirect(new moodle_url('/mod/offlinequiz/report.php', array('mode' => 'overview', 'id' => $cm->id, 'noresults' => $noresults, 'pagesize' => $pagesize)));
         }
     }
     // Now check if asked download of data.
     if ($download) {
         $filename = clean_filename("{$course->shortname} " . format_string($offlinequiz->name, true));
         $sort = '';
     }
     // Fetch the group data.
     $groups = $DB->get_records('offlinequiz_groups', array('offlinequizid' => $offlinequiz->id), 'number', '*', 0, $offlinequiz->numgroups);
     // Define table columns.
     $tablecolumns = array('checkbox', 'picture', 'fullname', $offlinequizconfig->ID_field, 'timestart', 'offlinegroupid', 'sumgrades');
     $tableheaders = array('<input type="checkbox" name="toggle" onClick="if (this.checked) {select_all_in(\'DIV\',null,\'tablecontainer\');}
             else {deselect_all_in(\'DIV\',null,\'tablecontainer\');}"/>', '', get_string('fullname'), get_string($offlinequizconfig->ID_field), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
     $checked = array();
     // Get participants list.
     $withparticipants = false;
     if ($lists = $DB->get_records('offlinequiz_p_lists', array('offlinequizid' => $offlinequiz->id))) {
         $withparticipants = true;
         $tablecolumns[] = 'checked';
         $tableheaders[] = get_string('present', 'offlinequiz');
         foreach ($lists as $list) {
             $participants = $DB->get_records('offlinequiz_participants', array('listid' => $list->id));
             foreach ($participants as $participant) {
                 $checked[$participant->userid] = $participant->checked;
             }
         }
     }
     if (!$download) {
         // Set up the table.
         $params = array('offlinequiz' => $offlinequiz, 'noresults' => $noresults, 'pagesize' => $pagesize);
         $table = new offlinequiz_results_table('mod-offlinequiz-report-overview-report', $params);
         $table->define_columns($tablecolumns);
         $table->define_headers($tableheaders);
         $table->define_baseurl($CFG->wwwroot . '/mod/offlinequiz/report.php?mode=overview&amp;id=' . $cm->id . '&amp;noresults=' . $noresults . '&amp;pagesize=' . $pagesize);
         $table->sortable(true);
         $table->no_sorting('checkbox');
         if ($withparticipants) {
             $table->no_sorting('checked');
         }
         $table->column_suppress('picture');
         $table->column_suppress('fullname');
         $table->column_class('picture', 'picture');
         $table->column_class($offlinequizconfig->ID_field, 'userkey');
         $table->column_class('timestart', 'timestart');
         $table->column_class('offlinegroupid', 'offlinegroupid');
         $table->column_class('sumgrades', 'sumgrades');
         $table->set_attribute('cellpadding', '2');
         $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 == 'ODS') {
             require_once "{$CFG->libdir}/odslib.class.php";
             $filename .= ".ods";
             // Creating a workbook.
             $workbook = new MoodleODSWorkbook("-");
             // Sending HTTP headers.
             $workbook->send($filename);
             // Creating the first worksheet.
             $sheettitle = get_string('reportoverview', 'offlinequiz');
             $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($offlinequizconfig->ID_field), get_string('firstname'), get_string('lastname'), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
             if (!empty($withparticipants)) {
                 $headers[] = get_string('present', 'offlinequiz');
             }
             $colnum = 0;
             foreach ($headers as $item) {
                 $myxls->write(0, $colnum, $item, $formatbc);
                 $colnum++;
             }
             $rownum = 1;
         } 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('results', 'offlinequiz');
                 $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 worksheet headers.
                 $headers = array(get_string($offlinequizconfig->ID_field), get_string('firstname'), get_string('lastname'), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
                 if (!empty($withparticipants)) {
                     $headers[] = get_string('present', 'offlinequiz');
                 }
                 $colnum = 0;
                 foreach ($headers as $item) {
                     $myxls->write(0, $colnum, $item, $formatbc);
                     $colnum++;
                 }
                 $rownum = 1;
             } else {
                 if ($download == 'CSV') {
                     $filename .= ".csv";
                     header("Content-Encoding: UTF-8");
                     header("Content-Type: text/csv; charset=utf-8");
                     header("Content-Disposition: attachment; filename=\"{$filename}\"");
                     header("Expires: 0");
                     header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                     header("Pragma: public");
                     echo "";
                     // UTF-8 BOM.
                     $headers = get_string($offlinequizconfig->ID_field) . ", " . get_string('fullname') . ", " . get_string('importedon', 'offlinequiz') . ", " . get_string('group') . ", " . get_string('grade', 'offlinequiz');
                     if (!empty($withparticipants)) {
                         $headers .= ", " . get_string('present', 'offlinequiz');
                     }
                     echo $headers . " \n";
                 } else {
                     if ($download == 'CSVplus1' || $download == 'CSVpluspoints') {
                         $filename .= ".csv";
                         header("Content-Encoding: UTF-8");
                         header("Content-Type: text/csv; charset=utf-8");
                         header("Content-Disposition: attachment; filename=\"{$filename}\"");
                         header("Expires: 0");
                         header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                         header("Pragma: public");
                         echo "";
                         // UTF-8 BOM.
                         // Print the table headers.
                         echo get_string('firstname') . ',' . get_string('lastname') . ',' . get_string($offlinequizconfig->ID_field) . ',' . get_string('group');
                         $maxquestions = offlinequiz_get_maxquestions($offlinequiz, $groups);
                         for ($i = 0; $i < $maxquestions; $i++) {
                             echo ', ' . get_string('question') . ' ' . ($i + 1);
                         }
                         echo "\n";
                         // Print the correct answer bit-strings.
                         foreach ($groups as $group) {
                             if ($group->templateusageid) {
                                 $quba = question_engine::load_questions_usage_by_activity($group->templateusageid);
                                 $slots = $quba->get_slots();
                                 echo ', ,' . get_string('correct', 'offlinequiz');
                                 echo ',' . $group->number;
                                 foreach ($slots as $slot) {
                                     $slotquestion = $quba->get_question($slot);
                                     $qtype = $slotquestion->get_type_name();
                                     if ($qtype == 'multichoice' || $qtype == 'multichoiceset') {
                                         $attempt = $quba->get_question_attempt($slot);
                                         $order = $slotquestion->get_order($attempt);
                                         // Order of the answers.
                                         $tempstr = ",";
                                         $letters = array();
                                         $counter = 0;
                                         foreach ($order as $key => $answerid) {
                                             $fraction = $DB->get_field('question_answers', 'fraction', array('id' => $answerid));
                                             if ($fraction > 0) {
                                                 $letters[] = $answerletters[$counter];
                                             }
                                             $counter++;
                                         }
                                         if (empty($letters)) {
                                             $tempstr .= '99';
                                         } else {
                                             $tempstr .= implode('/', $letters);
                                         }
                                         echo $tempstr;
                                     }
                                 }
                                 echo "\n";
                             }
                         }
                     }
                 }
             }
         }
     }
     $coursecontext = context_course::instance($course->id);
     $contextids = $coursecontext->get_parent_context_ids(true);
     // Construct the SQL
     // First get roleids for students from leagcy.
     if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
         error("No roles with capability 'moodle/offlinequiz:attempt' defined in system context");
     }
     $roleids = array();
     foreach ($roles as $role) {
         $roleids[] = $role->id;
     }
     $rolelist = implode(',', $roleids);
     $select = "SELECT " . $DB->sql_concat('u.id', "'#'", "COALESCE(qa.usageid, 0)") . " AS uniqueid,\n        qa.id AS resultid, u.id, qa.usageid, qa.offlinegroupid, qa.status,\n        u.id AS userid, u.firstname, u.lastname,\n        u.alternatename, u.middlename, u.firstnamephonetic, u.lastnamephonetic,\n        u.picture, u." . $offlinequizconfig->ID_field . ",\n        qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ";
     $result = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
     list($contexttest, $cparams) = $result;
     list($roletest, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
     $from = "FROM {user} u\n                  JOIN {role_assignments} ra ON ra.userid = u.id\n             LEFT JOIN {offlinequiz_results} qa ON u.id = qa.userid AND qa.offlinequizid = :offlinequizid\n             ";
     $where = " WHERE ra.contextid {$contexttest} AND ra.roleid {$roletest} ";
     $params = array('offlinequizid' => $offlinequiz->id);
     $params = array_merge($params, $cparams, $rparams);
     if ($groupid) {
         $from .= " JOIN {groups_members} gm ON gm.userid = u.id ";
         $where .= " AND gm.groupid = :groupid ";
         $params['groupid'] = $groupid;
     }
     if (empty($noresults)) {
         $where = $where . " AND qa.userid IS NOT NULL\n                                AND qa.status = 'complete'";
         // Show ONLY students with results.
     } else {
         if ($noresults == 1) {
             // The value noresults = 1 means only no results, so make the left join ask for only records
             // where the right is null (no results).
             $where .= ' AND qa.userid IS NULL';
             // Show ONLY students without results.
         } else {
             if ($noresults == 3) {
                 // We want all results, also the partial ones.
                 $from = "FROM {user} u\n                      JOIN {offlinequiz_results} qa ON u.id = qa.userid ";
                 $where = " WHERE qa.offlinequizid = :offlinequizid";
             }
         }
     }
     // The value noresults = 2 means we want all students, with or without results.
     $countsql = 'SELECT COUNT(DISTINCT(u.id)) ' . $from . $where;
     if (!$download) {
         // Count the records NOW, before funky question grade sorting messes up $from.
         $totalinitials = $DB->count_records_sql($countsql, $params);
         // Add extra limits due to initials bar.
         list($ttest, $tparams) = $table->get_sql_where();
         if (!empty($ttest)) {
             $where .= ' AND ' . $ttest;
             $countsql .= ' AND ' . $ttest;
             $params = array_merge($params, $tparams);
         }
         $total = $DB->count_records_sql($countsql, $params);
         // Add extra limits due to sorting by question grade.
         $sort = $table->get_sql_sort();
         // Fix some wired sorting.
         if (empty($sort)) {
             $sort = ' ORDER BY u.lastname';
         } else {
             $sort = ' ORDER BY ' . $sort;
         }
         $table->pagesize($pagesize, $total);
     }
     // Fetch the results.
     if (!$download) {
         $results = $DB->get_records_sql($select . $from . $where . $sort, $params, $table->get_page_start(), $table->get_page_size());
     } else {
         $results = $DB->get_records_sql($select . $from . $where . $sort, $params);
     }
     // Build table rows.
     if (!$download) {
         $table->initialbars(true);
     }
     if (!empty($results) || !empty($noresults)) {
         foreach ($results as $result) {
             $user = $DB->get_record('user', array('id' => $result->userid));
             $picture = $OUTPUT->user_picture($user, array('courseid' => $course->id));
             if (!empty($result->resultid)) {
                 $checkbox = '<input type="checkbox" name="s' . $result->resultid . '" value="' . $result->resultid . '" />';
             } else {
                 $checkbox = '';
             }
             if (!empty($result) && (empty($result->resultid) || $result->timefinish == 0)) {
                 $resultdate = '-';
             } else {
                 $resultdate = userdate($result->timefinish, $strtimeformat);
             }
             if (!empty($result) && $result->offlinegroupid) {
                 $groupletter = $letterstr[$groups[$result->offlinegroupid]->number];
             } else {
                 $groupletter = '-';
             }
             $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $result->userid . '&amp;course=' . $course->id . '">' . fullname($result) . '</a>';
             if (!$download) {
                 $row = array($checkbox, $picture, $userlink, $result->{$offlinequizconfig->ID_field}, $resultdate, $groupletter);
             } else {
                 $row = array($result->{$offlinequizconfig->ID_field}, $result->firstname, $result->lastname, $resultdate, $groupletter);
             }
             if (!empty($result) && $result->offlinegroupid) {
                 $outputgrade = format_float($result->sumgrades / $groups[$result->offlinegroupid]->sumgrades * $offlinequiz->grade, $offlinequiz->decimalpoints);
             } else {
                 $outputgrade = '-';
             }
             if (!$download) {
                 if ($result->status == 'partial') {
                     $row[] = get_string('partial', 'offlinequiz');
                 } else {
                     if ($result->sumgrades === null) {
                         $row[] = '-';
                     } else {
                         $row[] = '<a href="review.php?q=' . $offlinequiz->id . '&amp;resultid=' . $result->resultid . '">' . $outputgrade . '</a>';
                     }
                 }
                 if ($withparticipants) {
                     $row[] = !empty($checked[$result->userid]) ? "<img src=\"{$CFG->wwwroot}/mod/offlinequiz/pix/tick.gif\" alt=\"" . get_string('ischecked', 'offlinequiz') . "\">" : "<img src=\"{$CFG->wwwroot}/mod/offlinequiz/pix/cross.gif\" alt=\"" . get_string('isnotchecked', 'offlinequiz') . "\">";
                 }
             } else {
                 if ($download != 'CSVplus1' || $download == 'CSVpluspoints') {
                     $row[] = $result->sumgrades === null ? '-' : $outputgrade;
                     if ($withparticipants) {
                         if (array_key_exists($result->userid, $checked)) {
                             $row[] = $checked[$result->userid] ? get_string('ok') : '-';
                         } else {
                             $row[] = '-';
                         }
                     }
                 }
             }
             if (!$download) {
                 $table->add_data($row);
             } else {
                 if ($download == 'Excel' or $download == 'ODS') {
                     $colnum = 0;
                     foreach ($row as $item) {
                         $myxls->write($rownum, $colnum, $item, $format);
                         $colnum++;
                     }
                     $rownum++;
                 } else {
                     if ($download == 'CSV') {
                         $text = implode(',', $row);
                         echo $text . "\n";
                     } else {
                         if ($download == 'CSVplus1' || $download == 'CSVpluspoints') {
                             $text = $row[1] . ',' . $row[2] . ',' . $row[0] . ',' . $groups[$result->offlinegroupid]->number;
                             if ($pages = $DB->get_records('offlinequiz_scanned_pages', array('resultid' => $result->resultid), 'pagenumber ASC')) {
                                 foreach ($pages as $page) {
                                     if ($page->status == 'ok' || $page->status == 'submitted') {
                                         $choices = $DB->get_records('offlinequiz_choices', array('scannedpageid' => $page->id), 'slotnumber, choicenumber');
                                         $counter = 0;
                                         $oldslot = -1;
                                         $letters = array();
                                         foreach ($choices as $choice) {
                                             if ($oldslot == -1) {
                                                 $oldslot = $choice->slotnumber;
                                             } else {
                                                 if ($oldslot != $choice->slotnumber) {
                                                     if (empty($letters)) {
                                                         $text .= ',99';
                                                     } else {
                                                         $text .= ',' . implode('/', $letters);
                                                     }
                                                     $counter = 0;
                                                     $oldslot = $choice->slotnumber;
                                                     $letters = array();
                                                 }
                                             }
                                             if ($choice->value == 1) {
                                                 $letters[] = $answerletters[$counter];
                                             }
                                             $counter++;
                                         }
                                         if (empty($letters)) {
                                             $text .= ',99';
                                         } else {
                                             $text .= ',' . implode('/', $letters);
                                         }
                                     }
                                 }
                             }
                             echo $text . "\n";
                             if ($download == 'CSVpluspoints') {
                                 $text = $row[1] . ',' . $row[2] . ',' . $row[0] . ',' . $groups[$result->offlinegroupid]->number;
                                 $quba = question_engine::load_questions_usage_by_activity($result->usageid);
                                 $slots = $quba->get_slots();
                                 foreach ($slots as $slot) {
                                     $slotquestion = $quba->get_question($slot);
                                     $attempt = $quba->get_question_attempt($slot);
                                     $text .= ',' . format_float($attempt->get_mark(), $offlinequiz->decimalpoints, false);
                                 }
                                 echo $text . "\n";
                             }
                         }
                     }
                 }
             }
         }
         // End foreach ($results...
     } else {
         if (!$download) {
             $table->print_initials_bar();
         }
     }
     if (!$download) {
         // Print table.
         $table->finish_html();
         if (!empty($results)) {
             echo '<form id="downloadoptions" action="report.php" method="get">';
             echo ' <input type="hidden" name="id" value="' . $cm->id . '" />';
             echo ' <input type="hidden" name="q" value="' . $offlinequiz->id . '" />';
             echo ' <input type="hidden" name="mode" value="overview" />';
             echo ' <input type="hidden" name="noheader" value="yes" />';
             echo ' <table class="boxaligncenter"><tr><td>';
             $options = array('Excel' => get_string('excelformat', 'offlinequiz'), 'ODS' => get_string('odsformat', 'offlinequiz'), 'CSV' => get_string('csvformat', 'offlinequiz'), 'CSVplus1' => get_string('csvplus1format', 'offlinequiz'), 'CSVpluspoints' => get_string('csvpluspointsformat', 'offlinequiz'));
             print_string('downloadresultsas', 'offlinequiz');
             echo "</td><td>";
             echo html_writer::select($options, 'download', '', false);
             echo ' <input type="submit" value="' . get_string('download') . '" />';
             echo ' <script type="text/javascript">' . "\n<!--\n" . 'document.getElementById("noscriptmenuaction").style.display = "none";' . "\n-->\n" . '</script>';
             echo " </td>\n";
             echo "<td>";
             echo "</td>\n";
             echo '</tr></table></form>';
         }
     } else {
         if ($download == 'Excel' || $download == 'ODS') {
             $workbook->close();
             exit;
         } else {
             if ($download == 'CSV' || $download == 'CSVplus1' || $download == 'CSVpluspoints') {
                 exit;
             }
         }
     }
     // Print display options.
     echo '<div class="controls">';
     echo '<form id="options" action="report.php" method="get">';
     echo '<div class=centerbox>';
     echo '<p>' . get_string('displayoptions', 'offlinequiz') . ': </p>';
     echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
     echo '<input type="hidden" name="q" value="' . $offlinequiz->id . '" />';
     echo '<input type="hidden" name="mode" value="overview" />';
     echo '<input type="hidden" name="detailedmarks" value="0" />';
     echo '<table id="overview-options" class="boxaligncenter">';
     echo '<tr align="left">';
     echo '<td><label for="pagesize">' . get_string('pagesizeparts', 'offlinequiz') . '</label></td>';
     echo '<td><input type="text" id="pagesize" name="pagesize" size="3" value="' . $pagesize . '" /></td>';
     echo '</tr>';
     echo '<tr align="left">';
     echo '<td colspan="2">';
     $options = array();
     $options[] = get_string('attemptsonly', 'offlinequiz');
     $options[] = get_string('noattemptsonly', 'offlinequiz');
     $options[] = get_string('allstudents', 'offlinequiz');
     $options[] = get_string('allresults', 'offlinequiz');
     echo html_writer::select($options, 'noresults', $noresults, '');
     echo '</td></tr>';
     echo '<tr><td colspan="2" align="center">';
     echo '<input type="submit" value="' . get_string('go') . '" />';
     echo '</td></tr></table>';
     echo '</div>';
     echo '</form>';
     echo '</div>';
     echo "\n";
     return true;
 }
function user_download_ods($userids, $fields, $includecompanyfield)
{
    global $CFG, $SESSION, $DB;
    require_once "{$CFG->libdir}/odslib.class.php";
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $filename = clean_filename(get_string('users') . '.ods');
    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        if ($includecompanyfield || $fieldname != "profile_field_company") {
            $worksheet[0]->write(0, $col, $fieldname);
            $col++;
        }
    }
    $worksheet[0]->write(0, $col, 'temppassword');
    $row = 1;
    foreach ($userids as $userid) {
        // Stop the script from timing out on large numbers of users.
        set_time_limit(30);
        if (!($user = $DB->get_record('user', array('id' => $userid)))) {
            continue;
        }
        $col = 0;
        profile_load_data($user);
        foreach ($fields as $field => $unused) {
            // Stop the script from timing out on large numbers of users.
            set_time_limit(30);
            if ($includecompanyfield || $field != "profile_field_company") {
                $worksheet[0]->write($row, $col, $user->{$field});
                $col++;
            }
        }
        $worksheet[0]->write($row, $col, company_user::get_temporary_password($user));
        $row++;
    }
    $workbook->close();
    die;
}
Example #22
0
         }
     }
     $table->column_class('picture', 'picture');
     $table->column_class('fullname', 'bold');
     $table->column_class('score', 'bold');
     $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 == 'ODS') {
         require_once "{$CFG->libdir}/odslib.class.php";
         $filename .= ".ods";
         // Creating a workbook
         $workbook = new MoodleODSWorkbook("-");
         // Sending HTTP headers
         $workbook->send($filename);
         // Creating the first worksheet
         $sheettitle = get_string('report', 'scorm');
         $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');
Example #23
0
 /**
  * Display the report.
  */
 function display($quiz, $cm, $course)
 {
     global $CFG, $db;
     // Define some strings
     $strreallydel = addslashes(get_string('deleteattemptcheck', 'quiz'));
     $strtimeformat = get_string('strftimedatetime');
     $strreviewquestion = get_string('reviewresponse', 'quiz');
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     // Only print headers if not asked to download data
     if (!($download = optional_param('download', NULL))) {
         $this->print_header_and_tabs($cm, $course, $quiz, "overview");
     }
     if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) {
         //attempts need to be deleted
         require_capability('mod/quiz:deleteattempts', $context);
         $attemptids = optional_param('attemptid', array(), PARAM_INT);
         foreach ($attemptids as $attemptid) {
             add_to_log($course->id, 'quiz', 'delete attempt', 'report.php?id=' . $cm->id, $attemptid, $cm->id);
             quiz_delete_attempt($attemptid, $quiz);
         }
         //No need for a redirect, any attemptids that do not exist are ignored.
         //So no problem if the user refreshes and tries to delete the same attempts
         //twice.
     }
     // Work out some display options - whether there is feedback, and whether scores should be shown.
     $hasfeedback = quiz_has_feedback($quiz->id) && $quiz->grade > 1.0E-7 && $quiz->sumgrades > 1.0E-7;
     $fakeattempt = new stdClass();
     $fakeattempt->preview = false;
     $fakeattempt->timefinish = $quiz->timeopen;
     $reviewoptions = quiz_get_reviewoptions($quiz, $fakeattempt, $context);
     $showgrades = $quiz->grade && $quiz->sumgrades && $reviewoptions->scores;
     $pageoptions = array();
     $pageoptions['id'] = $cm->id;
     $pageoptions['q'] = $quiz->id;
     $pageoptions['mode'] = 'overview';
     /// find out current groups mode
     $currentgroup = groups_get_activity_group($cm, true);
     $reporturl = new moodle_url($CFG->wwwroot . '/mod/quiz/report.php', $pageoptions);
     $qmsubselect = quiz_report_qm_filter_select($quiz);
     $mform = new mod_quiz_report_overview_settings($reporturl, compact('qmsubselect', 'quiz', 'currentgroup'));
     if ($fromform = $mform->get_data()) {
         $attemptsmode = $fromform->attemptsmode;
         if ($qmsubselect) {
             //control is not on the form if
             //the grading method is not set
             //to grade one attempt per user eg. for average attempt grade.
             $qmfilter = $fromform->qmfilter;
         } else {
             $qmfilter = 0;
         }
         set_user_preference('quiz_report_overview_detailedmarks', $fromform->detailedmarks);
         set_user_preference('quiz_report_pagesize', $fromform->pagesize);
         $detailedmarks = $fromform->detailedmarks;
         $pagesize = $fromform->pagesize;
     } else {
         $qmfilter = optional_param('qmfilter', 0, PARAM_INT);
         $attemptsmode = optional_param('attemptsmode', QUIZ_REPORT_ATTEMPTS_ALL, PARAM_INT);
         $detailedmarks = get_user_preferences('quiz_report_overview_detailedmarks', 1);
         $pagesize = get_user_preferences('quiz_report_pagesize', 0);
     }
     if ($attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL && $currentgroup) {
         $attemptsmode = QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH;
     }
     if (!$reviewoptions->scores) {
         $detailedmarks = 0;
     }
     if ($pagesize < 1) {
         $pagesize = QUIZ_REPORT_DEFAULT_PAGE_SIZE;
     }
     // We only want to show the checkbox to delete attempts
     // if the user has permissions and if the report mode is showing attempts.
     $candelete = has_capability('mod/quiz:deleteattempts', $context) && $attemptsmode != QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO;
     $displayoptions = array();
     $displayoptions['attemptsmode'] = $attemptsmode;
     $displayoptions['qmfilter'] = $qmfilter;
     $reporturlwithdisplayoptions = new moodle_url($CFG->wwwroot . '/mod/quiz/report.php', $pageoptions + $displayoptions);
     if ($groupmode = groups_get_activity_groupmode($cm)) {
         // Groups are being used
         if (!$download) {
             groups_print_activity_menu($cm, $reporturlwithdisplayoptions->out());
         }
     }
     // Print information on the number of existing attempts
     if (!$download) {
         //do not print notices when downloading
         if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) {
             echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>';
         }
     }
     $nostudents = false;
     if (!($students = get_users_by_capability($context, array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), '', '', '', '', '', '', false))) {
         notify(get_string('nostudentsyet'));
         $nostudents = true;
         $studentslist = '';
     } else {
         $studentslist = join(',', array_keys($students));
     }
     if (empty($currentgroup)) {
         // all users who can attempt quizzes
         $groupstudentslist = '';
         $allowedlist = $studentslist;
     } else {
         // all users who can attempt quizzes and who are in the currently selected group
         if (!($groupstudents = get_users_by_capability($context, 'mod/quiz:attempt', '', '', '', '', $currentgroup, '', false))) {
             notify(get_string('nostudentsingroup'));
             $nostudents = true;
             $groupstudents = array();
         }
         $groupstudentslist = join(',', array_keys($groupstudents));
         $allowedlist = $groupstudentslist;
     }
     if (!$nostudents || $attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL) {
         // Print information on the grading method and whether we are displaying
         //
         if (!$download) {
             //do not print notices when downloading
             if ($strattempthighlight = quiz_report_highlighting_grading_method($quiz, $qmsubselect, $qmfilter)) {
                 echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>';
             }
         }
         // Now check if asked download of data
         if ($download) {
             $filename = clean_filename("{$course->shortname} " . format_string($quiz->name, true));
         }
         // Define table columns
         $columns = array();
         $headers = array();
         if (!$download && $candelete) {
             $columns[] = 'checkbox';
             $headers[] = NULL;
         }
         if (!$download && $CFG->grade_report_showuserimage) {
             $columns[] = 'picture';
             $headers[] = '';
         }
         $columns[] = 'fullname';
         $headers[] = get_string('name');
         if ($CFG->grade_report_showuseridnumber) {
             $columns[] = 'idnumber';
             $headers[] = get_string('idnumber');
         }
         $columns[] = 'timestart';
         $headers[] = get_string('startedon', 'quiz');
         $columns[] = 'timefinish';
         $headers[] = get_string('timecompleted', 'quiz');
         $columns[] = 'duration';
         $headers[] = get_string('attemptduration', 'quiz');
         if ($showgrades) {
             $columns[] = 'sumgrades';
             $headers[] = get_string('grade', 'quiz') . '/' . $quiz->grade;
         }
         if ($detailedmarks) {
             // we want to display marks for all questions
             $questions = quiz_report_load_questions($quiz);
             foreach ($questions as $id => $question) {
                 // Ignore questions of zero length
                 $columns[] = 'qsgrade' . $id;
                 $headers[] = '#' . $question->number;
             }
         }
         if ($hasfeedback) {
             $columns[] = 'feedbacktext';
             $headers[] = get_string('feedback', 'quiz');
         }
         if (!$download) {
             // Set up the table
             $table = new flexible_table('mod-quiz-report-overview-report');
             $table->define_columns($columns);
             $table->define_headers($headers);
             $table->define_baseurl($reporturlwithdisplayoptions->out());
             $table->sortable(true);
             $table->collapsible(true);
             $table->column_suppress('picture');
             $table->column_suppress('fullname');
             $table->column_suppress('idnumber');
             $table->no_sorting('feedbacktext');
             $table->column_class('picture', 'picture');
             $table->column_class('fullname', 'bold');
             $table->column_class('sumgrades', 'bold');
             $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 == 'ODS') {
                 require_once "{$CFG->libdir}/odslib.class.php";
                 $filename .= ".ods";
                 // Creating a workbook
                 $workbook = new MoodleODSWorkbook("-");
                 // 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
                 $colnum = 0;
                 foreach ($headers as $item) {
                     $myxls->write(0, $colnum, $item, $formatbc);
                     $colnum++;
                 }
                 $rownum = 1;
             } 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');
                     $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");
                         echo implode("\t", $headers) . " \n";
                     }
                 }
             }
         }
         // Construct the SQL
         $select = 'SELECT ' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ' AS uniqueid, ';
         if ($qmsubselect) {
             $select .= "(CASE " . "   WHEN {$qmsubselect} THEN 1" . "   ELSE 0 " . "END) AS gradedattempt, ";
         }
         $select .= 'qa.uniqueid AS attemptuniqueid, qa.id AS attempt, ' . 'u.id AS userid, u.idnumber, u.firstname, u.lastname, u.picture, u.imagealt, ' . 'qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ';
         // This part is the same for all cases - join users and quiz_attempts tables
         $from = 'FROM ' . $CFG->prefix . 'user u ';
         $from .= 'LEFT JOIN ' . $CFG->prefix . 'quiz_attempts qa ON qa.userid = u.id AND qa.quiz = ' . $quiz->id;
         if ($qmsubselect && $qmfilter) {
             $from .= ' AND ' . $qmsubselect;
         }
         switch ($attemptsmode) {
             case QUIZ_REPORT_ATTEMPTS_ALL:
                 // Show all attempts, including students who are no longer in the course
                 $where = ' WHERE qa.id IS NOT NULL AND qa.preview = 0';
                 break;
             case QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH:
                 // Show only students with attempts
                 $where = ' WHERE u.id IN (' . $allowedlist . ') AND qa.preview = 0 AND qa.id IS NOT NULL';
                 break;
             case QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
                 // Show only students without attempts
                 $where = ' WHERE u.id IN (' . $allowedlist . ') AND qa.id IS NULL';
                 break;
             case QUIZ_REPORT_ATTEMPTS_ALL_STUDENTS:
                 // Show all students with or without attempts
                 $where = ' WHERE u.id IN (' . $allowedlist . ') AND (qa.preview = 0 OR qa.preview IS NULL)';
                 break;
         }
         $countsql = 'SELECT COUNT(DISTINCT(' . sql_concat('u.id', '\'#\'', 'COALESCE(qa.attempt, 0)') . ')) ' . $from . $where;
         // Add table joins so we can sort by question grade
         // unfortunately can't join all tables necessary to fetch all grades
         // to get the state for one question per attempt row we must join two tables
         // and there is a limit to how many joins you can have in one query. In MySQL it
         // is 61. This means that when having more than 29 questions the query will fail.
         // So we join just the tables needed to sort the attempts.
         if (!$download && ($sort = $table->get_sql_sort())) {
             if (!$download && $detailedmarks) {
                 $from .= ' ';
                 $sortparts = explode(',', $sort);
                 $matches = array();
                 foreach ($sortparts as $sortpart) {
                     $sortpart = trim($sortpart);
                     if (preg_match('/^qsgrade([0-9]+)/', $sortpart, $matches)) {
                         $qid = intval($matches[1]);
                         $select .= ", qs{$qid}.grade AS qsgrade{$qid}, qs{$qid}.event AS qsevent{$qid}, qs{$qid}.id AS qsid{$qid}";
                         $from .= "LEFT JOIN {$CFG->prefix}question_sessions qns{$qid} ON qns{$qid}.attemptid = qa.uniqueid AND qns{$qid}.questionid = {$qid} ";
                         $from .= "LEFT JOIN  {$CFG->prefix}question_states qs{$qid} ON qs{$qid}.id = qns{$qid}.newgraded ";
                     } else {
                         $newsort[] = $sortpart;
                     }
                 }
                 $select .= ' ';
             }
         }
         if ($download) {
             $sort = '';
         }
         // Fix some wired sorting
         if (empty($sort)) {
             $sort = ' ORDER BY uniqueid';
         } else {
             $sort = ' ORDER BY ' . $sort;
         }
         if (!$download) {
             // Add extra limits due to initials bar
             if ($table->get_sql_where()) {
                 $where .= ' AND ' . $table->get_sql_where();
             }
             if (!empty($countsql)) {
                 $totalinitials = count_records_sql($countsql);
                 if ($table->get_sql_where()) {
                     $countsql .= ' AND ' . $table->get_sql_where();
                 }
                 $total = count_records_sql($countsql);
             }
             $table->pagesize($pagesize, $total);
         }
         // Fetch the attempts
         if (!$download) {
             $attempts = get_records_sql($select . $from . $where . $sort, $table->get_page_start(), $table->get_page_size());
         } else {
             $attempts = get_records_sql($select . $from . $where . $sort);
         }
         // Build table rows
         if (!$download) {
             $table->initialbars($totalinitials > 20);
         }
         if ($attempts) {
             if ($detailedmarks) {
                 //get all the attempt ids we want to display on this page
                 //or to export for download.
                 $attemptids = array();
                 foreach ($attempts as $attempt) {
                     if ($attempt->attemptuniqueid > 0) {
                         $attemptids[] = $attempt->attemptuniqueid;
                     }
                 }
                 $gradedstatesbyattempt = quiz_get_newgraded_states($attemptids, true, 'qs.id, qs.grade, qs.event, qs.question, qs.attempt');
             }
             foreach ($attempts as $attempt) {
                 // Username columns.
                 $row = array();
                 if (in_array('checkbox', $columns)) {
                     if ($attempt->attempt) {
                         $row[] = '<input type="checkbox" name="attemptid[]" value="' . $attempt->attempt . '" />';
                     } else {
                         $row[] = '';
                     }
                 }
                 if (in_array('picture', $columns)) {
                     $attempt->id = $attempt->userid;
                     $picture = print_user_picture($attempt, $course->id, NULL, false, true);
                     $row[] = $picture;
                 }
                 if (!$download) {
                     $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $attempt->userid . '&amp;course=' . $course->id . '">' . fullname($attempt) . '</a>';
                     $row[] = $userlink;
                 } else {
                     $row[] = fullname($attempt);
                 }
                 if (in_array('idnumber', $columns)) {
                     $row[] = $attempt->idnumber;
                 }
                 // Timing columns.
                 if ($attempt->attempt) {
                     $startdate = userdate($attempt->timestart, $strtimeformat);
                     if (!$download) {
                         $row[] = '<a href="review.php?q=' . $quiz->id . '&amp;attempt=' . $attempt->attempt . '">' . $startdate . '</a>';
                     } else {
                         $row[] = $startdate;
                     }
                     if ($attempt->timefinish) {
                         $timefinish = userdate($attempt->timefinish, $strtimeformat);
                         $duration = format_time($attempt->duration);
                         if (!$download) {
                             $row[] = '<a href="review.php?q=' . $quiz->id . '&amp;attempt=' . $attempt->attempt . '">' . $timefinish . '</a>';
                         } else {
                             $row[] = $timefinish;
                         }
                         $row[] = $duration;
                     } else {
                         $row[] = '-';
                         $row[] = get_string('unfinished', 'quiz');
                     }
                 } else {
                     $row[] = '-';
                     $row[] = '-';
                     $row[] = '-';
                 }
                 // Grades columns.
                 if ($showgrades) {
                     if ($attempt->timefinish) {
                         $grade = quiz_rescale_grade($attempt->sumgrades, $quiz);
                         if (!$download) {
                             $gradehtml = '<a href="review.php?q=' . $quiz->id . '&amp;attempt=' . $attempt->attempt . '">' . $grade . '</a>';
                             if ($qmsubselect && $attempt->gradedattempt) {
                                 $gradehtml = '<div class="highlight">' . $gradehtml . '</div>';
                             }
                             $row[] = $gradehtml;
                         } else {
                             $row[] = $grade;
                         }
                     } else {
                         $row[] = '-';
                     }
                 }
                 if ($detailedmarks) {
                     if (empty($attempt->attempt)) {
                         foreach ($questions as $question) {
                             $row[] = '-';
                         }
                     } else {
                         foreach ($questions as $questionid => $question) {
                             $stateforqinattempt = $gradedstatesbyattempt[$attempt->attemptuniqueid][$questionid];
                             if (question_state_is_graded($stateforqinattempt)) {
                                 $grade = quiz_rescale_grade($stateforqinattempt->grade, $quiz);
                             } else {
                                 $grade = '--';
                             }
                             if (!$download) {
                                 $grade = $grade . '/' . quiz_rescale_grade($question->grade, $quiz);
                                 $row[] = link_to_popup_window('/mod/quiz/reviewquestion.php?state=' . $stateforqinattempt->id . '&amp;number=' . $question->number, 'reviewquestion', $grade, 450, 650, $strreviewquestion, 'none', true);
                             } else {
                                 $row[] = $grade;
                             }
                         }
                     }
                 }
                 // Feedback column.
                 if ($hasfeedback) {
                     if ($attempt->timefinish) {
                         $row[] = quiz_report_feedback_for_grade(quiz_rescale_grade($attempt->sumgrades, $quiz), $quiz->id);
                     } else {
                         $row[] = '-';
                     }
                 }
                 if (!$download) {
                     $table->add_data($row);
                 } else {
                     if ($download == 'Excel' or $download == 'ODS') {
                         $colnum = 0;
                         foreach ($row as $item) {
                             $myxls->write($rownum, $colnum, $item, $format);
                             $colnum++;
                         }
                         $rownum++;
                     } else {
                         if ($download == 'CSV') {
                             $text = implode("\t", $row);
                             echo $text . " \n";
                         }
                     }
                 }
             }
             //end of adding data from attempts data to table / download
             //now add averages :
             if (!$download && $attempts) {
                 $averagesql = "SELECT AVG(qg.grade) AS grade " . "FROM {$CFG->prefix}quiz_grades qg " . "WHERE quiz=" . $quiz->id;
                 $table->add_separator();
                 if ($groupstudentslist) {
                     $groupaveragesql = $averagesql . " AND qg.userid IN ({$groupstudentslist})";
                     $groupaverage = get_record_sql($groupaveragesql);
                     $groupaveragerow = array('fullname' => get_string('groupavg', 'grades'), 'sumgrades' => round($groupaverage->grade, $quiz->decimalpoints), 'feedbacktext' => quiz_report_feedback_for_grade($groupaverage->grade, $quiz->id));
                     if ($detailedmarks && $qmsubselect) {
                         $avggradebyq = quiz_get_average_grade_for_questions($quiz, $groupstudentslist);
                         $groupaveragerow += quiz_format_average_grade_for_questions($avggradebyq, $questions, $quiz, $download);
                     }
                     $table->add_data_keyed($groupaveragerow);
                 }
                 $overallaverage = get_record_sql($averagesql . " AND qg.userid IN ({$studentslist})");
                 $overallaveragerow = array('fullname' => get_string('overallaverage', 'grades'), 'sumgrades' => round($overallaverage->grade, $quiz->decimalpoints), 'feedbacktext' => quiz_report_feedback_for_grade($overallaverage->grade, $quiz->id));
                 if ($detailedmarks && $qmsubselect) {
                     $avggradebyq = quiz_get_average_grade_for_questions($quiz, $studentslist);
                     $overallaveragerow += quiz_format_average_grade_for_questions($avggradebyq, $questions, $quiz, $download);
                 }
                 $table->add_data_keyed($overallaveragerow);
             }
             if (!$download) {
                 // Start form
                 echo '<div id="tablecontainer">';
                 echo '<form id="attemptsform" method="post" action="' . $reporturlwithdisplayoptions->out(true) . '" onsubmit="return confirm(\'' . $strreallydel . '\');">';
                 echo '<div style="display: none;">';
                 echo $reporturlwithdisplayoptions->hidden_params_out();
                 echo '</div>';
                 echo '<div>';
                 // Print table
                 $table->print_html();
                 // Print "Select all" etc.
                 if (!empty($attempts) && $candelete) {
                     echo '<table id="commands">';
                     echo '<tr><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;';
                     echo '<input type="submit" value="' . get_string('deleteselected', 'quiz_overview') . '"/>';
                     echo '</td></tr></table>';
                 }
                 // Close form
                 echo '</div>';
                 echo '</form></div>';
                 if (!empty($attempts)) {
                     echo '<table class="boxaligncenter"><tr>';
                     echo '<td>';
                     print_single_button($reporturl->out(true), $pageoptions + $displayoptions + array('download' => 'ODS'), get_string('downloadods'));
                     echo "</td>\n";
                     echo '<td>';
                     print_single_button($reporturl->out(true), $pageoptions + $displayoptions + array('download' => 'Excel'), get_string('downloadexcel'));
                     echo "</td>\n";
                     echo '<td>';
                     print_single_button($reporturl->out(true), $pageoptions + $displayoptions + array('download' => 'CSV'), get_string('downloadtext'));
                     echo "</td>\n";
                     echo "<td>";
                     helpbutton('overviewdownload', get_string('overviewdownload', 'quiz_overview'), 'quiz');
                     echo "</td>\n";
                     echo '</tr></table>';
                 }
             }
         } else {
             if (!$download) {
                 $table->print_html();
             }
         }
         if ($download == 'Excel' or $download == 'ODS') {
             $workbook->close();
             exit;
         } else {
             if ($download == 'CSV') {
                 exit;
             }
         }
     }
     if (!$download) {
         // Print display options
         $mform->set_data($displayoptions + compact('detailedmarks', 'pagesize'));
         $mform->display();
         //should be quicker than a COUNT to test if there is at least one record :
         if ($showgrades && record_exists('quiz_grades', 'quiz', $quiz->id)) {
             $imageurl = $CFG->wwwroot . '/mod/quiz/report/overview/overviewgraph.php?id=' . $quiz->id;
             print_heading(get_string('overviewreportgraph', 'quiz_overview'));
             echo '<div class="mdl-align"><img src="' . $imageurl . '" alt="' . get_string('overviewreportgraph', 'quiz_overview') . '" /></div>';
         }
     }
     return true;
 }
Example #24
0
/** Download data in ODS format
  *
  * @param array $fields Array of column headings
  * @param string $datarows Array of data to populate table with
  * @param string $file Name of file for exportig
  * @return Returns the ODS file
 */
function facetoface_download_ods($fields, $datarows, $file=null) {
    global $CFG, $DB;

    require_once("$CFG->libdir/odslib.class.php");
    $filename = clean_filename($file . '.ods');

    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");

    $workbook = new MoodleODSWorkbook('-');
    $workbook->send($filename);

    $worksheet = array();

    $worksheet[0] = $workbook->add_worksheet('');
    $row = 0;
    $col = 0;

    foreach ($fields as $field) {
        $worksheet[0]->write($row, $col, strip_tags($field));
        $col++;
    }
    $row++;

    $numfields = count($fields);

    foreach ($datarows as $record) {
        for($col=0; $col<$numfields; $col++) {
            if (isset($record[$col])) {
                $worksheet[0]->write($row, $col, html_entity_decode($record[$col], ENT_COMPAT, 'UTF-8'));
            }
        }
        $row++;
    }

    $workbook->close();
    die;
}
Example #25
0
        $results[$surveyanswer->userid][$questionid]['answer1'] = $surveyanswer->answer1;
        $results[$surveyanswer->userid][$questionid]['answer2'] = $surveyanswer->answer2;
    }
}

// Output the file as a valid ODS spreadsheet if required
$coursecontext = context_course::instance($course->id);
$courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));

if ($type == "ods") {
    require_once("$CFG->libdir/odslib.class.php");

/// Calculate file name
    $downloadfilename = clean_filename(strip_tags($courseshortname.' '.format_string($survey->name, true))).'.ods';
/// Creating a workbook
    $workbook = new MoodleODSWorkbook("-");
/// Sending HTTP headers
    $workbook->send($downloadfilename);
/// Creating the first worksheet
    $myxls = $workbook->add_worksheet(textlib::substr(strip_tags(format_string($survey->name,true)), 0, 31));

    $header = array("surveyid","surveyname","userid","firstname","lastname","email","idnumber","time", "notes");
    $col=0;
    foreach ($header as $item) {
        $myxls->write_string(0,$col++,$item);
    }

    foreach ($nestedorder as $key => $nestedquestions) {
        foreach ($nestedquestions as $key2 => $qid) {
            $question = $questions[$qid];
            if ($question->type == "0" || $question->type == "1" || $question->type == "3" || $question->type == "-1")  {
Example #26
0
function exporttotableed($data, $filename, $format)
{
    global $CFG;
    if ($format === 'excel') {
        require_once "{$CFG->libdir}/excellib.class.php";
        $filename .= ".xls";
        $workbook = new MoodleExcelWorkbook("-");
    } else {
        require_once "{$CFG->libdir}/odslib.class.php";
        $filename .= ".ods";
        $workbook = new MoodleODSWorkbook("-");
    }
    // Sending HTTP headers.
    $workbook->send($filename);
    // Creating the first worksheet.
    $myxls = $workbook->add_worksheet('Attendances');
    // Format types.
    $formatbc = $workbook->add_format();
    $formatbc->set_bold(1);
    $myxls->write(0, 0, get_string('course'), $formatbc);
    $myxls->write(0, 1, $data->course);
    $myxls->write(1, 0, get_string('group'), $formatbc);
    $myxls->write(1, 1, $data->group);
    $i = 3;
    $j = 0;
    foreach ($data->tabhead as $cell) {
        $myxls->write($i, $j++, $cell, $formatbc);
    }
    $i++;
    $j = 0;
    foreach ($data->table as $row) {
        foreach ($row as $cell) {
            $myxls->write($i, $j++, $cell);
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
}
 public function view_issued_certificates(moodle_url $url)
 {
     global $OUTPUT, $DB, $CFG;
     // Declare some variables
     $strcertificates = get_string('modulenameplural', 'simplecertificate');
     $strcertificate = get_string('modulename', 'simplecertificate');
     $strto = html_writer::link($url->out(false, array('orderby' => 'username')), get_string('awardedto', 'simplecertificate'));
     $strdate = html_writer::link($url->out(false, array('orderby' => 'issuedate')), get_string('receiveddate', 'simplecertificate'));
     $strgrade = get_string('grade', 'simplecertificate');
     $strcode = get_string('code', 'simplecertificate');
     $strreport = get_string('report', 'simplecertificate');
     $groupmode = groups_get_activity_groupmode($this->get_course_module());
     $page = $url->get_param('page');
     $perpage = $url->get_param('perpage');
     $orderby = $url->get_param('orderby');
     $usercount = 0;
     $users = $this->get_issued_certificate_users($orderby, $groupmode);
     if ($users) {
         $usercount = count($users);
         $users = array_slice($users, intval($page * $perpage), $perpage);
     }
     if (!$url->get_param('action')) {
         echo $OUTPUT->header();
         $this->show_tabs($url);
         if ($groupmode) {
             groups_get_activity_group($this->coursemodule, true);
         }
         groups_print_activity_menu($this->coursemodule, $url);
         if (!$users) {
             notify(get_string('nocertificatesissued', 'simplecertificate'));
             echo $OUTPUT->footer();
             exit;
         }
         // Create the table for the users
         $table = new html_table();
         $table->width = "95%";
         $table->tablealign = "center";
         $table->head = array($strto, $strdate, $strgrade, $strcode);
         $table->align = array("left", "left", "center", "center");
         foreach ($users as $user) {
             $name = $OUTPUT->user_picture($user) . fullname($user);
             $date = userdate($user->timecreated) . simplecertificate_print_issue_certificate_file($this->get_issue($user));
             $code = $user->code;
             $table->data[] = array($name, $date, $this->get_grade($user->id), $code);
         }
         // Create table to store buttons
         $tablebutton = new html_table();
         $tablebutton->attributes['class'] = 'downloadreport';
         $btndownloadods = $OUTPUT->single_button($url->out_as_local_url(false, array('action' => 'download', 'type' => 'ods')), get_string("downloadods"));
         $btndownloadxls = $OUTPUT->single_button($url->out_as_local_url(false, array('action' => 'download', 'type' => 'xls')), get_string("downloadexcel"));
         $btndownloadtxt = $OUTPUT->single_button($url->out_as_local_url(false, array('action' => 'download', 'type' => 'txt')), get_string("downloadtext"));
         $tablebutton->data[] = array($btndownloadods, $btndownloadxls, $btndownloadtxt);
         echo $OUTPUT->paging_bar($usercount, $page, $perpage, $url);
         echo '<br />';
         echo html_writer::table($table);
         echo html_writer::tag('div', html_writer::table($tablebutton), array('style' => 'margin:auto; width:50%'));
     } else {
         if ($url->get_param('action') == 'download') {
             $page = $perpage = 0;
             $type = $url->get_param('type');
             // Calculate file name
             $filename = clean_filename($this->get_instance()->coursename . '-' . strip_tags(format_string($this->get_instance()->name, true)) . '.' . strip_tags(format_string($type, true)));
             switch ($type) {
                 case 'ods':
                     require_once "{$CFG->libdir}/odslib.class.php";
                     // Creating a workbook
                     $workbook = new MoodleODSWorkbook("-");
                     // Send HTTP headers
                     $workbook->send(format_text($filename, true));
                     // Creating the first worksheet
                     $myxls = $workbook->add_worksheet($strreport);
                     // Print names of all the fields
                     $myxls->write_string(0, 0, get_string("fullname"));
                     $myxls->write_string(0, 1, get_string("idnumber"));
                     $myxls->write_string(0, 2, get_string("group"));
                     $myxls->write_string(0, 3, $strdate);
                     $myxls->write_string(0, 4, $strgrade);
                     $myxls->write_string(0, 5, $strcode);
                     // Generate the data for the body of the spreadsheet
                     $i = 0;
                     $row = 1;
                     if ($users) {
                         foreach ($users as $user) {
                             $myxls->write_string($row, 0, fullname($user));
                             $studentid = !empty($user->idnumber) ? $user->idnumber : " ";
                             $myxls->write_string($row, 1, $studentid);
                             $ug2 = '';
                             if ($usergrps = groups_get_all_groups($this->get_course()->id, $user->id)) {
                                 foreach ($usergrps as $ug) {
                                     $ug2 = $ug2 . $ug->name;
                                 }
                             }
                             $myxls->write_string($row, 2, $ug2);
                             $myxls->write_string($row, 3, userdate($user->timecreated));
                             $myxls->write_string($row, 4, $this->get_grade($user->id));
                             $myxls->write_string($row, 5, $user->code);
                             $row++;
                         }
                         $pos = 5;
                     }
                     // Close the workbook
                     $workbook->close();
                     break;
                 case 'xls':
                     require_once "{$CFG->libdir}/excellib.class.php";
                     // Creating a workbook
                     $workbook = new MoodleExcelWorkbook("-");
                     // Send HTTP headers
                     $workbook->send(format_text($filename, true));
                     // Creating the first worksheet
                     $myxls = $workbook->add_worksheet($strreport);
                     // Print names of all the fields
                     $myxls->write_string(0, 0, get_string("fullname"));
                     $myxls->write_string(0, 1, get_string("idnumber"));
                     $myxls->write_string(0, 2, get_string("group"));
                     $myxls->write_string(0, 3, $strdate);
                     $myxls->write_string(0, 4, $strgrade);
                     $myxls->write_string(0, 5, $strcode);
                     // Generate the data for the body of the spreadsheet
                     $i = 0;
                     $row = 1;
                     if ($users) {
                         foreach ($users as $user) {
                             $myxls->write_string($row, 0, fullname($user));
                             $studentid = !empty($user->idnumber) ? $user->idnumber : " ";
                             $myxls->write_string($row, 1, $studentid);
                             $ug2 = '';
                             if ($usergrps = groups_get_all_groups($this->get_course()->id, $user->id)) {
                                 foreach ($usergrps as $ug) {
                                     $ug2 = $ug2 . $ug->name;
                                 }
                             }
                             $myxls->write_string($row, 2, $ug2);
                             $myxls->write_string($row, 3, userdate($user->timecreated));
                             $myxls->write_string($row, 4, $this->get_grade($user->id));
                             $myxls->write_string($row, 5, $user->code);
                             $row++;
                         }
                         $pos = 5;
                     }
                     // Close the workbook
                     $workbook->close();
                     break;
                 case 'txt':
                     header("Content-Type: application/download\n");
                     header("Content-Disposition: attachment; filename=\"" . format_text($filename, true) . "\"");
                     header("Expires: 0");
                     header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                     header("Pragma: public");
                     // Print names of all the fields
                     echo get_string("fullname") . "\t" . get_string("idnumber") . "\t";
                     echo get_string("group") . "\t";
                     echo $strdate . "\t";
                     echo $strgrade . "\t";
                     echo $strcode . "\n";
                     // Generate the data for the body of the spreadsheet
                     $i = 0;
                     $row = 1;
                     if ($users) {
                         foreach ($users as $user) {
                             echo fullname($user);
                             $studentid = " ";
                             if (!empty($user->idnumber)) {
                                 $studentid = $user->idnumber;
                             }
                             echo "\t" . $studentid . "\t";
                             $ug2 = '';
                             if ($usergrps = groups_get_all_groups($this->get_course()->id, $user->id)) {
                                 foreach ($usergrps as $ug) {
                                     $ug2 = $ug2 . $ug->name;
                                 }
                             }
                             echo $ug2 . "\t";
                             echo userdate($user->timecreated) . "\t";
                             echo $this->get_grade($user->id) . "\t";
                             echo $user->code . "\n";
                             $row++;
                         }
                     }
                     break;
             }
             exit;
         }
     }
     echo $OUTPUT->footer();
 }
Example #28
0
    if ($groupmode) {
        groups_get_activity_group($cm, true);
        groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/choice/report.php?id=' . $id);
    }
} else {
    $groupmode = groups_get_activity_groupmode($cm);
}
// Check if we want to include responses from inactive users.
$onlyactive = $choice->includeinactive ? false : true;
$users = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
if ($download == "ods" && has_capability('mod/choice:downloadresponses', $context)) {
    require_once "{$CFG->libdir}/odslib.class.php";
    /// Calculate file name
    $filename = clean_filename("{$course->shortname} " . strip_tags(format_string($choice->name, true))) . '.ods';
    /// Creating a workbook
    $workbook = new MoodleODSWorkbook("-");
    /// Send HTTP headers
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls = $workbook->add_worksheet($strresponses);
    /// Print names of all the fields
    $myxls->write_string(0, 0, get_string("lastname"));
    $myxls->write_string(0, 1, get_string("firstname"));
    $myxls->write_string(0, 2, get_string("idnumber"));
    $myxls->write_string(0, 3, get_string("group"));
    $myxls->write_string(0, 4, get_string("choice", "choice"));
    /// generate the data for the body of the spreadsheet
    $i = 0;
    $row = 1;
    if ($users) {
        foreach ($users as $option => $userid) {
Example #29
0
                            }
                        }
                    }
                }
            }
        }
    }
}
// a new Moodle nesting record? ;-)
/// OK, we have all the data, now present it to the user
if ($download == "ods" and confirm_sesskey()) {
    require_once "../lib/odslib.class.php";
    /// Calculate file name
    $downloadfilename = clean_filename("{$course->shortname} {$strgrades}.ods");
    /// Creating a workbook
    $workbook = new MoodleODSWorkbook("-");
    /// Sending HTTP headers
    $workbook->send($downloadfilename);
    /// Adding the worksheet
    $myxls =& $workbook->add_worksheet($strgrades);
    /// Print names of all the fields
    $myxls->write_string(0, 0, get_string("firstname"));
    $myxls->write_string(0, 1, get_string("lastname"));
    $myxls->write_string(0, 2, get_string("idnumber"));
    $myxls->write_string(0, 3, get_string("institution"));
    $myxls->write_string(0, 4, get_string("department"));
    $myxls->write_string(0, 5, get_string("email"));
    $pos = 6;
    foreach ($columns as $column) {
        $myxls->write_string(0, $pos++, strip_tags($column));
    }