/**
  * Export a report in this format
  *
  * @param  string  $query         Final form of the main report query
  * @param  string  $storage_path  Path on the file system to save the output to,
  *                                or NULL if sending to browser
  * @param  $filename              Filename to use when sending to browser
  */
 function export($query, $storage_path, $filename)
 {
     global $CFG;
     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('studentprogress', 'reportstudentprogress');
     $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');
     $rownum = 0;
     $colnum = 0;
     foreach ($this->report->headers as $header) {
         $myxls->write($rownum, $colnum++, $header, $formatbc);
     }
     foreach ($this->report->data as $datum) {
         if (!is_object($datum)) {
             continue;
         }
         $rownum++;
         $colnum = 0;
         foreach ($this->headers as $id => $header) {
             if (isset($datum->{$id})) {
                 $myxls->write($rownum, $colnum++, $datum->{$id}, $format);
             } else {
                 $myxls->write($rownum, $colnum++, '', $format);
             }
         }
     }
     $workbook->close();
 }
Пример #2
0
        }
        $attempt = new stdClass();
        $attempt->passed = $passed;
        $attempt->persent = $newpoint;
        $attempt->id = $ida->id;
        $DB->update_record('reader_attempts', $attempt);
    }
    $adjustscorestext = get_string('done', 'reader');
}
/*
* EXCEL
*/
if ($excel) {
    $workbook = new MoodleExcelWorkbook("-");
    $myxls =& $workbook->add_worksheet('report');
    $format =& $workbook->add_format();
    $format->set_bold(0);
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    if (!empty($grid)) {
        $grname = groups_get_group_name($grid);
    } else {
        $grname = "all";
    }
    $exceldata['time'] = date("d.M.Y");
    $exceldata['course_shotname'] = str_replace(" ", "-", $course->shortname);
    $exceldata['groupname'] = str_replace(" ", "-", $grname);
    if ($act != "exportstudentrecords") {
        $workbook->send('report_' . $exceldata['time'] . '_' . $exceldata['course_shotname'] . '_' . $exceldata['groupname'] . '.xls');
    } else {
        header("Content-Type: text/plain; filename=\"{$COURSE->shortname}_attempts.txt\"");
Пример #3
0
/** Download data in XLS 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 Excel file
  */
function facetoface_download_xls($fields, $datarows, $file=null) {
    global $CFG, $DB;

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

    $filename = clean_filename($file . '.xls');

    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 MoodleExcelWorkbook('-');
    $workbook->send($filename);

    $worksheet = array();

    $worksheet[0] = $workbook->add_worksheet('');
    $row = 0;
    $col = 0;
    $dateformat = $workbook->add_format();
    $dateformat->set_num_format('dd mmm yyyy');
    $datetimeformat = $workbook->add_format();
    $datetimeformat->set_num_format('dd mmm yyyy h:mm');

    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++) {
            $worksheet[0]->write($row, $col, html_entity_decode($record[$col], ENT_COMPAT, 'UTF-8'));
        }
        $row++;
    }

    $workbook->close();
    die;
}
Пример #4
0
         $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();
Пример #5
0
 /**
  * (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;
 }
Пример #6
0
} else {
    $filename .= "AllPartners_";
}
if ($shid != 0) {
    $scheduler = $DB->get_record("scheduler", array("id" => $shid));
    $filename .= $scheduler->name . "_";
}
$filename .= date("Ymd", time());
$filename .= ".xls";
$workbook = new MoodleExcelWorkbook("-");
/// Sending HTTP headers
$workbook->send($filename);
/// Creating the first worksheet
$myxls =& $workbook->add_worksheet('Show appointments');
/// format types
$formatbc =& $workbook->add_format();
$formatbc->set_bold(1);
$myxls->write(0, 0, 'Group', $formatbc);
$myxls->write(0, 1, 'Partner', $formatbc);
$myxls->write(0, 2, 'Given name', $formatbc);
$myxls->write(0, 3, 'Family name', $formatbc);
$myxls->write(0, 4, 'Username', $formatbc);
$myxls->write(0, 5, 'Date/Time (partner)', $formatbc);
$myxls->write(0, 6, 'Date/Time (student)', $formatbc);
$myxls->write(0, 7, 'Scheduler', $formatbc);
$myxls->write(0, 8, 'Comment', $formatbc);
$data = array();
$datareport = array();
$datareport2 = array();
$users = array();
$appointmentarray = array();
Пример #7
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'));
     }
 }
Пример #8
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;
 }
Пример #9
0
/**
 * 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;
}
function ExportToExcel($data)
{
    global $CFG;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "EMBA_students_reg_report:.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('EMBA_reg_report');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    $header1 =& $workbook->add_format();
    $header1->set_bold(1);
    // Make it bold
    $header1->set_align('center');
    // Align text to center
    $header1->set_size(14);
    //$header1->set_fg_color(22);
    $header2 =& $workbook->add_format();
    $header2->set_bold(1);
    // Make it bold
    $header2->set_align('center');
    // Align text to center
    $header2->set_size(12);
    //$header2->set_fg_color(23);
    $normal =& $workbook->add_format();
    $normal->set_bold(0);
    $normal->set_align('center');
    $normal->set_size(10);
    $name =& $workbook->add_format();
    $name->set_bold(0);
    $name->set_size(10);
    $grey_code_f =& $workbook->add_format();
    $grey_code_f->set_bold(0);
    // Make it bold
    $grey_code_f->set_size(12);
    $grey_code_f->set_fg_color(22);
    $grey_code_f->set_align('center');
    //$formatbc->set_size(14);
    $myxls->write(1, 0, "EMBA Students Registration Report", $header1);
    $myxls->write(4, 0, 'Duration');
    $myxls->write(4, 1, $data->duration, $formatbc);
    $i = 6;
    $j = 0;
    foreach ($data->head as $heading) {
        $heading = str_replace('<br/>', '', $heading);
        $heading = trim($heading);
        $myxls->write_string($i, $j, $heading, $header2);
        // $myxls->set_column($pos,$pos,(strlen($grade_item->get_name()))+4);
        $col_size = strlen($heading);
        $col_size += 6;
        if (preg_match('/^NAME/i', $heading)) {
            $col_size = 20;
        }
        $myxls->set_column($j, $j, $col_size);
        $j++;
    }
    $myxls->merge_cells(1, 0, 1, $j - 1);
    $myxls->merge_cells(2, 0, 2, $j - 1);
    $myxls->merge_cells(4, 1, 4, 3);
    $myxls->set_row(1, 25);
    $i = 7;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                //if($cell>25.99){
                //	$myxls->write_number($i, $j++, $cell,$grey_code_f);
                //}
                //else{
                $myxls->write_number($i, $j++, $cell, $normal);
                //}
            } else {
                if (preg_match('/^!!/', $cell)) {
                    $cell = str_replace("!!", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $grey_code_f);
                } else {
                    if ($j == 2) {
                        $myxls->write_string($i, $j++, $cell, $name);
                    } else {
                        $myxls->write_string($i, $j++, $cell, $normal);
                    }
                }
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #11
0
 /**
  * fills workbook (either XLS or ODS) with data
  *
  * @param MoodleExcelWorkbook $workbook workbook to put data into
  */
 public function fill_workbook(&$workbook)
 {
     global $DB;
     $time = time();
     $time = userdate($time);
     $worksheet = $workbook->add_worksheet($time);
     $headline_prop = array('size' => 12, 'bold' => 1, 'HAlign' => 'center', 'bottom' => 1, 'VAlign' => 'vcenter');
     $headline_format = $workbook->add_format($headline_prop);
     $headline_format->set_left(1);
     $headline_format->set_align('center');
     $headline_format->set_align('vcenter');
     $headline_first = $workbook->add_format($headline_prop);
     $headline_first->set_align('center');
     $headline_first->set_align('vcenter');
     unset($headline_prop['bottom']);
     $hdrleft = $workbook->add_format($headline_prop);
     $hdrleft->set_align('right');
     $hdrleft->set_align('vcenter');
     unset($headline_prop['bold']);
     $hdrright = $workbook->add_format($headline_prop);
     $hdrright->set_align('left');
     $hdrright->set_align('vcenter');
     $text_prop = array('size' => 10, 'align' => 'left');
     $text = $workbook->add_format($text_prop);
     $text->set_left(1);
     $text->set_align('vcenter');
     $text_first = $workbook->add_format($text_prop);
     $text_first->set_align('vcenter');
     $line = 0;
     //write header
     for ($i = 0; $i < count($this->header); $i += 2) {
         $worksheet->write_string($line, 0, $this->header[$i], $hdrleft);
         $worksheet->write_string($line, 1, $this->header[$i + 1], $hdrright);
         $line++;
     }
     $line++;
     // table header
     $i = 0;
     $first = true;
     foreach ($this->titles as $key => $header) {
         if ($first) {
             $worksheet->write_string($line, $i, $header, $headline_first);
             $first = false;
         } else {
             $worksheet->write_string($line, $i, $header, $headline_format);
             $first = false;
         }
         $i++;
     }
     // data
     $prev = $this->data[0];
     foreach ($this->data as $row) {
         $first = true;
         $line++;
         $i = 0;
         foreach ($row as $idx => $cell) {
             if (is_null($cell['data'])) {
                 $cell['data'] = $prev[$idx]['data'];
             }
             if ($first) {
                 $worksheet->write_string($line, $i, $cell['data'], $text_first);
                 $first = false;
             } else {
                 $worksheet->write_string($line, $i, $cell['data'], $text);
             }
             $prev[$idx] = $cell;
             $i++;
         }
     }
 }
Пример #12
0
 /**
  * Get the data needed for a downloadable version of the report (all data,
  * no paging necessary) and format it accordingly for the download file
  * type.
  *
  * NOTE: It is expected that the valid format types will be overridden in
  * an extended report class as the array is empty by default.
  *
  * @param string $format A valid format type.
  */
 function download($format)
 {
     global $CFG;
     $output = '';
     if (empty($this->data)) {
         return $output;
     }
     $filename = !empty($this->title) ? $this->title : 'report_download';
     switch ($format) {
         case 'csv':
             $filename .= '.csv';
             header("Content-Transfer-Encoding: ascii");
             header("Content-Disposition: attachment; filename={$filename}");
             header("Content-Type: text/comma-separated-values");
             $row = array();
             foreach ($this->headers as $header) {
                 $row[] = $this->csv_escape_string(strip_tags($header));
             }
             echo implode(',', $row) . "\n";
             foreach ($this->data as $datum) {
                 if (!is_object($datum)) {
                     continue;
                 }
                 $row = array();
                 foreach ($this->headers as $id => $header) {
                     if (isset($datum->{$id})) {
                         $row[] = $this->csv_escape_string($datum->{$id});
                     } else {
                         $row[] = '""';
                     }
                 }
                 echo implode(',', $row) . "\n";
             }
             break;
         case '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('studentprogress', 'reportstudentprogress');
             $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');
             $rownum = 0;
             $colnum = 0;
             foreach ($this->headers as $header) {
                 $myxls->write($rownum, $colnum++, $header, $formatbc);
             }
             foreach ($this->data as $datum) {
                 if (!is_object($datum)) {
                     continue;
                 }
                 $rownum++;
                 $colnum = 0;
                 foreach ($this->headers as $id => $header) {
                     if (isset($datum->{$id})) {
                         $myxls->write($rownum, $colnum++, $datum->{$id}, $format);
                     } else {
                         $myxls->write($rownum, $colnum++, '', $format);
                     }
                 }
             }
             $workbook->close();
             break;
         case 'pdf':
             require_once $CFG->libdir . '/fpdf/fpdf.php';
             $filename .= '.pdf';
             $newpdf = new FPDF('L', 'in', 'letter');
             $marginx = 0.75;
             $marginy = 0.75;
             $newpdf->setMargins($marginx, $marginy);
             $newpdf->SetFont('Arial', '', 9);
             $newpdf->AddPage();
             $newpdf->SetFont('Arial', '', 16);
             $newpdf->MultiCell(0, 0.2, $this->title, 0, 'C');
             $newpdf->Ln(0.2);
             $newpdf->SetFont('Arial', '', 8);
             $newpdf->SetFillColor(225, 225, 225);
             $heights = array();
             $widths = array();
             $hmap = array();
             $rownum = 0;
             /// PASS 1 - Calculate sizes.
             foreach ($this->headers as $id => $header) {
                 $widths[$id] = $newpdf->GetStringWidth($header) + 0.2;
             }
             $row = 0;
             foreach ($this->data as $datum) {
                 if (!isset($heights[$row])) {
                     $heights[$row] = 0;
                 }
                 foreach ($this->headers as $id => $header) {
                     if (isset($datum->{$id})) {
                         $width = $newpdf->GetStringWidth($datum->{$id}) + 0.2;
                         if ($width > $widths[$id]) {
                             $lines = ceil($width / $widths[$id]);
                             $widths[$id] = $width;
                         } else {
                             $lines = 1;
                         }
                         $height = $lines * 0.2;
                         if ($height > $heights[$row]) {
                             $heights[$row] = $height;
                         }
                     }
                 }
                 $row++;
             }
             /// Calculate the width of the table...
             $twidth = 0;
             foreach ($widths as $width) {
                 $twidth += $width;
             }
             /// Readjust the left margin according to the total width...
             $marginx = (11.0 - $twidth) / 2.0;
             $newpdf->setMargins($marginx, $marginy);
             foreach ($this->headers as $id => $header) {
                 $text = str_replace(' ', "\n", $header);
                 $newpdf->Cell($widths[$id], 0.2, "{$text}", 1, 0, 'C', 1);
             }
             $newpdf->Ln();
             $row = 0;
             foreach ($this->data as $datum) {
                 if (is_array($datum) && strtolower($datum[0]) == 'hr') {
                     $curx = $newpdf->GetX();
                     $cury = $newpdf->GetY() + 0.1;
                     $endx = 0;
                     $endy = $cury;
                     foreach ($widths as $width) {
                         $endx += $width;
                     }
                     $newpdf->Line($curx, $cury, $endx, $endy);
                     $newpdf->SetX($curx + 0.1);
                 } else {
                     foreach ($this->headers as $id => $header) {
                         $text = '';
                         if (isset($datum->{$id})) {
                             $text = $datum->{$id};
                         }
                         $newpdf->Cell($widths[$id], $heights[$row], $text, 0, 0, 'C', 0);
                     }
                 }
                 $newpdf->Ln();
                 $row++;
             }
             $newpdf->Output($filename, 'I');
             break;
         default:
             return $output;
             break;
     }
 }
Пример #13
0
function ExportToExcel($data)
{
    global $CFG;
    global $modules;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Course_audit_report.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Autid Report');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    //$formatbc->set_size(14);
    $myxls->write(0, 3, "Audit SUMMARY", $formatbc);
    $myxls->write(1, 3, "ACTIVITIES RECORD", $formatbc);
    //	$myxls->write(3, 0, "Duration", $formatbc);
    $myxls->write(3, 1, $data->duration, $formatbc);
    $myxls->write_string(5, 0, "S.No", $formatbc);
    $myxls->write_string(5, 1, "Period", $formatbc);
    $myxls->write_string(5, 2, "Course Name", $formatbc);
    $myxls->write_string(5, 3, "Teacher Name", $formatbc);
    $myxls->write_string(5, 4, "Actitivties", $formatbc);
    $j = 5;
    foreach ($modules as $module) {
        if ($module == "attforblock") {
            $myxls->write_string(5, $j++, "Attendance", $formatbc);
        } else {
            $myxls->write_string(5, $j++, strtoupper($module), $formatbc);
        }
    }
    $i = 6;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                $myxls->write_number($i, $j++, strip_tags($cell));
            } else {
                $myxls->write_string($i, $j++, strip_tags($cell));
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
function ExportToExcel($data, $uname, $uidnumber)
{
    global $CFG, $USER;
    global $modules;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Student Semester Record.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Students');
    /// format types
    $normal =& $workbook->add_format();
    $normal->set_bold(0);
    // Make it bold
    $normal->set_size(10);
    $normal->set_align('center');
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    $formatbc->set_align('center');
    $formatbc1 =& $workbook->add_format();
    $formatbc1->set_align('center');
    //$formatbc->set_size(14);
    $myxls->write(0, 3, "Student's Semester Record", $formatbc);
    $myxls->write(1, 3, "Name:" . $uname, $formatbc);
    $myxls->write(2, 3, "Registration Number:" . $uidnumber, $formatbc);
    $i = 4;
    $j = 0;
    $a = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                if (preg_match('/^<b>/', $cell)) {
                    $myxls->write_number($i, $j++, strip_tags($cell), $formatbc);
                } else {
                    $myxls->write_number($i, $j++, strip_tags($cell), $formatbc1);
                }
            } else {
                if (preg_match('/^<b>/', $cell)) {
                    $myxls->write_string($i, $j++, strip_tags($cell), $formatbc);
                } else {
                    $myxls->write_string($i, $j++, strip_tags($cell), $formatbc1);
                }
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #15
0
function generate_xls($month, $year, $userid, $courseid, $method = 'I', $base = '')
{
    global $CFG, $DB;
    $monthinfo = get_month_info($month, $year);
    $workerrecord = $DB->get_record('block_timetracker_workerinfo', array('id' => $userid, 'courseid' => $courseid));
    if (!$workerrecord) {
        print_error('usernotexist', 'block_timetracker', $CFG->wwwroot . '/blocks/timetracker/index.php?id=' . $courseid);
    }
    //TODO -- change this to a filename, comment out 'send' function
    $fn = $year . '_' . ($month < 10 ? '0' . $month : $month) . 'Timesheet_' . substr($workerrecord->firstname, 0, 1) . $workerrecord->lastname . '_' . $workerrecord->mdluserid . '.xls';
    if ($method == 'F') {
        $workbook = new MoodleExcelWorkbook($base . '/' . $fn);
    } else {
        $workbook = new MoodleExcelWorkbook('-');
        $workbook->send($fn);
    }
    // Formatting
    $format_bold =& $workbook->add_format();
    $format_bold->set_bold();
    $format_cal_block =& $workbook->add_format();
    $format_cal_block->set_left(1);
    $format_cal_block->set_right(1);
    $format_cal_block->set_bottom(1);
    $format_cal_block->set_text_wrap();
    $format_cal_block->set_v_align('Top');
    $format_cal_block->set_size(8);
    $format_cal_total =& $workbook->add_format();
    $format_cal_total->set_align('center');
    $format_cal_total->set_bold();
    $format_cal_total->set_size(12);
    $format_cal_total->set_left(1);
    $format_cal_total->set_right(1);
    $format_cal_total->set_bottom(1);
    $format_calendar_dates =& $workbook->add_format();
    $format_calendar_dates->set_bold();
    $format_calendar_dates->set_align('center');
    $format_calendar_dates->set_size(8);
    $format_calendar_dates->set_left(1);
    $format_calendar_dates->set_right(1);
    $format_calendar_days =& $workbook->add_format();
    $format_calendar_days->set_bold();
    $format_calendar_days->set_align('center');
    $format_calendar_days->set_size(8);
    $format_calendar_days->set_fg_color(22);
    $format_calendar_days->set_border(1);
    $format_center =& $workbook->add_format();
    $format_center->set_align('center');
    $format_footer =& $workbook->add_format();
    $format_footer->set_bold();
    $format_footer->set_bottom(1);
    $format_footer->set_v_align('Top');
    $format_footer->set_text_wrap();
    $format_footer_block =& $workbook->add_format();
    $format_footer_block->set_bottom(1);
    $format_footer_block->set_top(1);
    $format_footer_block->set_left(1);
    $format_footer_block->set_right(1);
    $format_timesheet_header =& $workbook->add_format();
    $format_timesheet_header->set_bold();
    $format_timesheet_header->set_align('center');
    $format_timesheet_header->set_size(12);
    $format_timesheet_header->set_bottom(1);
    $format_title =& $workbook->add_format();
    $format_title->set_bold();
    $format_title->set_align('center');
    $format_title->set_size(12);
    $format_week_header =& $workbook->add_format();
    $format_week_header->set_bold();
    $format_week_header->set_align('center');
    $format_week_header->set_size(8);
    // Collect Data
    $mdluser = $DB->get_record('user', array('id' => $workerrecord->mdluserid));
    $conf = get_timetracker_config($courseid);
    $worksheet = array();
    $worksheet[1] =& $workbook->add_worksheet('First worksheet');
    // Set column widths
    $worksheet[1]->set_column(0, 8, 10.57);
    // Write data to spreadsheet
    $worksheet[1]->write_string(0, 0, 'Mars Hill College', $format_title);
    $worksheet[1]->merge_cells(0, 0, 0, 7);
    $worksheet[1]->write_string(1, 0, 'Timesheet - ' . $monthinfo['monthname'] . ', ' . $year, $format_timesheet_header);
    $worksheet[1]->merge_cells(1, 0, 1, 7);
    // Creates separator line under 'Timesheet'
    foreach (range(1, 7) as $i) {
        $worksheet[1]->write_blank(1, $i, $format_timesheet_header);
    }
    // Header Data
    $worksheet[1]->write_string(2, 0, 'WORKER: ' . strtoupper($workerrecord->lastname) . ', ' . strtoupper($workerrecord->firstname), $format_bold);
    $worksheet[1]->merge_cells(2, 0, 2, 3);
    $worksheet[1]->write_string(3, 0, "ID: {$mdluser->username}", $format_bold);
    $worksheet[1]->merge_cells(3, 0, 3, 3);
    $worksheet[1]->write_string(4, 0, "ADDRESS: {$workerrecord->address}", $format_bold);
    $worksheet[1]->merge_cells(4, 0, 4, 3);
    $worksheet[1]->write_string(5, 0, 'YTD Earnings: $' . number_format(get_earnings_this_year($userid, $courseid), 2), $format_bold);
    $worksheet[1]->merge_cells(5, 0, 5, 3);
    $worksheet[1]->write_string(2, 4, 'SUPERVISOR: ' . $conf['supname'], $format_bold);
    $worksheet[1]->merge_cells(2, 4, 2, 7);
    $worksheet[1]->write_string(3, 4, 'DEPARTMENT: ' . $conf['department'], $format_bold);
    $worksheet[1]->merge_cells(3, 4, 3, 7);
    $worksheet[1]->write_string(4, 4, 'POSITION: ' . $conf['position'], $format_bold);
    $worksheet[1]->merge_cells(4, 4, 4, 7);
    $worksheet[1]->write_string(5, 4, 'BUDGET: ' . $conf['budget'], $format_bold);
    $worksheet[1]->merge_cells(5, 4, 5, 7);
    // Calendar Data
    $worksheet[1]->write_string(7, 0, 'Sunday', $format_calendar_days);
    $worksheet[1]->write_string(7, 1, 'Monday', $format_calendar_days);
    $worksheet[1]->write_string(7, 2, 'Tuesday', $format_calendar_days);
    $worksheet[1]->write_string(7, 3, 'Wednesday', $format_calendar_days);
    $worksheet[1]->write_string(7, 4, 'Thursday', $format_calendar_days);
    $worksheet[1]->write_string(7, 5, 'Friday', $format_calendar_days);
    $worksheet[1]->write_string(7, 6, 'Saturday', $format_calendar_days);
    $worksheet[1]->write_string(7, 7, 'Total Hours', $format_calendar_days);
    $worksheet[1]->set_row(9, 69);
    $worksheet[1]->set_row(11, 69);
    $worksheet[1]->set_row(13, 69);
    $worksheet[1]->set_row(15, 69);
    $worksheet[1]->set_row(17, 69);
    $worksheet[1]->set_row(19, 69);
    $worksheet[1]->set_row(8, 11.25);
    $worksheet[1]->set_row(10, 11.25);
    $worksheet[1]->set_row(12, 11.25);
    $worksheet[1]->set_row(14, 11.25);
    $worksheet[1]->set_row(16, 11.25);
    $worksheet[1]->set_row(18, 11.25);
    foreach (range(0, 7) as $i) {
        $worksheet[1]->write_blank(8, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(9, $i, $format_cal_block);
        $worksheet[1]->write_blank(10, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(11, $i, $format_cal_block);
        $worksheet[1]->write_blank(12, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(13, $i, $format_cal_block);
        $worksheet[1]->write_blank(14, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(15, $i, $format_cal_block);
        $worksheet[1]->write_blank(16, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(17, $i, $format_cal_block);
        $worksheet[1]->write_blank(18, $i, $format_calendar_dates);
        $worksheet[1]->write_blank(19, $i, $format_cal_block);
    }
    // Footer
    foreach (range(0, 7) as $i) {
        $worksheet[1]->write_blank(20, $i, $format_footer_block);
        $worksheet[1]->write_blank(21, $i, $format_footer_block);
    }
    // Number the Days and add data
    $units = get_split_month_work_units($workerrecord->id, $courseid, $month, $year);
    $date = 1;
    $dayofweek = $monthinfo['dayofweek'];
    $weeksum = 0;
    $monthsum = 0;
    for ($currentrow = 8; $currentrow < 20; $currentrow += 2) {
        //echo "inside for loop <br />";
        $dayofweek = $dayofweek % 7;
        do {
            $worksheet[1]->write_string($currentrow, $dayofweek, $date, $format_calendar_dates);
            //begin of print work units
            // Print the data in the correct date blocks
            $wustr = "";
            $mid = 86400 * ($date - 1) + $monthinfo['firstdaytimestamp'];
            $eod = 86400 * ($date - 1) + ($monthinfo['firstdaytimestamp'] + 86399);
            if ($units) {
                foreach ($units as $unit) {
                    if ($unit->timein < $eod && $unit->timein >= $mid) {
                        $in = userdate($unit->timein, get_string('timeformat', 'block_timetracker'));
                        $out = userdate($unit->timeout, get_string('timeformat', 'block_timetracker'));
                        if ($unit->timeout - $unit->timein > 449) {
                            $wustr .= "In: {$in}\nOut: {$out}\n";
                            $weeksum += get_hours($unit->timeout - $unit->timein);
                        }
                    }
                }
            }
            $worksheet[1]->write_string($currentrow + 1, $dayofweek, $wustr, $format_cal_block);
            //end of print work units
            //if day of week = 7, copy value over and reset weekly sum to 0.
            // Calculate total hours
            if ($dayofweek == 6 || $date == $monthinfo['lastday']) {
                //Add week sum to monthly sum
                //Print value in weekly totals column
                //clear weekly sum
                $monthsum = $monthsum + $weeksum;
                $worksheet[1]->write_string($currentrow + 1, 7, $weeksum, $format_cal_total);
                $weeksum = 0;
            }
            $dayofweek++;
            $date++;
        } while ($date <= $monthinfo['lastday'] && $dayofweek % 7 != 0);
        if ($date >= $monthinfo['lastday']) {
            break;
        }
    }
    // Write footer data
    $worksheet[1]->write_string(20, 0, "Pay Rate or Stipend Amount\n" . '$' . number_format($workerrecord->currpayrate, 2), $format_footer);
    $worksheet[1]->merge_cells(20, 0, 20, 3);
    $worksheet[1]->write_string(20, 4, 'Total Hours/Earnings for ' . $monthinfo['monthname'] . ', ' . $year . ":\n" . number_format($monthsum, 2) . ' / $' . $monthsum * $workerrecord->currpayrate, $format_footer);
    $worksheet[1]->merge_cells(20, 4, 20, 7);
    $worksheet[1]->write_string(21, 0, 'Supervisor Signature/Date', $format_footer);
    $worksheet[1]->merge_cells(21, 0, 21, 3);
    $worksheet[1]->write_string(21, 4, 'Worker Signature/Date', $format_footer);
    $worksheet[1]->merge_cells(21, 4, 21, 7);
    $worksheet[1]->set_row(20, 30);
    $worksheet[1]->set_row(21, 42);
    $workbook->close();
    return $fn;
}
 $slots = get_records('scheduler_slots', 'schedulerid', $scheduler->id, 'starttime', 'id, starttime, duration, exclusivity, teacherid, hideuntil');
 if ($subaction == 'singlesheet') {
     /// Adding the worksheet
     $myxls['singlesheet'] =& $workbook->add_worksheet($COURSE->shortname . ': ' . format_string($scheduler->name));
     $myxls['singlesheet']->write_string(0, 0, get_string('date', 'scheduler'));
     $myxls['singlesheet']->write_string(0, 1, get_string('starttime', 'scheduler'));
     $myxls['singlesheet']->write_string(0, 2, get_string('endtime', 'scheduler'));
     $myxls['singlesheet']->write_string(0, 3, get_string('slottype', 'scheduler'));
     $myxls['singlesheet']->write_string(0, 4, $scheduler->staffrolename);
     $myxls['singlesheet']->write_string(0, 5, get_string('students', 'scheduler'));
     $myxls['singlesheet']->set_column(0, 0, 26);
     $myxls['singlesheet']->set_column(1, 2, 15);
     $myxls['singlesheet']->set_column(3, 3, 10);
     $myxls['singlesheet']->set_column(4, 4, 20);
     $myxls['singlesheet']->set_column(5, 5, 60);
     $f = $workbook->add_format(array('bold' => 1));
     $myxls['singlesheet']->set_row(0, 13, $f);
 } elseif ($subaction == 'byteacher') {
     /// Adding the worksheets
     if ($teachers) {
         foreach ($teachers as $teacher) {
             $myxls[$teacher->id] =& $workbook->add_worksheet(fullname($teacher));
             /// Print names of all the fields
             $myxls[$teacher->id]->write_string(0, 0, get_string('date', 'scheduler'));
             $myxls[$teacher->id]->write_string(0, 1, get_string('starttime', 'scheduler'));
             $myxls[$teacher->id]->write_string(0, 2, get_string('endtime', 'scheduler'));
             $myxls[$teacher->id]->write_string(0, 3, get_string('slottype', 'scheduler'));
             $myxls[$teacher->id]->write_string(0, 4, get_string('students', 'scheduler'));
             $myxls['singlesheet']->set_column(0, 0, 26);
             $myxls['singlesheet']->set_column(1, 2, 15);
             $myxls['singlesheet']->set_column(3, 3, 10);
function ExportToExcel($data)
{
    global $CFG;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Semester_Result:.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Semester_result');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    $myxls->set_row(1, 20);
    $myxls->set_row(2, 20);
    //	$myxls->set_column(2,3,30);
    $header1 =& $workbook->add_format();
    $header1->set_bold(1);
    // Make it bold
    $header1->set_align('center');
    // Align text to center
    $header1->set_size(14);
    //$header1->set_fg_color(22);
    $header2 =& $workbook->add_format();
    $header2->set_bold(1);
    // Make it bold
    $header2->set_align('center');
    // Align text to center
    $header2->set_size(12);
    $header2->set_text_wrap(1);
    $normal =& $workbook->add_format();
    $normal->set_bold(0);
    $normal->set_align('center');
    $normal->set_size(10);
    $normal1 =& $workbook->add_format();
    $normal1->set_bold(1);
    $normal1->set_align('center');
    $normal1->set_size(10);
    $name =& $workbook->add_format();
    $name->set_bold(0);
    $name->set_size(10);
    $name->set_align('center');
    $grey_code_f =& $workbook->add_format();
    $grey_code_f->set_bold(0);
    // Make it bold
    $grey_code_f->set_size(12);
    $grey_code_f->set_fg_color(22);
    $grey_code_f->set_align('center');
    //$formatbc->set_size(14);
    $myxls->write(1, 0, $data->schoolname, $header1);
    $myxls->write(2, 0, "On Campus Semester Result Information", $header1);
    $myxls->write(3, 1, "Semester:" . $data->semester, $header2);
    $myxls->write(3, 4, "Duration:" . $data->start_duration . "-" . $data->end_duration, $header2);
    $myxls->set_column(0, 0, 8);
    $myxls->set_column(1, 1, 10);
    $myxls->set_column(3, 3, 30);
    $myxls->set_column(2, 2, 20);
    $myxls->merge_cells(3, 1, 3, 2);
    $myxls->merge_cells(3, 4, 3, 10);
    $i = 5;
    $j = 0;
    $a = 0;
    $flag1 = false;
    foreach ($data->head as $heading) {
        $heading = str_replace('<br/>', '', $heading);
        $heading = trim($heading);
        if ($heading == "Credits") {
            $flag1 = true;
        }
        if ($flag1 == true) {
            $myxls->set_column($j, $j, 5);
        }
        if ($j >= 4 && $flag1 == false) {
            $myxls->set_column($j, $j, 8);
            //$myxls->merge_cells($i,$j,$i,$j+1);/////merge
        }
        //	if($data->headspan[$a]==2){
        //$myxls->set_column($j,$j+1,38);
        //$myxls->merge_cells($i,$j,$i,$j+1);/////merge
        //	}
        $myxls->write_string($i, $j, $heading, $header2);
        //$myxls->set_column($pos,$pos,(strlen($grade_item->get_name()))+4);
        $col_size = strlen($heading);
        $col_size += 6;
        //	if(preg_match('/^NAME/i',$heading)){
        //		$col_size=39;
        //	}
        $myxls->set_row(1, 15);
        //	$myxls->set_column($j,$j,$col_size);
        if ($data->headspan[$a] == 2) {
            $myxls->merge_cells($i, $j, $i, $j + 1);
            $j += 2;
        }
        if ($data->headspan[$a] == 1) {
            $j++;
        }
        //$j++;
        $a++;
    }
    $myxls->set_row(5, 55);
    $myxls->merge_cells(1, 0, 1, $j - 1);
    $myxls->merge_cells(2, 0, 2, $j - 1);
    $myxls->merge_cells(4, 1, 4, 3);
    $i = 6;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            foreach ($cell as $cel) {
                if ($cel->colspan == 2) {
                    //$myxls->merge_cells($i,$j,$i,$j+1);/////merge
                }
                if (is_numeric($cel)) {
                    $myxls->write_string($i, $j, strip_tags($cel->text), $normal1);
                } else {
                    $myxls->write_string($i, $j, strip_tags($cel->text), $normal1);
                }
                if ($cel->colspan == 2) {
                    $myxls->merge_cells($i, $j, $i, $j + 1);
                    $j += 2;
                }
                if ($cel->colspan == 1) {
                    $j++;
                }
            }
        }
        $i++;
        $j = 0;
    }
    $i = 9;
    $j = 0;
    $flag = false;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            if ($i >= 9 && $flag == true) {
                if (is_numeric($cell)) {
                    $myxls->write_number($i, $j++, $cell, $normal);
                } else {
                    $myxls->write_string($i, $j++, $cell, $normal);
                }
            }
        }
        $i++;
        $j = 0;
        if ($i == 12 && $flag == false) {
            $i = 9;
            $flag = true;
        }
    }
    $workbook->close();
    exit;
}
function ExportToExcel($data, $name, $type)
{
    global $CFG;
    global $modules;
    global $name, $type;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Institute_audit_report.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Autid Report');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc1 =& $workbook->add_format();
    $formatbc->set_bold(1);
    $myxls->set_column(0, 0, 30);
    $myxls->set_column(1, 7, 20);
    $formatbc->set_align('center');
    $formatbc1->set_align('center');
    $xlsFormats = new stdClass();
    $xlsFormats->default = $workbook->add_format(array('width' => 40));
    //$formatbc->set_size(14);
    $myxls->write(0, 2, "AUDIT REPORT", $formatbc);
    $myxls->write(1, 2, $name, $formatbc);
    if ($type == "Activities") {
        $myxls->write_string(4, 0, "Period", $formatbc);
        $j = 1;
    }
    foreach ($modules as $module) {
        $myxls->write_string(4, $j++, strtoupper($module), $formatbc);
    }
    $i = 5;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                $myxls->write_number($i, $j++, strip_tags($cell), $formatbc1);
            } else {
                $myxls->write_string($i, $j++, strip_tags($cell), $formatbc1);
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #19
0
//get the questions (item-names)
if (!($items = $DB->get_records('feedback_item', array('feedback' => $feedback->id, 'hasvalue' => 1), 'position'))) {
    print_error('no_items_available_yet', 'feedback', $CFG->wwwroot . '/mod/feedback/view.php?id=' . $id);
    exit;
}
$filename = "feedback.xls";
$mygroupid = groups_get_activity_group($cm);
// Creating a workbook
// $workbook = new EasyWorkbook("-");
$workbook = new MoodleExcelWorkbook('-');
// $workbook->setTempDir($CFG->dataroot.'/temp');
$workbook->send($filename);
// $workbook->setVersion(8);
//creating the needed formats
$xlsFormats = new stdClass();
$xlsFormats->head1 = $workbook->add_format(array('bold' => 1, 'size' => 12));
$xlsFormats->head2 = $workbook->add_format(array('align' => 'left', 'bold' => 1, 'bottum' => 2));
$xlsFormats->default = $workbook->add_format(array('align' => 'left', 'v_align' => 'top'));
// $xlsFormats->head2_green = $workbook->add_format(array(
// 'align'=>'left',
// 'bold'=>1,
// 'v_align'=>'top',
// 'bottum'=>2,
// 'fg_color'=>'green'));
$xlsFormats->value_bold = $workbook->add_format(array('align' => 'left', 'bold' => 1, 'v_align' => 'top'));
// $xlsFormats->value_blue = $workbook->add_format(array(
// 'align'=>'left',
// 'bold'=>1,
// 'v_align'=>'top',
// 'top'=>2,
// 'fg_color'=>'blue'));
Пример #20
0
 if ($download == "ods") {
     require_once "{$CFG->libdir}/odslib.class.php";
     $workbook = new MoodleODSWorkbook("-");
     $filename .= '.ods';
 } else {
     require_once "{$CFG->libdir}/excellib.class.php";
     $workbook = new MoodleExcelWorkbook("-");
     $filename .= '.xls';
 }
 /// Send HTTP headers
 $workbook->send($filename);
 /// Creating the first worksheet
 $myxls = $workbook->add_worksheet($strresponses);
 if ($download == "ods") {
     $cellformat = '';
     $cellformat1 = $workbook->add_format(array('bg_color' => 'red'));
 } else {
     $cellformat = '';
     $cellformat1 = $workbook->add_format(array('bg_color' => 'red'));
 }
 /// Print names of all the fields
 if ($action == "all") {
     $myxls->write_string(0, 0, get_string("booking", "booking"));
     $myxls->write_string(0, 1, get_string("institution", "booking"));
     $myxls->write_string(0, 2, get_string("location", "booking"));
     $myxls->write_string(0, 3, get_string("coursestarttime", "booking"));
     $myxls->write_string(0, 4, get_string("courseendtime", "booking"));
     $myxls->write_string(0, 5, get_string("user") . " " . get_string("idnumber"));
     $myxls->write_string(0, 6, get_string("firstname"));
     $myxls->write_string(0, 7, get_string("lastname"));
     $myxls->write_string(0, 8, get_string("email"));
Пример #21
0
/**
 * Download the list of users attending at least one of the sessions
 * for a given facetoface activity
 */
function facetoface_download_attendance($facetofacename, $facetofaceid, $location, $format)
{
    global $CFG;
    $timenow = time();
    $timeformat = str_replace(' ', '_', get_string('strftimedate', 'langconfig'));
    $downloadfilename = clean_filename($facetofacename . '_' . userdate($timenow, $timeformat));
    $dateformat = 0;
    if ('ods' === $format) {
        // OpenDocument format (ISO/IEC 26300).
        require_once $CFG->dirroot . '/lib/odslib.class.php';
        $downloadfilename .= '.ods';
        $workbook = new MoodleODSWorkbook('-');
    } else {
        // Excel format.
        require_once $CFG->dirroot . '/lib/excellib.class.php';
        $downloadfilename .= '.xls';
        $workbook = new MoodleExcelWorkbook('-');
        $dateformat =& $workbook->add_format();
        $dateformat->set_num_format('d mmm yy');
        // TODO: use format specified in language pack.
    }
    $workbook->send($downloadfilename);
    $worksheet =& $workbook->add_worksheet('attendance');
    facetoface_write_worksheet_header($worksheet);
    facetoface_write_activity_attendance($worksheet, 1, $facetofaceid, $location, '', '', $dateformat);
    $workbook->close();
    exit;
}
Пример #22
0
 /**
  * fills workbook (either XLSX or ODS) with data
  *
  * @param MoodleExcelWorkbook $workbook workbook to put data into
  * @param stdClass[] $data userdata with headline at index 0
  * @param stdClass[] $orderby current sort-array
  * @param string[] $collapsed current collapsed columns
  */
 private function userlist_fill_workbook(&$workbook, $data = array(), $orderby = array(), $collapsed = array())
 {
     global $SESSION, $CFG;
     $orientation = optional_param('orientation', 0, PARAM_BOOL);
     if (count($data) > 0) {
         if (count($data) > 1) {
             // General information? unused at the moment!
             $worksheet = $workbook->add_worksheet(get_string('all'));
             if (is_a($worksheet, 'Moodle_Excel_Worksheet')) {
                 if ($orientation) {
                     $worksheet->pear_excel_worksheet->setLandscape();
                 } else {
                     $worksheet->pear_excel_worksheet->setPortrait();
                 }
             }
         }
         // Prepare formats!
         $headlineprop = array('size' => 12, 'bold' => 1, 'HAlign' => 'center', 'bottom' => 2, 'VAlign' => 'vcenter');
         $headlineformat = $workbook->add_format($headlineprop);
         $headlineformat->set_right(1);
         $headlineformat->set_align('center');
         $headlineformat->set_align('vcenter');
         $headlinelast = $workbook->add_format($headlineprop);
         $headlinelast->set_align('center');
         $headlinelast->set_align('vcenter');
         $headlinelast->set_left(1);
         $headlinenb = $workbook->add_format($headlineprop);
         $headlinenb->set_align('center');
         $headlinenb->set_align('vcenter');
         unset($headlineprop['bottom']);
         $headlinenbb = $workbook->add_format($headlineprop);
         $headlinenbb->set_align('center');
         $headlinenbb->set_align('vcenter');
         $regentryprop = array('size' => 10, 'align' => 'left');
         $queueentryprop = $regentryprop;
         $queueentryprop['italic'] = true;
         $queueentryprop['color'] = 'grey';
         $regentryformat = $workbook->add_format($regentryprop);
         $regentryformat->set_right(1);
         $regentryformat->set_align('vcenter');
         $regentrylast = $workbook->add_format($regentryprop);
         $regentrylast->set_align('vcenter');
         $noregentriesformat = $workbook->add_format($regentryprop);
         $noregentriesformat->set_align('center');
         $noregentriesformat->set_align('vcenter');
         $noregentriesformat->set_right(1);
         $queueentryformat = $workbook->add_format($queueentryprop);
         $queueentryformat->set_right(1);
         $queueentryformat->set_align('vcenter');
         $queueentrylast = $workbook->add_format($queueentryprop);
         $queueentrylast->set_align('vcenter');
         $noqueueentriesformat = $workbook->add_format($queueentryprop);
         $noqueueentriesformat->set_align('center');
         $noqueueentriesformat->set_align('vcenter');
         // Start row for groups general sheet!
         $j = 0;
         // We create a dummy user-object to get the fullname-format!
         $dummy = new stdClass();
         $namefields = get_all_user_name_fields();
         foreach ($namefields as $namefield) {
             $dummy->{$namefield} = $namefield;
         }
         $fullnameformat = fullname($dummy);
         // Now get the ones used in fullname in the correct order!
         $namefields = order_in_string($namefields, $fullnameformat);
         $columnwidth = array(0 => 26, 'fullname' => 26, 'firstname' => 20, 'surname' => 20, 'email' => 35, 'registrations' => 47, 'queues_rank' => 7.5, 'queues_grp' => 47);
         // Unit: mm!
         foreach ($data as $key => $user) {
             if ($key == 0) {
                 // Headline!
                 $k = 0;
                 // First we output every namefield from used by fullname in exact the defined order!
                 foreach ($namefields as $namefield) {
                     $worksheet->write_string($j, $k, get_user_field_name($namefield), $headlineformat);
                     $worksheet->write_blank($j + 1, $k, $headlineformat);
                     $worksheet->merge_cells($j, $k, $j + 1, $k);
                     $hidden = in_array($namefield, $collapsed) ? true : false;
                     $columnwidth[$namefield] = empty($columnwidth[$namefield]) ? $columnwidth[0] : $columnwidth[$namefield];
                     $worksheet->set_column($k, $k, $columnwidth[$namefield], null, $hidden);
                     $k++;
                 }
                 // ...k = n!
                 if (!empty($CFG->showuseridentity)) {
                     $fields = explode(',', $CFG->showuseridentity);
                     foreach ($fields as $field) {
                         $worksheet->write_string($j, $k, get_user_field_name($field), $headlineformat);
                         $worksheet->write_blank($j + 1, $k, $headlineformat);
                         $hidden = in_array($field, $collapsed) ? true : false;
                         $columnwidth[$field] = empty($columnwidth[$field]) ? $columnwidth[0] : $columnwidth[$field];
                         $worksheet->set_column($k, $k, $columnwidth[$field], null, $hidden);
                         $worksheet->merge_cells($j, $k, $j + 1, $k);
                         $k++;
                         // ...k = n+x!
                     }
                 } else {
                     $worksheet->write_string($j, $k, get_user_field_name('idnumber'), $headlineformat);
                     $worksheet->write_blank($j + 1, $k, $headlineformat);
                     $hidden = in_array('idnumber', $collapsed) ? true : false;
                     $columnwidth['idnumber'] = empty($columnwidth['idnumber']) ? $columnwidth[0] : $columnwidth['idnumber'];
                     $worksheet->set_column($k, $k, $columnwidth['idnumber'], null, $hidden);
                     $worksheet->merge_cells($j, $k, $j + 1, $k);
                     $k++;
                     // ...k = n+1!
                     $worksheet->write_string($j, $k, get_user_field_name('email'), $headlineformat);
                     $worksheet->write_blank($j + 1, $k, $headlineformat);
                     $hidden = in_array('email', $collapsed) ? true : false;
                     $columnwidth['email'] = empty($columnwidth['email']) ? $columnwidth[0] : $columnwidth['email'];
                     $worksheet->set_column($k, $k, $columnwidth['email'], null, $hidden);
                     $worksheet->merge_cells($j, $k, $j + 1, $k);
                     $k++;
                     // ...k = n+2!
                 }
                 $worksheet->write_string($j, $k, $user['registrations'], $headlineformat);
                 $worksheet->write_blank($j + 1, $k, $headlineformat);
                 $hidden = in_array('registrations', $collapsed) ? true : false;
                 $columnwidth['registrations'] = empty($columnwidth['registrations']) ? $columnwidth[0] : $columnwidth['registrations'];
                 $worksheet->set_column($k, $k, $columnwidth['registrations'], null, $hidden);
                 $worksheet->merge_cells($j, $k, $j + 1, $k);
                 $k++;
                 // ...k = n+3!
                 $worksheet->write_string($j, $k, $user['queues'], $headlinenbb);
                 $worksheet->write_blank($j, $k + 1, $headlinenbb);
                 $hidden = in_array('queues', $collapsed) ? true : false;
                 $columnwidth['queues_rank'] = empty($columnwidth['queues_rank']) ? $columnwidth[0] : $columnwidth['queues_rank'];
                 $worksheet->set_column($k, $k, $columnwidth['queues_rank'], null, $hidden);
                 $columnwidth['queues_grp'] = empty($columnwidth['queues_grp']) ? $columnwidth[0] : $columnwidth['queues_grp'];
                 $worksheet->set_column($k + 1, $k + 1, $columnwidth['queues_grp'], null, $hidden);
                 $worksheet->merge_cells($j, $k, $j, $k + 1);
                 $worksheet->write_string($j + 1, $k, get_string('rank', 'grouptool'), $headlinelast);
                 $worksheet->write_string($j + 1, $k + 1, get_string('group', 'group'), $headlinenb);
                 $k += 2;
                 // ...k = n+5!
                 $rows = 2;
             } else {
                 $k = 0;
                 $rows = max(array(1, count($user['registrations']), count($user['queues'])));
                 // First we output every namefield from used by fullname in exact the defined order!
                 foreach ($namefields as $namefield) {
                     if (empty($user[$namefield])) {
                         $user[$namefield] = '';
                     }
                     $worksheet->write_string($j, $k, $user[$namefield], $regentryformat);
                     if ($rows > 1) {
                         $worksheet->merge_cells($j, $k, $j + $rows - 1, $k);
                     }
                     $k++;
                 }
                 // ...k = n!
                 if (!empty($CFG->showuseridentity)) {
                     $fields = explode(',', $CFG->showuseridentity);
                     foreach ($fields as $field) {
                         if (empty($user[$field])) {
                             $worksheet->write_blank($j, $k, $regentryformat);
                         } else {
                             $worksheet->write_string($j, $k, $user[$field], $regentryformat);
                         }
                         if ($rows > 1) {
                             $worksheet->merge_cells($j, $k, $j + $rows - 1, $k);
                         }
                         $k++;
                         // ...k = n+x!
                     }
                 } else {
                     $worksheet->write_string($j, $k, $user['idnumber'], $regentryformat);
                     if ($rows > 1) {
                         $worksheet->merge_cells($j, $k, $j + $rows - 1, $k);
                     }
                     $k++;
                     // ...k = n+1!
                     $worksheet->write_string($j, $k, $user['email'], $regentryformat);
                     if ($rows > 1) {
                         $worksheet->merge_cells($j, $k, $j + $rows - 1, $k);
                     }
                     $k++;
                     // ...k = n+2!
                 }
                 for ($i = 0; $i < $rows; $i++) {
                     if ($i != 0) {
                         for ($m = 0; $m < $k; $m++) {
                             // Write all the empty cells!
                             $worksheet->write_blank($j + $i, $m, $regentryformat);
                         }
                     }
                     if (count($user['registrations']) == 0 && $i == 0) {
                         $worksheet->write_string($j, $k, get_string('no_registrations', 'grouptool'), $noregentriesformat);
                         if ($rows > 1) {
                             $worksheet->merge_cells($j, $k, $j + $rows - 1, $k);
                         }
                     } else {
                         if (key_exists($i, $user['registrations'])) {
                             $worksheet->write_string($j + $i, $k, $user['registrations'][$i], $regentryformat);
                         } else {
                             $worksheet->write_blank($j + $i, $k, $regentryformat);
                         }
                     }
                     if (count($user['queues']) == 0 && $i == 0) {
                         $worksheet->write_string($j, $k + 1, get_string('nowhere_queued', 'grouptool'), $noqueueentriesformat);
                         $worksheet->merge_cells($j, $k + 1, $j + $rows - 1, $k + 2);
                     } else {
                         if (key_exists($i, $user['queues'])) {
                             $worksheet->write_number($j + $i, $k + 1, $user['queues'][$i]['rank'], $queueentrylast);
                             $worksheet->write_string($j + $i, $k + 2, $user['queues'][$i]['name'], $queueentrylast);
                         } else {
                             $worksheet->write_blank($j + $i, $k + 1, $queueentrylast);
                             $worksheet->write_blank($j + $i, $k + 2, $queueentrylast);
                         }
                     }
                 }
                 $k += 3;
             }
             $j += $rows;
             // We use 1 row space between groups!
         }
     }
 }
Пример #23
0
 /**
  * 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;
 }
function ExportToExcel($data, $name, $type)
{
    global $CFG;
    global $headings;
    global $name, $type;
    global $department;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Faculty_Feedback_Report.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Faculty Feedback Report');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc1 =& $workbook->add_format();
    $formatbc->set_bold(1);
    $myxls->set_column(0, 0, 50);
    $myxls->set_column(1, 7, 20);
    $formatbc->set_align('center');
    $formatbc1->set_align('center');
    $xlsFormats = new stdClass();
    $xlsFormats->default = $workbook->add_format(array('width' => 40));
    //$formatbc->set_size(14);
    $myxls->write(0, 2, "FEEDBACK REPORT", $formatbc);
    $myxls->write(1, 2, $name, $formatbc);
    $myxls->write(2, 2, "Department: " . $department, $formatbc);
    foreach ($headings as $heading) {
        $myxls->write_string(4, $j++, strtoupper($heading), $formatbc);
    }
    $i = 5;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                $myxls->write_number($i, $j++, strip_tags($cell), $formatbc1);
            } else {
                $myxls->write_string($i, $j++, strip_tags($cell), $formatbc1);
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #25
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
function ExportToExcel($data, $perd, $weeks)
{
    global $CFG, $USER;
    global $modules;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Missing Lectures Report.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('MCR');
    /// format types
    $green =& $workbook->add_format();
    $green->set_bold(0);
    // Make it bold
    $green->set_size(12);
    $green->set_fg_color("white");
    $green->set_align('center');
    $red =& $workbook->add_format();
    $red->set_bold(0);
    // Make it bold
    $red->set_size(12);
    $red->set_fg_color(10);
    $red->set_align('center');
    $orange =& $workbook->add_format();
    $orange->set_bold(0);
    // Make it bold
    $orange->set_size(12);
    $orange->set_fg_color("orange");
    $orange->set_align('center');
    $normal =& $workbook->add_format();
    $normal->set_bold(0);
    // Make it bold
    $normal->set_size(10);
    $normal->set_align('center');
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    $formatbc->set_align('center');
    //$formatbc->set_size(14);
    $myxls->write(0, 3, "Missing Lectures Record", $formatbc);
    $myxls->write(2, 2, "Period : ( " . $perd . " ) ", $formatbc);
    $myxls->write(3, 2, "Weeks: " . $weeks, $formatbc);
    $myxls->write(4, 2, "The Remarks are entered by " . $USER->firstname . " " . $USER->lastname, $formatbc);
    $i = 6;
    $j = 0;
    $a = 0;
    foreach ($data->head as $heading) {
        $myxls->write_string($i, $j, $heading, $formatbc);
        if ($data->headspan[$a] == 3) {
            $myxls->merge_cells($i, $j, $i, $j + 2);
            $j += 3;
        }
        if ($data->headspan[$a] == 1) {
            $j++;
        }
        $a++;
    }
    $myxls->set_column(0, 0, 6, $formatbc);
    $myxls->set_column(1, 1, 22, $formatbc);
    $myxls->set_column(2, 2, 12, $formatbc);
    $myxls->set_column(3, 3, 30, $formatbc);
    $myxls->set_column(4, 4, 15, $formatbc);
    $myxls->set_column(5, 5, 25, $formatbc);
    $myxls->set_column(6, 6, 12, $formatbc);
    $i = 7;
    $j = 0;
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                $myxls->write_number($i, $j++, $cell, $normal);
            } else {
                if (preg_match('/^!!r/', $cell)) {
                    $cell = str_replace("!!r", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $red);
                } elseif (preg_match('/^!!g/', $cell)) {
                    $cell = str_replace("!!g", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $green);
                } elseif (preg_match('/^!!o/', $cell)) {
                    $cell = str_replace("!!o", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $orange);
                } else {
                    if (strstr($cell, "<b>") == true) {
                        $myxls->write_string($i, $j++, strip_tags($cell), $formatbc);
                    } else {
                        $myxls->write_string($i, $j++, $cell, $normal);
                    }
                }
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #27
0
function print_log_xls($course, $user, $date, $order = 'l.time DESC', $modname, $modid, $modaction, $groupid)
{
    global $CFG, $DB;
    require_once "{$CFG->libdir}/excellib.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 .= '.xls';
    $workbook = new MoodleExcelWorkbook('-');
    $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($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
        $myxls->write_date($row, 1, $log->time, $formatDate);
        // write_date() does conversion/timezone support. MDL-14934
        $myxls->write($row, 2, $log->ip, '');
        $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
        $myxls->write($row, 3, $fullname, '');
        $myxls->write($row, 4, $log->module . ' ' . $log->action, '');
        $myxls->write($row, 5, $log->info, '');
        $row++;
    }
    $workbook->close();
    return true;
}
function ExportToExcel($data)
{
    global $CFG;
    global $reportname;
    global $start;
    global $end;
    //require_once("$CFG->libdir/excellib.class.php");/*
    require_once $CFG->dirroot . '/lib/excellib.class.php';
    $filename = "Attendance_report:.xls";
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    ob_clean();
    $workbook->send($filename);
    /// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Attendances');
    /// format types
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);
    $myxls->set_row(1, 20);
    //Added By Hina
    $myxls->set_row(2, 20);
    //Added By Hina
    $header1 =& $workbook->add_format();
    $header1->set_bold(1);
    // Make it bold
    $header1->set_align('center');
    // Align text to center
    $header1->set_size(14);
    //$header1->set_fg_color(22);
    $header2 =& $workbook->add_format();
    $header2->set_bold(1);
    // Make it bold
    $header2->set_align('center');
    // Align text to center
    $header2->set_size(12);
    //$header2->set_fg_color(23);
    $green =& $workbook->add_format();
    $green->set_bold(0);
    // Make it bold
    $green->set_size(12);
    $green->set_fg_color(3);
    $green->set_align('center');
    $red =& $workbook->add_format();
    $red->set_bold(0);
    // Make it bold
    $red->set_size(12);
    $red->set_fg_color(10);
    $red->set_align('center');
    $orange =& $workbook->add_format();
    $orange->set_bold(0);
    // Make it bold
    $orange->set_size(12);
    $orange->set_fg_color('orange');
    $orange->set_align('center');
    $normal =& $workbook->add_format();
    $normal->set_bold(0);
    $normal->set_align('center');
    $normal->set_size(10);
    //Added By Hina Yousuf//
    $normal1 =& $workbook->add_format();
    $normal1->set_bold(1);
    $normal1->set_align('center');
    $normal1->set_size(10);
    //end
    $name =& $workbook->add_format();
    $name->set_bold(0);
    $name->set_size(10);
    $grey_code_f =& $workbook->add_format();
    $grey_code_f->set_bold(0);
    // Make it bold
    $grey_code_f->set_size(12);
    $grey_code_f->set_fg_color(22);
    $grey_code_f->set_align('center');
    //$formatbc->set_size(14);
    $myxls->write(1, 1, "ATTENDANCE SUMMARY", $header1);
    $myxls->write(2, 1, $reportname, $header2);
    if ($start) {
        $duration = 'Period : ( ' . date(" M jS, Y", $start) . ' - ' . date(" M jS, Y", $end) . ')';
        $myxls->write(4, 1, $duration, $formatbc);
    }
    //$myxls->write(4, 0, $duration);
    $myxls->set_column(3, 100, 15);
    //Added By Hina
    $i = 6;
    $j = 0;
    $a = 0;
    $a = 0;
    foreach ($data->head as $heading) {
        $heading = str_replace('<br/>', '', $heading);
        $heading = trim($heading);
        $myxls->write_string($i, $j, $heading, $header2);
        $col_size = strlen($heading);
        $col_size += 6;
        if (preg_match('/^NAME/i', $heading)) {
            $col_size = 25;
        }
        $myxls->set_column($j, $j, $col_size);
        //added By Hina Yousuf
        if ($data->headspan[$a] == 4) {
            $myxls->merge_cells($i, $j, $i, $j + 3);
            $j += 4;
        }
        if ($data->headspan[$a] == 3) {
            $myxls->merge_cells($i, $j, $i, $j + 2);
            $j += 3;
        }
        if ($data->headspan[$a] == 1) {
            $j++;
        }
        //$j++;
        $a++;
        //end
        //$j++;
    }
    //$myxls->merge_cells(1,0,1,$j-1);
    //$myxls->merge_cells(2,0,2,$j-1);
    //$myxls->merge_cells(4,1,4,3);
    $i = 7;
    $j = 0;
    ///Added By Hina Yousuf
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            foreach ($cell as $cel) {
                $myxls->write_string($i, $j, strip_tags($cel->text), $normal1);
                $j++;
            }
        }
    }
    ///end
    foreach ($data->data as $row) {
        foreach ($row as $cell) {
            //$myxls->write($i, $j++, $cell);
            if (is_numeric($cell)) {
                //if($cell>25.99){
                //	$myxls->write_number($i, $j++, $cell,$grey_code_f);
                //}
                //else{
                $myxls->write_number($i, $j++, $cell, $normal);
                //}
            } else {
                ///
                if (preg_match('/^!!r/', $cell)) {
                    $cell = str_replace("!!r", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $red);
                } elseif (preg_match('/^!!g/', $cell)) {
                    $cell = str_replace("!!g", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $green);
                } elseif (preg_match('/^!!o/', $cell)) {
                    $cell = str_replace("!!o", '', $cell);
                    $myxls->write_string($i, $j++, $cell, $orange);
                } else {
                    if ($j == 2) {
                        $myxls->write_string($i, $j++, $cell, $name);
                    } else {
                        $myxls->write_string($i, $j++, $cell, $normal);
                    }
                }
            }
        }
        $i++;
        $j = 0;
    }
    $workbook->close();
    exit;
}
Пример #29
0
 function Export_Excel(&$questions, $filename)
 {
     global $CFG;
     require_once "{$CFG->libdir}/excellib.class.php";
     /// Calculate file name
     $filename .= ".xls";
     /// Creating a workbook
     $workbook = new MoodleExcelWorkbook("-");
     /// 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;
 }
 /**
  * Get the data needed for a downloadable version of the report (all data,
  * no paging necessary) and format it accordingly for the download file
  * type.
  *
  * NOTE: It is expected that the valid format types will be overridden in
  * an extended report class as the array is empty by default.
  *
  * @param string $format A valid format type.
  */
 function download($format)
 {
     global $CFG;
     $output = '';
     if (empty($this->rawdata)) {
         return $output;
     }
     $filename = !empty($this->title) ? $this->title : get_string('download_report', 'block_curr_admin');
     switch ($format) {
         case 'csv':
             $filename .= '.csv';
             header("Content-Transfer-Encoding: ascii");
             header("Content-Disposition: attachment; filename={$filename}");
             header("Content-Type: text/comma-separated-values");
             $row = array();
             $row[] = get_string('curriculum', 'block_curr_admin');
             foreach ($this->headers as $header) {
                 $row[] = $this->csv_escape_string(strip_tags($header));
             }
             echo implode(',', $row) . "\n";
             if (!empty($this->rawdata)) {
                 foreach ($this->rawdata as $curid => $curlist) {
                     $output .= '<strong>' . $curlist->curriculumname . ' - ' . get_string('enrolled_classes', 'block_curr_admin') . '</strong>';
                     $this->data = $curlist->data;
                     $output .= $this->display();
                     unset($this->table);
                     $output .= '<br /><br />';
                 }
             } else {
                 $output .= '<h2>' . get_string('no_classes_completed', 'block_curr_admin') . '</h2>';
             }
             foreach ($this->rawdata as $curid => $curlist) {
                 $first = $curlist->curriculumname;
                 foreach ($curlist->data as $datum) {
                     if (!is_object($datum)) {
                         continue;
                     }
                     $row = array();
                     $row[] = $this->csv_escape_string($first);
                     foreach ($this->headers as $id => $header) {
                         if (isset($datum->{$id})) {
                             $row[] = $this->csv_escape_string($datum->{$id});
                         } else {
                             $row[] = '""';
                         }
                     }
                     echo implode(',', $row) . "\n";
                 }
             }
             break;
         case '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('studentprogress', 'reportstudentprogress');
             $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');
             $rownum = 0;
             $colnum = 0;
             $myxls->write($rownum, $colnum++, get_string('curriculum', 'block_curr_admin'), $formatbc);
             foreach ($this->headers as $header) {
                 $myxls->write($rownum, $colnum++, $header, $formatbc);
             }
             foreach ($this->rawdata as $curid => $curlist) {
                 $first = $curlist->curriculumname;
                 foreach ($curlist->data as $datum) {
                     if (!is_object($datum)) {
                         continue;
                     }
                     $rownum++;
                     $colnum = 0;
                     $myxls->write($rownum, $colnum++, $first, $format);
                     foreach ($this->headers as $id => $header) {
                         if (isset($datum->{$id})) {
                             $myxls->write($rownum, $colnum++, $datum->{$id}, $format);
                         } else {
                             $myxls->write($rownum, $colnum++, '', $format);
                         }
                     }
                 }
             }
             $workbook->close();
             break;
         case 'pdf':
             require_once $CFG->libdir . '/fpdf/fpdf.php';
             $filename .= '.pdf';
             $this->newpdf = new FPDF('P', 'in', 'letter');
             $marginx = 0.75;
             $marginy = 28.35 / $this->newpdf->k;
             $marginy = 0.75;
             $this->newpdf->setMargins($marginx, $marginy);
             $this->newpdf->SetFont('Arial', '', 9);
             $this->newpdf->AddPage();
             $this->newpdf->SetFillColor(225, 225, 225);
             if (file_exists("{$CFG->dirroot}/curriculum/pix/transcript.jpg")) {
                 $this->newpdf->Image("{$CFG->dirroot}/curriculum/pix/transcript.jpg", 0, 0, 8.5, 11.0, 'jpg');
             }
             $this->newpdf->SetFont('Arial', 'I', 7);
             $this->newpdf->SetXY($marginx, 2.62);
             $full = 8.5 - 2.0 * $marginx;
             $half = $full / 2.0;
             $qrtr = $half / 2.0;
             $this->newpdf->Cell($full, 0.2, get_string('transmessage', 'block_curr_admin'), 0, 0, 'C', 0);
             $this->newpdf->Ln(0.15);
             $this->newpdf->Ln(0.15);
             $this->newpdf->SetFont('Arial', '', 8);
             /// Set the left, middle and right columns.
             $leftcol = array();
             $middcol = array();
             $rghtcol = array();
             $leftcol[] = cm_fullname($this->user);
             switch ($this->user->gender) {
                 case 'M':
                 case 'm':
                     $gender = get_string('male', 'block_curr_admin');
                     break;
                 case 'F':
                 case 'f':
                     $gender = get_string('female', 'block_curr_admin');
                     break;
                 default:
                     $gender = get_string('unknown', 'block_curr_admin');
                     break;
             }
             $middcol[] = get_string('sex', 'block_curr_admin');
             $rghtcol[] = $gender;
             $bday = cm_timestring_to_date($this->user->birthdate);
             $leftcol[] = $this->user->address;
             $middcol[] = get_string('born', 'block_curr_admin');
             $rghtcol[] = $bday;
             if (!empty($this->user->origenroldate)) {
                 $enroldate = cm_timestring_to_date($this->user->origenroldate);
             } else {
                 if (!empty($this->user->timecreated)) {
                     $enroldate = cm_timestamp_to_date($this->user->timecreated);
                 } else {
                     $enroldate = get_string('unknown', 'block_curr_admin');
                 }
             }
             if (!empty($this->user->address2)) {
                 $leftcol[] = $this->user->address2;
             }
             $middcol[] = get_string('registrationdate', 'block_curr_admin');
             $rghtcol[] = $enroldate;
             $text = !empty($this->user->city) ? s($this->user->city) : '';
             $text .= !empty($this->user->state) ? (!empty($text) ? ', ' : '') . $this->user->state : '';
             $text .= !empty($this->user->postalcode) ? (!empty($text) ? ' ' : '') . s($this->user->postalcode) : '';
             $text .= !empty($this->user->country) ? (!empty($text) ? ' ' : '') . cm_get_country($this->user->country) : '';
             $leftcol[] = $text;
             $middcol[] = get_string('nuident', 'block_curr_admin');
             $rghtcol[] = $this->user->idnumber;
             $entrycredstr = get_string('entrycred', 'block_curr_admin') . ': ' . $this->user->entrycred;
             if ($this->newpdf->GetStringWidth($entrycredstr) > $half) {
                 if ($lines = $this->split_lines($entrycredstr, $half)) {
                     foreach ($lines as $line) {
                         $leftcol[] = $line;
                     }
                 }
             } else {
                 $leftcol[] = $entrycredstr;
             }
             $middcol[] = get_string('degree', 'block_curr_admin') . ':';
             $rghtcol[] = $this->user->degree;
             $leftcol[] = get_string('awards', 'block_curr_admin') . ': ' . $this->user->awards;
             foreach ($leftcol as $idx => $lefttxt) {
                 if (isset($middcol[$idx])) {
                     $this->newpdf->Cell($half, 0.2, $lefttxt, 0, 0, 'L', 0);
                     $this->newpdf->Cell($qrtr, 0.2, $middcol[$idx], 0, 0, 'L', 0);
                     $this->newpdf->Cell($qrtr, 0.2, $rghtcol[$idx], 0, 0, 'L', 0);
                 } else {
                     $this->newpdf->Cell($full, 0.2, $lefttxt, 0, 0, 'L', 0);
                 }
                 $this->newpdf->Ln(0.15);
             }
             $twidth = 0;
             $heights = array();
             $widths = array();
             $hmap = array();
             $rownum = 0;
             $this->newpdf->SetFont('Arial', '', 7);
             /// PASS 1 - Calculate sizes.
             foreach ($this->headers as $id => $header) {
                 $widths[$id] = $this->newpdf->GetStringWidth($header) + 0.2;
                 $twidth += $widths[$id];
             }
             $row = 0;
             foreach ($this->rawdata as $curid => $curlist) {
                 foreach ($curlist->data as $datum) {
                     if (!isset($heights[$row])) {
                         $heights[$row] = 0;
                     }
                     foreach ($this->headers as $id => $header) {
                         if (isset($datum->{$id})) {
                             $width = $this->newpdf->GetStringWidth($datum->{$id}) + 0.2;
                             if ($width > $widths[$id]) {
                                 $lines = ceil($width / $widths[$id]);
                                 $lines = 1;
                                 $widths[$id] = $width;
                             } else {
                                 $lines = 1;
                             }
                             $height = $lines * 0.2;
                             if ($height > $heights[$row]) {
                                 $heights[$row] = $height;
                             }
                         }
                     }
                     $row++;
                 }
             }
             /// Calculate the width of the table...
             $twidth = 0;
             foreach ($widths as $width) {
                 $twidth += $width;
             }
             $curx = 0.2;
             $cury = $this->newpdf->GetY() + 0.1;
             $endx = 8.300000000000001;
             $endy = $cury;
             $this->newpdf->Line($marginx, $cury, 8.5 - $marginx, $endy);
             $this->newpdf->Ln(0.2);
             /// Readjust the left margin according to the total width...
             $marginx = (8.5 - $twidth) / 2.0;
             $this->newpdf->setMargins($marginx, $marginy);
             //                $this->newpdf->SetX($marginx);
             $this->newpdf->Cell(8.300000000000001, 0.2, get_string('transmessage1', 'block_curr_admin'), 0, 0, 'L', 0);
             $this->newpdf->Ln(0.15);
             $this->newpdf->Cell(8.300000000000001, 0.2, get_string('transmessage2', 'block_curr_admin'), 0, 0, 'L', 0);
             $this->newpdf->Ln(0.15);
             $this->newpdf->Ln(0.15);
             $leftsummary = array();
             $rightsummary = array();
             foreach ($this->rawdata as $curid => $curlist) {
                 foreach ($this->headers as $id => $header) {
                     $text = str_replace(' ', "\n", $header);
                     $this->newpdf->Cell($widths[$id], 0.2, "{$text}", 1, 0, 'C', 1);
                 }
                 $this->newpdf->Ln();
                 $row = 0;
                 foreach ($curlist->data as $datum) {
                     if (is_array($datum) && strtolower($datum[0]) == 'hr') {
                         $curx = $this->newpdf->GetX();
                         $cury = $this->newpdf->GetY() + 0.1;
                         $endx = 0;
                         $endy = $cury;
                         foreach ($widths as $width) {
                             $endx += $width;
                         }
                         $this->newpdf->Line($curx, $cury, $endx, $endy);
                         $this->newpdf->SetX($curx + 0.1);
                     } else {
                         foreach ($this->headers as $id => $header) {
                             $text = '';
                             if (isset($datum->{$id})) {
                                 $text = $datum->{$id};
                             }
                             $this->newpdf->Cell($widths[$id], $heights[$row], $text, 0, 0, 'L', 0);
                         }
                     }
                     $this->newpdf->Ln();
                     $row++;
                 }
                 $curx = $marginx;
                 $cury = $this->newpdf->GetY() + 0.1;
                 $endx = 8.5 - $marginx;
                 $endy = $cury;
                 $this->newpdf->Line($curx, $cury, $endx, $endy);
                 $this->newpdf->Ln(0.2);
                 $this->newpdf->Write(0.2, "\n");
                 if ($curlist->numcredits > 0) {
                     $gpa = sprintf('%1.2f', (double) $curlist->gpa / (double) $curlist->numcredits);
                 } else {
                     $gpa = '0.0';
                 }
                 $leftsummary[] = get_string('total_credits', 'block_curr_admin', $curlist->curriculumname) . ": {$curlist->numcredits}";
                 $rightsummary[] = "{$curlist->curriculumname} Grade Point Average: {$gpa}";
             }
             foreach ($leftsummary as $idx => $lsummary) {
                 $this->newpdf->Cell(4.25, 0.2, $lsummary, 0, 0, 'L', 0);
                 $this->newpdf->Cell(4.25, 0.2, $rightsummary[$idx], 0, 0, 'L', 0);
                 $this->newpdf->Ln(0.15);
             }
             $this->newpdf->Ln(0.15);
             $this->newpdf->Cell(4.25, 0.2, get_string('transfercredits', 'block_curr_admin') . ": {$this->user->transfercredits}", 0, 0, 'L', 0);
             $this->newpdf->Ln(0.75);
             /// Signature line:
             $curx = $this->newpdf->GetX();
             $cury = $this->newpdf->GetY() + 0.1;
             $endx = 0;
             $endy = $cury;
             foreach ($widths as $width) {
                 $endx += $width;
             }
             $this->newpdf->Line($marginx, $cury, 8.5 - $marginx, $endy);
             $this->newpdf->Ln(0.15);
             $half = (8.5 - 2 * $marginx) / 2.0;
             $this->newpdf->Cell($half, 0.2, get_string('registrar', 'block_curr_admin'), 0, 0, 'L', 0);
             $this->newpdf->Cell($half, 0.2, get_string('date', 'block_curr_admin'), 0, 0, 'L', 0);
             $this->newpdf->Output($filename, 'I');
             break;
         default:
             return $output;
             break;
     }
 }