/** Configurable Reports * A Moodle block for creating customizable reports * @package blocks * @author: Juan leyva <http://www.twitter.com/jleyvadelgado> * @date: 2009 */ function export_report($report) { global $DB, $CFG; require_once $CFG->libdir . '/csvlib.class.php'; $table = $report->table; $matrix = array(); $filename = 'report'; if (!empty($table->head)) { $countcols = count($table->head); $keys = array_keys($table->head); $lastkey = end($keys); foreach ($table->head as $key => $heading) { $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading)))); } } if (!empty($table->data)) { foreach ($table->data as $rkey => $row) { foreach ($row as $key => $item) { $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item)))); } } } $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); foreach ($matrix as $ri => $col) { $csvexport->add_data($col); } $csvexport->download_file(); exit; }
public function print_grades() { global $CFG; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}"); $csvexport = new csv_export_writer($this->separator); $csvexport->set_filename($downloadfilename); // Print names of all the fields $exporttitle = array(); foreach ($profilefields as $field) { $exporttitle[] = $field->fullname; } if (!$this->onlyactive) { $exporttitle[] = get_string("suspended"); } // Add a feedback column. foreach ($this->columns as $grade_item) { $exporttitle[] = $this->format_column_name($grade_item); if ($this->export_feedback) { $exporttitle[] = $this->format_column_name($grade_item, true); } } $csvexport->add_data($exporttitle); // Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { $exportdata = array(); $user = $userdata->user; foreach ($profilefields as $field) { $fieldvalue = grade_helper::get_user_field_value($user, $field); $exportdata[] = $fieldvalue; } if (!$this->onlyactive) { $issuspended = $user->suspendedenrolment ? get_string('yes') : ''; $exportdata[] = $issuspended; } foreach ($userdata->grades as $itemid => $grade) { if ($export_tracking) { $status = $geub->track($grade); } $exportdata[] = $this->format_grade($grade); if ($this->export_feedback) { $exportdata[] = $this->format_feedback($userdata->feedbacks[$itemid]); } } $csvexport->add_data($exportdata); } $gui->close(); $geub->close(); $csvexport->download_file(); exit; }
function report_download_csv($fields, $data, $reportname = 'reportincsv') { $filename = clean_filename($reportname); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); foreach ($data as $eachrow) { $csvexport->add_data($eachrow); } $csvexport->download_file(); }
public function test_csv_functions() { $csvexport = new csv_export_writer(); $csvexport->set_filename('unittest'); foreach ($this->testdata as $data) { $csvexport->add_data($data); } $csvoutput = $csvexport->print_csv_data(true); $this->assertEquals($csvoutput, $this->teststring); $test_data = csv_export_writer::print_array($this->testdata, 'comma', '"', true); $this->assertEquals($test_data, $this->teststring); }
function user_download_csv($fields) { global $CFG; require_once($CFG->libdir . '/csvlib.class.php'); $filename = clean_filename(get_string('course', 'local_cobaltcourses')); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $userprofiledata = array(); $csvexport->add_data($userprofiledata); $csvexport->download_file(); die; }
function user_download_csv($fields) { global $CFG; require_once($CFG->libdir . '/csvlib.class.php'); $filename = clean_filename('Departments'); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $userprofiledata = array(); $csvexport->add_data($userprofiledata); $csvexport->download_file(); die; }
function user_download_csv($fields) { global $CFG; require_once($CFG->libdir . '/csvlib.class.php'); $filename = clean_filename('Users sample'); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $userprofiledata = array('lp_shortname','testuser'); $csvexport->add_data($userprofiledata); $csvexport->download_file(); die; }
public function test_csv_functions() { $csvexport = new csv_export_writer(); $csvexport->set_filename('unittest'); foreach ($this->testdata as $data) { $csvexport->add_data($data); } $csvoutput = $csvexport->print_csv_data(true); $this->assertEquals($csvoutput, $this->teststring); $test_data = csv_export_writer::print_array($this->testdata, 'comma', '"', true); $this->assertEquals($test_data, $this->teststring); // Testing that the content is imported correctly. $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring, 'utf-8', 'comma'); $csvimport->init(); $dataset = array(); $dataset[] = $csvimport->get_columns(); while ($record = $csvimport->next()) { $dataset[] = $record; } $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($dataset, $this->testdata); // Testing for the wrong count of columns. $errortext = get_string('csvweirdcolumns', 'error'); $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring2, 'utf-8', 'comma'); $importerror = $csvimport->get_error(); $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($importerror, $errortext); // Testing for empty content $errortext = get_string('csvemptyfile', 'error'); $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring3, 'utf-8', 'comma'); $importerror = $csvimport->get_error(); $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($importerror, $errortext); }
public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->libdir . '/csvlib.class.php'; $username = $this->arguments[0]; $filename = $this->expandedOptions['name']; $user = get_user_by_name($username); if (!$user) { cli_error("User not found."); } else { $userid = $user->id; } $fields = array('id' => 'id', 'username' => 'username', 'email' => 'email', 'firstname' => 'firstname', 'lastname' => 'lastname', 'idnumber' => 'idnumber', 'institution' => 'institution', 'department' => 'department', 'phone1' => 'phone1', 'phone2' => 'phone2', 'city' => 'city', 'url' => 'url', 'icq' => 'icq', 'skype' => 'skype', 'aim' => 'aim', 'yahoo' => 'yahoo', 'msn' => 'msn', 'country' => 'country'); if ($extrafields = $DB->get_records('user_info_field')) { foreach ($extrafields as $n => $v) { $fields['profile_field_' . $v->shortname] = 'profile_field_' . $v->shortname; } } $csvexport = new \csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $row = array(); profile_load_data($user); $userprofiledata = array(); foreach ($fields as $field => $unused) { if (is_array($user->{$field})) { $userprofiledata[] = reset($user->{$field}); } else { $userprofiledata[] = $user->{$field}; } } $csvexport->add_data($userprofiledata); file_put_contents($filename, $csvexport->print_csv_data(true)); echo "User " . $user->username . " successfully downloaded\n"; }
if ($users && in_array($USER->id, array_keys($users))) { $allow_marking = true; $allow_marking_criteria = $rcriterion->id; break; } } } } /* * Setup page header */ if ($csv) { $shortname = format_string($course->shortname, true, array('context' => $context)); $shortname = preg_replace('/[^a-z0-9-]/', '_', core_text::strtolower(strip_tags($shortname))); $export = new csv_export_writer(); $export->set_filename('completion-' . $shortname); } else { // Navigation and header $strcompletion = get_string('coursecompletion'); $PAGE->set_title($strcompletion); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); $PAGE->requires->js('/report/completion/textrotate.js'); $PAGE->requires->js_function_call('textrotate_init', null, true); // Handle groups (if enabled) groups_print_course_menu($course, $CFG->wwwroot . '/report/completion/?course=' . $course->id); } // Generate where clause $where = array(); $where_params = array(); if ($sifirst !== 'all') {
// You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Internal library of functions for module ratingallocate, subpart csv_export. * * * @package mod_ratingallocate * @copyright 2014 Max Schulze, C Usener * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once '../../config.php'; // to include $CFG, for example require_once $CFG->libdir . '/csvlib.class.php'; require_once './locallib.php'; $id = required_param('id', PARAM_INT); // course_module ID, or $cm = get_coursemodule_from_id('ratingallocate', $id, 0, false, MUST_EXIST); $course = get_course($cm->course); $ratingallocate = $DB->get_record('ratingallocate', array('id' => $cm->instance), '*', MUST_EXIST); require_login($course, true, $cm); $context = context_module::instance($cm->id); require_capability('mod/ratingallocate:export_ratings', $context); $ratingallocateobj = new ratingallocate($ratingallocate, $course, $cm, $context); global $DB; // print all the exported data here $downloadfilename = clean_filename('export_ratings_' . $ratingallocateobj->ratingallocate->name); $csvexport = new csv_export_writer('semicolon'); $csvexport->set_filename($downloadfilename); $renderer = $PAGE->get_renderer('mod_ratingallocate'); $renderer->ratings_csv_for_ratingallocate($ratingallocateobj, $csvexport); $csvexport->download_file();
/** * Creates a file for downloading an array into a deliminated format. * This function is useful if you are happy with the defaults and all of your * information is in one array. * * @param string $filename The filename of the file being created. * @param array $records An array of information to be converted. * @param string $delimiter The name of the delimiter. Supported types(comma, tab, semicolon, colon, cfg) * @param string $enclosure How speical fields are enclosed. */ public static function download_array($filename, array &$records, $delimiter = 'comma', $enclosure = '"') { $csvdata = new csv_export_writer($delimiter, $enclosure); $csvdata->set_filename($filename); foreach ($records as $row) { $csvdata->add_data($row); } $csvdata->download_file(); }
/** * Save requested users to a comma separated values (CSV) file. * * @return csv_export_writer The csv file object. */ protected function save_users_to_csv() { global $DB; $csv = new csv_export_writer($this->delimiter); $csv->set_filename('users'); $maxrolesnumber = 0; // Getting the maximum number of roles a user can have. foreach ($this->contents as $key => $user) { $rolesnumber = count($user->roles); if ($rolesnumber > $maxrolesnumber) { $maxrolesnumber = $rolesnumber; } } // Saving field names. $userfields = $this->fields; if ($this->useoverrides) { foreach ($this->overrides as $field => $value) { if (!array_search($field, $userfields)) { $userfields[] = $field; } } } $row = $userfields; if ($maxrolesnumber > 0) { for ($i = 1; $i <= $maxrolesnumber; $i++) { $coursename = 'course' . $i; $rolename = 'role' . $i; $row[] = $coursename; $row[] = $rolename; } } $csv->add_data($row); $columnsnumber = count($row); foreach ($this->contents as $key => $user) { if (!empty($user->roles)) { $row = array(); foreach ($userfields as $key => $field) { $row[] = $user->{$field}; } foreach ($user->roles as $key => $rolesarray) { foreach ($rolesarray as $role => $course) { $row[] = $course; $row[] = $role; } } // Adding blank columns until we have the same number of columns. $no = count($row); while ($no < $columnsnumber) { $row[] = ''; $no++; } $csv->add_data($row); } } return $csv; }
/** * Trigger a download of a csv export of the search results. * * @access public * @return void */ public function download_csv() { $csv = new \csv_export_writer(); $csv->set_filename('mediacollection_search'); $csv->add_data(array(get_string('caption', 'mod_mediagallery'), get_string('gallery', 'mod_mediagallery'), get_string('creator', 'mod_mediagallery'), get_string('groups'), get_string('roles'))); foreach ($this->results as $row) { $csv->add_data(array($row->itemcaption, $row->galleryname, $row->creator, implode(', ', $row->groups), implode(', ', $row->roles))); } $csv->download_file(); exit; }
require_once($CFG->libdir . '/csvlib.class.php'); //$table = $report->table; $matrix = array(); $filename = 'report'; if (!empty($table->head)) { $countcols = count($table->head); $keys = array_keys($table->head); $lastkey = end($keys); foreach ($table->head as $key => $heading) { $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading)))); } } if (!empty($table->data)) { foreach ($table->data as $rkey => $row) { foreach ($row as $key => $item) { $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item)))); } } } $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); foreach ($matrix as $ri => $col) { $csvexport->add_data($col); } $csvexport->download_file(); exit;
public static function __getCourseResourceCommentsExport($userid, $recordrow) { global $CFG, $DB; require_once $CFG->libdir . '/csvlib.class.php'; $fields = array('Course Name' => 'Courses', 'File Name' => 'File Name', 'Comments' => 'Comments'); $filename = time(); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); if ($recordrow != "") { $fav_comment_sql = 'SELECT urc.id AS commentid, r.name AS resource_name, c.fullname AS course_name, urc.comment FROM mdl_user_resource_comments urc JOIN mdl_course_modules cm ON cm.id = urc.coursemoduleid JOIN mdl_course c ON cm.course = c.id JOIN mdl_resource r ON cm.instance = r.id WHERE urc.userid = ' . $userid . " AND TRIM(COALESCE(urc.comment, '')) != '' AND urc.id IN({$recordrow}) ORDER BY urc.id DESC"; } else { $fav_comment_sql = "SELECT urc.id AS commentid, r.name AS resource_name, c.fullname AS course_name, urc.comment\n\t\t\t\tFROM mdl_user_resource_comments urc\n\t\t\t\t JOIN mdl_course_modules cm ON cm.id = urc.coursemoduleid\n\t\t\t\t JOIN mdl_course c ON cm.course = c.id\n\t\t\t\t JOIN mdl_resource r ON cm.instance = r.id\n\t\t\t\tWHERE urc.userid = '{$userid}' AND TRIM(COALESCE(urc.comment, '')) != '' ORDER BY urc.id DESC"; } $comments = $DB->get_recordset_sql($fav_comment_sql); if (!empty($comments)) { foreach ($comments as $comment) { $commentsdata['Course Name'] = $comment->course_name; //$commentsdata['File Name'] = $comment->resource_name; $resource_name = explode(": ", $comment->resource_name); if ($resource_name[1] != "") { $commentsdata['File Name'] = $resource_name[1]; } else { $commentsdata['File Name'] = $resource_name[0]; } $commentsdata['Comments'] = $comment->comment; $csvexport->add_data($commentsdata); } } $csvexport->download_file(); exit; }
} $records=$DB->get_records_sql($sql); $fields = array('studentname'=> 'studentname'); $sessions=array(); foreach ($records as $record) { $fields[$record->sessdates]= $record->sessdates; $sessions[$record->id]=$record->id; } $usersql="SELECT u.id,u.firstname,u.lastname FROM {user} u,{local_user_clclasses} c WHERE u.id=c.userid AND c.classid={$classid}"; $userlists=$DB->get_records_sql($usersql); $workbook = new csv_export_writer(''); $filename = clean_filename('userlist'); $workbook->set_filename($filename); $worksheet = array(); $worksheet[0] = $workbook->add_data($fields); $sheetrow = 1; foreach ($userlists as $userlist) { $post = array(); $post[] = $userlist->firstname.$userlist->lastname; foreach($sessions as $key=>$v) { //sessid-userid $post[]=$key.'-'.$userlist->id; } $workbook->add_data($post); $sheetrow++;
function user_download_csv($fields) { global $CFG, $SESSION, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->libdir . '/csvlib.class.php'; $filename = clean_filename(get_string('users')); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); foreach ($SESSION->bulk_users as $userid) { $row = array(); if (!($user = $DB->get_record('user', array('id' => $userid)))) { continue; } profile_load_data($user); $userprofiledata = array(); foreach ($fields as $field => $unused) { // Custom user profile textarea fields come in an array // The first element is the text and the second is the format. // We only take the text. if (is_array($user->{$field})) { $userprofiledata[] = reset($user->{$field}); } else { $userprofiledata[] = $user->{$field}; } } $csvexport->add_data($userprofiledata); } $csvexport->download_file(); die; }
public function __analyseExport($type, $retailer, $store, $region, $country, $course, $team, $sortBy, $fieldsval, $keyword, $isshowreport, $recordrow) { global $CFG, $DB, $SESSION; require_once $CFG->libdir . '/csvlib.class.php'; $useragent = new uagent_info(); if ($useragent->DetectIpad() || $useragent->DetectIphoneOrIpod() || $useragent->DetectAndroid() || $useragent->DetectIosNative()) { $csvexport = new csv_export_writer(); $download_method = 'download_file'; } else { $csvexport = new csv_export_writer('tab'); $download_method = 'download_file_for_excel'; } if ($recordrow != '') { $fields = array('Region' => 'Region', 'Country' => 'Country', 'Retailer' => 'Retailer', 'Store' => 'Store', 'Course' => 'Course', 'First Name' => 'First Name', 'Last Name' => 'Last Name', 'Job Title' => 'Job Title', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); $filename = time(); $csvexport->set_filename($filename); $csvexport->add_data($fields); if (empty($sortBy)) { $sortBy = 'firstname'; $sortMode = 'ASC'; } else { list($sortBy, $sortMode) = explode(' ', $sortBy); } $recordrow = explode(',', $recordrow); $reportsDetails = $SESSION->reports_current_page; foreach ($reportsDetails as $id => &$reportsDetail) { if (!in_array($id, $recordrow)) { unset($reportsDetails[$id]); } } unset($reportsDetail); foreach ($reportsDetails as $kReportsDetails => $vReportDetails) { $userprofiledata['Region'] = $vReportDetails->region; $userprofiledata['Country'] = $vReportDetails->country; $userprofiledata['Retailer'] = $vReportDetails->retailer; $userprofiledata['Store'] = $vReportDetails->store; $userprofiledata['Course'] = $vReportDetails->fullname; $userprofiledata['First Name'] = $vReportDetails->firstname; $userprofiledata['Last Name'] = $vReportDetails->lastname; $userprofiledata['Job Title'] = $vReportDetails->jobtitle; $userprofiledata['Course Points'] = $vReportDetails->points; $userprofiledata['Total Points'] = $vReportDetails->totalpoints; $csvexport->add_data($userprofiledata); $i++; } $csvexport->{$download_method}(); exit; } if ($isshowreport == 'true') { if ($type == 'user' || $type == 'course') { $fields = array('Region' => 'Region', 'Country' => 'Country', 'Retailer' => 'Retailer', 'Store' => 'Store', 'Course' => 'Course', 'First Name' => 'First Name', 'Last Name' => 'Last Name', 'Job Title' => 'Job Title', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); //$filename = clean_filename(get_string('users')); $filename = time(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $region = explode(",", $region); $country = explode(",", $country); $retailer = explode(",", $retailer); $store = explode(",", $store); $course = explode(",", $course); if ($type == 'user' || $type == 'course') { if (in_array("sel_all", $region) || in_array("null", $country)) { $regionstr = ''; } else { $regionstr = implode('~', $region); } if (in_array("sel_all", $country) || in_array("null", $country)) { $countrystr = ''; } else { $countrystr = implode('~', $country); } if (in_array("sel_all", $retailer) || in_array("null", $retailer)) { $retailerstr = ''; } else { $retailerstr = implode('~', $retailer); } if (in_array("sel_all", $store) || in_array("null", $store)) { $storestr = ''; } else { $storestr = implode('~', $store); } if (in_array("sel_all", $course) || in_array("null", $course)) { $coursestr = ''; } else { $coursestr = implode('~', $course); } if (empty($sortBy)) { $sortBy = 'firstname'; $sortMode = 'ASC'; } else { list($sortBy, $sortMode) = explode(' ', $sortBy); } /* CALL get_mdl_reports_dtl ( @v_region := '', @v_country := '', @v_retailer := '', @v_store := '', @v_course := '', @v_username := '******', @v_email := 'terasima.ibuki@rainbow.plala.or.jp~whyunwhaya@nate.com', @v_sortby := 'lastname', @v_sortmode := 'desc', @v_offset := '0', @v_limit := '25' ) */ $reportsSPCall = "CALL get_mdl_reports_dtl ('{$regionstr}','{$countrystr}','{$retailerstr}','{$storestr}','{$coursestr}', " . "'{$sortBy}', '{$sortMode}', '', '')"; $reportsDetails = $DB->get_records_sql($reportsSPCall); } foreach ($reportsDetails as $kReportsDetails => $vReportDetails) { $userprofiledata['Region'] = $vReportDetails->region; $userprofiledata['Country'] = $vReportDetails->country; $userprofiledata['Retailer'] = $vReportDetails->retailer; $userprofiledata['Store'] = $vReportDetails->store; $userprofiledata['Course'] = $vReportDetails->fullname; $userprofiledata['First Name'] = $vReportDetails->firstname; $userprofiledata['Last Name'] = $vReportDetails->lastname; $userprofiledata['Job Title'] = $vReportDetails->jobtitle; $userprofiledata['Course Points'] = $vReportDetails->points; $userprofiledata['Total Points'] = $vReportDetails->totalpoints; $csvexport->add_data($userprofiledata); $i++; } $csvexport->{$download_method}(); exit; } } else { $filename = time(); $csvexport->set_filename($filename); $fields = array('Region' => 'Region', 'Country' => 'Country', 'Retailer' => 'Retailer', 'Store' => 'Store', 'Course' => 'Course', 'First Name' => 'First Name', 'Last Name' => 'Last Name', 'Job Title' => 'Job Title', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); $csvexport->add_data($fields); if (empty($sortBy)) { $sortBy = 'firstname'; $sortMode = 'ASC'; } else { list($sortBy, $sortMode) = explode(' ', $sortBy); } $fieldsArr = explode(',', $fieldsval); $coursekey = array_search('fullname', $fieldsArr); if (!is_bool($coursekey)) { $fieldsArr[$coursekey] = 'course'; } $fieldstilde = implode('~', $fieldsArr); /* CALL get_mdl_reports_dtl ( @v_region := '', @v_country := '', @v_retailer := '', @v_store := '', @v_course := '', @v_username := '******', @v_email := 'terasima.ibuki@rainbow.plala.or.jp~whyunwhaya@nate.com', @v_sortby := 'lastname', @v_sortmode := 'desc', @v_offset := '0', @v_limit := '25' ) */ $reportsSPCall = "CALL get_mdl_reports_search ('{$keyword}','{$fieldstilde}'," . "'{$sortBy}', '{$sortMode}', '', '')"; $reportsDetails = $DB->get_records_sql($reportsSPCall); $i = 0; foreach ($reportsDetails as $kReportsDetails => $vReportDetails) { $userprofiledata['Region'] = $vReportDetails->region; $userprofiledata['Country'] = $vReportDetails->country; $userprofiledata['Retailer'] = $vReportDetails->retailer; $userprofiledata['Store'] = $vReportDetails->store; $userprofiledata['Course'] = $vReportDetails->fullname; $userprofiledata['First Name'] = $vReportDetails->firstname; $userprofiledata['Last Name'] = $vReportDetails->lastname; $userprofiledata['Job Title'] = $vReportDetails->jobtitle; $userprofiledata['Course Points'] = $vReportDetails->points; $userprofiledata['Total Points'] = $vReportDetails->totalpoints; $csvexport->add_data($userprofiledata); $i++; } $csvexport->{$download_method}(); exit; } }
function print_log_csv($course, $user, $date, $order = 'l.time DESC', $modname, $modid, $modaction, $groupid) { global $DB, $CFG; require_once $CFG->libdir . '/csvlib.class.php'; $csvexporter = new csv_export_writer('tab'); $header = array(); $header[] = get_string('course'); $header[] = get_string('time'); $header[] = get_string('ip_address'); $header[] = get_string('fullnameuser'); $header[] = get_string('action'); $header[] = get_string('info'); 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"); $csvexporter->set_filename('logs', '.txt'); $title = array(get_string('savedat') . userdate(time(), $strftimedatetime)); $csvexporter->add_data($title); $csvexporter->add_data($header); if (empty($logs['logs'])) { return true; } 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 && is_numeric($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 $coursecontext = context_course::instance($course->id); $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext)); $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext)); $actionurl = $CFG->wwwroot . make_log_url($log->module, $log->url); $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module . ' ' . $log->action . ' (' . $actionurl . ')', $log->info); $csvexporter->add_data($row); } $csvexporter->download_file(); return true; }
public function send($filename) { $writer = new csv_export_writer($this->delimiter); $writer->set_filename($filename); foreach ($this->pages as $page) { if ($page->title) { $writer->add_data(array('*** ' . $page->title . ' ***')); } // Find extent of the table. $rows = $this->get_row_count($page); $cols = $this->get_col_count($page); for ($row = 0; $row < $rows; $row++) { $data = array(); $col = 0; while ($col < $cols) { if (isset($page->cells[$row][$col])) { $data[] = $page->cells[$row][$col]; } else { $data[] = ''; } $span = 1; if (isset($page->mergers[$row][$col])) { $mergewidth = (int) $page->mergers[$row][$col]; if ($mergewidth >= 1) { $span = $mergewidth; } } $col += $span; } $writer->add_data($data); } } $writer->download_file(); }
public function print_grades() { global $CFG; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}"); $csvexport = new csv_export_writer($this->separator); $csvexport->set_filename($downloadfilename); // $profilefields = array('idnumber','firstname'); // Print names of all the fields // $exporttitle = array(); $exporttitle = array('Client Code', 'Client Name', 'Qualification Code', 'Unit Code', 'Unit Start Date', 'Unit End Date', 'Outcome Code'); // foreach ($profilefields as $field) { // $exporttitle[] = $field->fullname; // } // if (!$this->onlyactive) { // $exporttitle[] = get_string("suspended"); // } // Add a feedback column. // foreach ($this->columns as $grade_item) { // $exporttitle[] = $this->format_column_name($grade_item); // if ($this->export_feedback) { // $exporttitle[] = $this->format_column_name($grade_item, true); // } // } $csvexport->add_data($exporttitle); // Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { $user = $userdata->user; // foreach ($profilefields as $field) { // $fieldvalue = grade_helper::get_user_field_value($user, $field); // $exportdata[] = $fieldvalue; // } // if (!$this->onlyactive) { // $issuspended = ($user->suspendedenrolment) ? get_string('yes') : ''; // $exportdata[] = $issuspended; // } // foreach ($userdata->grades as $itemid => $grade) { // if ($export_tracking) { // $status = $geub->track($grade); // } // $exportdata[] = $this->format_grade($grade); // if ($this->export_feedback) { // $exportdata[] = $this->format_feedback($userdata->feedbacks[$itemid]); // } // } foreach ($this->columns as $itemid => $grade_item) { $exportdata = array(); $gradetxt = $this->format_grade($userdata->grades[$itemid]); $activity_start_date = $this->get_activity_start_date($this->course, $user, $grade_item); $grade_modified = $userdata->grades[$itemid]->timemodified; $client_name = $userdata->user->firstname . ' ' . $userdata->user->lastname; $client_code = $userdata->user->idnumber; $unit_code = $grade_item->itemname; $unit_start = $activity_start_date ? $activity_start_date->format('d/m/Y') : '-'; $unit_end = $grade_modified ? userdate($grade_modified, '%d/%m/%Y') : '-'; $course_code = $this->get_course_short_name($grade_item); $grade_name = 'grade_name'; if ($grade_item->itemtype == 'category') { $category_start_date = $this->get_category_start_date($this->course, $user, $grade_item); $unit_start = $category_start_date ? $category_start_date->format('d/m/Y') : '-'; } // get the status of this grade, and put it through track to get the status $g = new grade_export_update_buffer(); $grade_grade = new grade_grade(array('itemid' => $itemid, 'userid' => $user->id)); $status = $g->track($grade_grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { // $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>'; } else { $exportdata[] = $client_code; $exportdata[] = $client_name; $exportdata[] = $course_code; $exportdata[] = $unit_code; $exportdata[] = $unit_start; $exportdata[] = $unit_end; $exportdata[] = $gradetxt; $gradeupdated = true; } if ($grade_item->itemtype == 'category') { $csvexport->add_data($exportdata); } } } $gui->close(); $geub->close(); $csvexport->download_file(); exit; }
/** * 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 = ' '; $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 ' '; 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')); } }
public function test_csv_functions() { global $CFG; $csvexport = new csv_export_writer(); $csvexport->set_filename('unittest'); foreach ($this->testdata as $data) { $csvexport->add_data($data); } $csvoutput = $csvexport->print_csv_data(true); $this->assertEquals($csvoutput, $this->teststring); $test_data = csv_export_writer::print_array($this->testdata, 'comma', '"', true); $this->assertEquals($test_data, $this->teststring); // Testing that the content is imported correctly. $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring, 'utf-8', 'comma'); $csvimport->init(); $dataset = array(); $dataset[] = $csvimport->get_columns(); while ($record = $csvimport->next()) { $dataset[] = $record; } $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($dataset, $this->testdata); // Testing for the wrong count of columns. $errortext = get_string('csvweirdcolumns', 'error'); $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring2, 'utf-8', 'comma'); $importerror = $csvimport->get_error(); $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($importerror, $errortext); // Testing for empty content $errortext = get_string('csvemptyfile', 'error'); $iid = csv_import_reader::get_new_iid('lib'); $csvimport = new csv_import_reader($iid, 'lib'); $contentcount = $csvimport->load_csv_content($this->teststring3, 'utf-8', 'comma'); $importerror = $csvimport->get_error(); $csvimport->cleanup(); $csvimport->close(); $this->assertEquals($importerror, $errortext); // Testing for a tab separated file. // The tab separated file has a trailing tab and extra blank lines at the end of the file. $filename = $CFG->dirroot . '/lib/tests/fixtures/tabfile.csv'; $fp = fopen($filename, 'r'); $tabdata = fread($fp, filesize($filename)); fclose($fp); $iid = csv_import_reader::get_new_iid('tab'); $csvimport = new csv_import_reader($iid, 'tab'); $contentcount = $csvimport->load_csv_content($tabdata, 'utf-8', 'tab'); // This should import four rows including the headings. $this->assertEquals($contentcount, 4); // Testing for empty lines. $iid = csv_import_reader::get_new_iid('blanklines'); $csvimport = new csv_import_reader($iid, 'blanklines'); $contentcount = $csvimport->load_csv_content($this->teststring4, 'utf-8', 'comma'); // Five lines including the headings should be imported. $this->assertEquals($contentcount, 5); }
/** * 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 = 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. 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' => 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 if (!$groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', 'u.id', '', '', '', $currentgroup, '', false)) { 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), '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; $questioncount = get_scorm_question_count($scorm->id); $nbmaincolumns = count($columns); 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'); for($id = 0; $id < $questioncount; $id++) { if ($displayoptions['qtext']) { $table->no_sorting('question'.$id); } if ($displayoptions['resp']) { $table->no_sorting('response'.$id); } if ($displayoptions['right']) { $table->no_sorting('right'.$id); } } 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 '<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); foreach (get_all_user_name_fields() as $addname) { $user->$addname = $scouser->$addname; } $row[] = $OUTPUT->user_picture($user, array('courseid'=>$course->id)); } if (!$download) { $row[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$scouser->userid.'&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.'&user='******'&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 (isset($trackdata->score_max)) { $score .= '/'.$trackdata->score_max; } // 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.'&user='******'&attempt='.$scouser->attempt. '" title="'.get_string('details', 'scorm').'">'.$score.'</a>'; } else { $row[] = $score; } // interaction data for ($i=0; $i < $questioncount; $i++) { if ($displayoptions['qtext']) { $element='cmi.interactions_'.$i.'.id'; if (isset($trackdata->$element)) { $row[] = s($trackdata->$element); } else { $row[] = ' '; } } if ($displayoptions['resp']) { $element='cmi.interactions_'.$i.'.student_response'; if (isset($trackdata->$element)) { $row[] = s($trackdata->$element); } else { $row[] = ' '; } } 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[] = ' '; } } } //---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; } // complete the empty cells for ($i=0; $i < count($columns) - $nbmaincolumns; $i++) { $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') { $csvexport->add_data($row); } } 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 ' '; 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') { $csvexport->download_file(); exit; } } else { echo $OUTPUT->notification(get_string('noactivity', 'scorm')); } }// function ends
function user_download_csv($fields, $extrafields = array()) { global $CFG, $SESSION, $DB; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->libdir . '/csvlib.class.php'; $filename = clean_filename(get_string('users')); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $extrafield_sql = ''; foreach ($extrafields as $n => $v) { $extrafield_sql .= " MAX(IF(muif.shortname = '" . $v->shortname . "', muid.data, NULL)) profile_field_" . $v->shortname . ","; } $extrafield_sql = rtrim($extrafield_sql, ","); $idstoload = $SESSION->bulk_users; $users = array(); foreach (array_chunk($idstoload, 10000, true) as $user_id) { $userids = implode(",", $user_id); $users[] = $DB->get_records_sql("SELECT mu.*,\r\n {$extrafield_sql}\r\n FROM mdl_user AS mu\r\n LEFT JOIN mdl_user_info_data AS muid ON mu.id = muid.userid\r\n LEFT JOIN mdl_user_info_field AS muif ON muif.id = muid.fieldid\r\n WHERE mu.id IN ({$userids}) GROUP BY mu.id"); } foreach ($users as $userdetails) { foreach ($userdetails as $user) { $row = array(); #if (!$user = $DB->get_record('user', array('id'=>$userid))) { #continue; #} #profile_load_data($user); $userprofiledata = array(); foreach ($fields as $field => $unused) { // Custom user profile textarea fields come in an array // The first element is the text and the second is the format. // We only take the text. if (is_array($user->{$field})) { $userprofiledata[] = reset($user->{$field}); } else { $userprofiledata[] = $user->{$field}; } } $csvexport->add_data($userprofiledata); } } $csvexport->download_file(); die; }
function evapares_get_all_data($cmid, $evaparesname) { global $DB; $csv = new csv_export_writer("semicolon", '"'); $filename = "evapares_alldata_" . $evaparesname . "_" . date("d-m-Y", time()); $header = array("N" => "N", "Grupo" => "Grupo", "Alumno evaluado" => "Alumno evaluado", "Email" => "Email", "Alumno evaluador" => "Alumno evaluador", "Evaluación" => "Evaluación", "Tiempo de respuesta" => "Tiempo de respuesta", "Nota" => "Nota", "Stop" => "Stop", "Start" => "Start", "Continue" => "Continue", "P1" => "P1", "P2" => "P2", "P3" => "P3", "P4" => "P4", "P5" => "P5", "P6" => "P6", "P7" => "P7", "P8" => "P8", "P9" => "P9", "P10" => "P10", "P11" => "P11", "P12" => "P12"); $csv->add_data($header); $sqlfulldata = "SELECT ee.id, \r\n\t\t\tg.name AS gname, \r\n\t\t\tee.alu_evaluado_id AS evaluado,\r\n\t\t\tCONCAT(u.firstname, ' ', u.lastname) AS username,\r\n\t\t\tu.email,\r\n\t\t\tee.alu_evalua_id AS evaluator,\r\n\t\t\tee.iterations_id AS itid,\r\n\t\t\tei.evaluation_name as evaluacion,\r\n\t\t\tei.n_iteration AS inum,\r\n\t\t\tee.enddate,\r\n\t\t\tee.nota,\r\n\t\t\tee.ssc_stop AS stop, \r\n\t\t\tee.ssc_start AS start,\r\n\t\t\tee.ssc_continue AS cont\r\n\t\t\tFROM {user} AS u\r\n\t\t\tINNER JOIN {groups_members} AS gm ON (u.id = gm.userid)\r\n\t\t\tINNER JOIN {groups} AS g ON (gm.groupid = g.id)\r\n\t\t\tINNER JOIN {course} AS c ON (g.courseid = c.id)\r\n\t\t\tINNER JOIN {course_modules} AS cm ON (c.id = cm.course AND cm.id = ?)\r\n\t\t\tINNER JOIN {evapares_iterations} AS ei ON (cm.id = ei.evapares_id)\r\n\t\t\tINNER JOIN {evapares_evaluations} AS ee ON (ei.id = ee.iterations_id AND ee.alu_evaluado_id = u.id)\r\n\t\t\tORDER BY g.name, ei.id, ee.alu_evaluado_id"; $evaluations = $DB->get_recordset_sql($sqlfulldata, array($cmid)); $count = 1; foreach ($evaluations as $evaluation) { $row = array(); $row[] = $count; $row[] = $evaluation->gname; $row[] = $evaluation->username; $row[] = $evaluation->email; $row[] = "Anónimo"; $row[] = $evaluation->evaluacion; if ($evaluation->enddate != NULL) { $row[] = date("H:i - d/m/Y", $evaluation->enddate); } else { $row[] = "No realizado"; } $row[] = $evaluation->nota; $row[] = (string) $evaluation->stop; $row[] = (string) $evaluation->start; $row[] = (string) $evaluation->cont; $sqlanswers = "SELECT eha.id, \r\n\t\t\t\teq.n_of_question AS nquestion, \r\n\t\t\t\tea.number, \r\n\t\t\t\tea.text\r\n\t\t\t\tFROM {evapares_eval_has_answ} AS eha\r\n\t\t\t\tINNER JOIN {evapares_answers} AS ea ON (ea.id = eha.answers_id)\r\n\t\t\t\tINNER JOIN {evapares_questions} AS eq ON (ea.question_id AND eq.id)\r\n\t\t\t\tWHERE eha.evaluations_id = ?\r\n\t\t\t\tGROUP BY eha.id \r\n\t\t\t\tORDER BY eq.n_of_question"; // Have answers if ($answers = $DB->get_records_sql($sqlanswers, array($evaluation->id))) { foreach ($answers as $answer) { $row[] = $answer->number; } } else { for ($answer = 1; $answer <= 12; $answer++) { $row[] = "0"; } } $csv->add_data($row); $count++; } $evaluations->close(); $csv->set_filename($filename); $csv->download_file(); echo $csv->print_csv_data(); }
public function __analyseExport($type, $retailer, $store, $region, $country, $team, $sortBy, $recordrow) { global $CFG, $DB; require_once $CFG->libdir . '/csvlib.class.php'; $systemcontext = context_system::instance(); $response = new CliniqueServiceResponce(); if ($recordrow != '') { /*if($type == 'user') { $fields = array('Last Name' => 'Last Name', 'First Name' => 'First Name', 'Job Title' => 'Job Title', 'Course' => 'Course', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); } else {*/ $fields = array('Course' => 'Course', 'Last Name' => 'Last Name', 'First Name' => 'First Name', 'Job Title' => 'Job Title', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); // } //$filename = clean_filename(get_string('users')); $filename = time(); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $reportsDetails = array_values($DB->get_records_sql("SELECT fullname, lastname, firstname, jobtitle, points, totalpoints FROM {reports} WHERE id IN ({$recordrow})")); $reportcnt = count($reportsDetails); for ($i = 0; $i < $reportcnt; $i++) { /* if($type == 'user') { $userprofiledata['Last Name'] = $reportsDetails[$i]->lastname; $userprofiledata['First Name'] = $reportsDetails[$i]->firstname; $userprofiledata['Job Title'] = $reportsDetails[$i]->jobtitle; $userprofiledata['Course'] = $reportsDetails[$i]->fullname; if(empty($reportsDetails[$i]->points)){ $reportsDetails[$i]->points = 0; } $userprofiledata['Course Points'] = $reportsDetails[$i]->points; $userprofiledata['Total Points'] = $reportsDetails[$i]->totalpoints; } else {*/ $userprofiledata['Course'] = $reportsDetails[$i]->fullname; $userprofiledata['Last Name'] = $reportsDetails[$i]->lastname; $userprofiledata['First Name'] = $reportsDetails[$i]->firstname; $userprofiledata['Job Title'] = $reportsDetails[$i]->jobtitle; $userprofiledata['Course Points'] = $reportsDetails[$i]->points; $userprofiledata['Total Points'] = $reportsDetails[$i]->totalpoints; //} $csvexport->add_data($userprofiledata); } $csvexport->download_file(); exit; } if ($type == 'user' || $type == 'course') { $fields = array('Last Name' => 'Last Name', 'First Name' => 'First Name', 'Job Title' => 'Job Title', 'Course' => 'Course', 'Course Points' => 'Course Points', 'Total Points' => 'Total Points'); //$filename = clean_filename(get_string('users')); $filename = time(); $csvexport = new csv_export_writer(); $csvexport->set_filename($filename); $csvexport->add_data($fields); $where = "WHERE id!=''"; if ($region != '') { $where .= " AND region='" . $region . "'"; } if ($country != '') { $where .= " AND country='" . $country . "'"; } if ($retailer != '' && $retailer != 'null') { /*if($retailer == '') { $where .=" AND retailer =''"; } else {*/ if (is_array($retailer)) { foreach ($retailer as $key => $value) { $retailerstr .= '"' . $value . '",'; } } else { $retailerexp = explode(",", $retailer); foreach ($retailerexp as $key => $value) { $retailerstr .= '"' . $value . '",'; } } $retailersrtval = substr($retailerstr, 0, -1); $where .= " AND retailer IN(" . $retailersrtval . ")"; //} } if ($store != '' && $store != 'null') { /*if($store == '') { $where .=" AND store =''"; } else { */ if (is_array($store)) { foreach ($store as $key => $value) { $storestr .= '"' . $value . '",'; } } else { $storeexp = explode(",", $store); foreach ($storeexp as $key => $value) { $storestr .= '"' . $value . '",'; } } $storesrtval = substr($storestr, 0, -1); $where .= " AND store IN(" . $storesrtval . ")"; //} } if ($limit_start != '') { $start = $limit_start; } else { $start = 0; } if ($limit_end != '') { $end = $limit_end; } else { $end = 9; } if ($sortBy != "") { // sortby asc desc if ($sortBy == 'firstname DESC') { $sort = "firstname DESC"; } if ($sortBy == 'firstname ASC') { $sort = "firstname ASC"; } if ($sortBy == 'lastname DESC') { $sort = "lastname DESC"; } if ($sortBy == 'lastname ASC') { $sort = "lastname ASC"; } if ($sortBy == 'fullname DESC') { $sort = "fullname DESC"; } if ($sortBy == 'fullname ASC') { $sort = "fullname ASC"; } if ($sortBy == 'points ASC') { $sort = "points ASC"; } if ($sortBy == 'points DESC') { $sort = "points DESC"; } if ($sortBy == 'totalpoints ASC') { $sort = "totalpoints ASC"; } if ($sortBy == 'totalpoints DESC') { $sort = "totalpoints DESC"; } if ($sortBy == 'ASC') { $sort = "firstname ASC"; } } else { $sort = "firstname ASC"; } $reportsDetails = array_values($DB->get_records_sql("SELECT lastname, firstname, jobtitle, fullname, points, totalpoints FROM {reports} {$where} ORDER BY {$sort}")); $reportcnt = count($reportsDetails); for ($i = 0; $i < $reportcnt; $i++) { $userprofiledata['Last Name'] = $reportsDetails[$i]->lastname; $userprofiledata['First Name'] = $reportsDetails[$i]->firstname; $userprofiledata['Job Title'] = $reportsDetails[$i]->jobtitle; $userprofiledata['Course'] = $reportsDetails[$i]->fullname; $userprofiledata['Course Points'] = $reportsDetails[$i]->points; $userprofiledata['Total Points'] = $reportsDetails[$i]->totalpoints; $csvexport->add_data($userprofiledata); } $csvexport->download_file(); exit; } }