MDL-55532 gradebook: fix grade export to include category names
[moodle.git] / grade / export / lib.php
blob6dabe7a8906750b848f8ef0579f7e0a4c3405002
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 require_once($CFG->dirroot.'/lib/gradelib.php');
19 require_once($CFG->dirroot.'/grade/lib.php');
20 require_once($CFG->dirroot.'/grade/export/grade_export_form.php');
22 /**
23 * Base export class
25 abstract class grade_export {
27 public $plugin; // plgin name - must be filled in subclasses!
29 public $grade_items; // list of all course grade items
30 public $groupid; // groupid, 0 means all groups
31 public $course; // course object
32 public $columns; // array of grade_items selected for export
34 public $export_letters; // export letters
35 public $export_feedback; // export feedback
36 public $userkey; // export using private user key
38 public $updatedgradesonly; // only export updated grades
40 /**
41 * Grade display type (real, percentages or letter).
43 * This attribute is an integer for XML file export. Otherwise is an array for all other formats (ODS, XLS and TXT).
45 * @var $displaytype Grade display type constant (1, 2 or 3) or an array of display types where the key is the name
46 * and the value is the grade display type constant or 0 for unchecked display types.
47 * @access public.
49 public $displaytype;
50 public $decimalpoints; // number of decimal points for exports
51 public $onlyactive; // only include users with an active enrolment
52 public $usercustomfields; // include users custom fields
54 /**
55 * @deprecated since Moodle 2.8
56 * @var $previewrows Number of rows in preview.
58 public $previewrows;
60 /**
61 * Constructor should set up all the private variables ready to be pulled.
63 * This constructor used to accept the individual parameters as separate arguments, in
64 * 2.8 this was simplified to just accept the data from the moodle form.
66 * @access public
67 * @param object $course
68 * @param int $groupid
69 * @param stdClass|null $formdata
70 * @note Exporting as letters will lead to data loss if that exported set it re-imported.
72 public function __construct($course, $groupid, $formdata) {
73 if (func_num_args() != 3 || ($formdata != null && get_class($formdata) != "stdClass")) {
74 $args = func_get_args();
75 return call_user_func_array(array($this, "deprecated_constructor"), $args);
77 $this->course = $course;
78 $this->groupid = $groupid;
80 $this->grade_items = grade_item::fetch_all(array('courseid'=>$this->course->id));
82 $this->process_form($formdata);
85 /**
86 * Old deprecated constructor.
88 * This deprecated constructor accepts the individual parameters as separate arguments, in
89 * 2.8 this was simplified to just accept the data from the moodle form.
91 * @deprecated since 2.8 MDL-46548. Instead call the shortened constructor which accepts the data
92 * directly from the grade_export_form.
94 protected function deprecated_constructor($course,
95 $groupid=0,
96 $itemlist='',
97 $export_feedback=false,
98 $updatedgradesonly = false,
99 $displaytype = GRADE_DISPLAY_TYPE_REAL,
100 $decimalpoints = 2,
101 $onlyactive = false,
102 $usercustomfields = false) {
104 debugging('Many argument constructor for class "grade_export" is deprecated. Call the 3 argument version instead.', DEBUG_DEVELOPER);
106 $this->course = $course;
107 $this->groupid = $groupid;
109 $this->grade_items = grade_item::fetch_all(array('courseid'=>$this->course->id));
110 //Populating the columns here is required by /grade/export/(whatever)/export.php
111 //however index.php, when the form is submitted, will construct the collection here
112 //with an empty $itemlist then reconstruct it in process_form() using $formdata
113 $this->columns = array();
114 if (!empty($itemlist)) {
115 if ($itemlist=='-1') {
116 //user deselected all items
117 } else {
118 $itemids = explode(',', $itemlist);
119 // remove items that are not requested
120 foreach ($itemids as $itemid) {
121 if (array_key_exists($itemid, $this->grade_items)) {
122 $this->columns[$itemid] =& $this->grade_items[$itemid];
126 } else {
127 foreach ($this->grade_items as $itemid=>$unused) {
128 $this->columns[$itemid] =& $this->grade_items[$itemid];
132 $this->export_feedback = $export_feedback;
133 $this->userkey = '';
134 $this->previewrows = false;
135 $this->updatedgradesonly = $updatedgradesonly;
137 $this->displaytype = $displaytype;
138 $this->decimalpoints = $decimalpoints;
139 $this->onlyactive = $onlyactive;
140 $this->usercustomfields = $usercustomfields;
144 * Init object based using data from form
145 * @param object $formdata
147 function process_form($formdata) {
148 global $USER;
150 $this->columns = array();
151 if (!empty($formdata->itemids)) {
152 if ($formdata->itemids=='-1') {
153 //user deselected all items
154 } else {
155 foreach ($formdata->itemids as $itemid=>$selected) {
156 if ($selected and array_key_exists($itemid, $this->grade_items)) {
157 $this->columns[$itemid] =& $this->grade_items[$itemid];
161 } else {
162 foreach ($this->grade_items as $itemid=>$unused) {
163 $this->columns[$itemid] =& $this->grade_items[$itemid];
167 if (isset($formdata->key)) {
168 if ($formdata->key == 1 && isset($formdata->iprestriction) && isset($formdata->validuntil)) {
169 // Create a new key
170 $formdata->key = create_user_key('grade/export', $USER->id, $this->course->id, $formdata->iprestriction, $formdata->validuntil);
172 $this->userkey = $formdata->key;
175 if (isset($formdata->decimals)) {
176 $this->decimalpoints = $formdata->decimals;
179 if (isset($formdata->export_letters)) {
180 $this->export_letters = $formdata->export_letters;
183 if (isset($formdata->export_feedback)) {
184 $this->export_feedback = $formdata->export_feedback;
187 if (isset($formdata->export_onlyactive)) {
188 $this->onlyactive = $formdata->export_onlyactive;
191 if (isset($formdata->previewrows)) {
192 $this->previewrows = $formdata->previewrows;
195 if (isset($formdata->display)) {
196 $this->displaytype = $formdata->display;
198 // Used by grade exports which accept multiple display types.
199 // If the checkbox value is 0 (unchecked) then remove it.
200 if (is_array($formdata->display)) {
201 $this->displaytype = array_filter($formdata->display);
205 if (isset($formdata->updatedgradesonly)) {
206 $this->updatedgradesonly = $formdata->updatedgradesonly;
211 * Update exported field in grade_grades table
212 * @return boolean
214 public function track_exports() {
215 global $CFG;
217 /// Whether this plugin is entitled to update export time
218 if ($expplugins = explode(",", $CFG->gradeexport)) {
219 if (in_array($this->plugin, $expplugins)) {
220 return true;
221 } else {
222 return false;
224 } else {
225 return false;
230 * Returns string representation of final grade
231 * @param object $grade instance of grade_grade class
232 * @param integer $gradedisplayconst grade display type constant.
233 * @return string
235 public function format_grade($grade, $gradedisplayconst = null) {
236 $displaytype = $this->displaytype;
237 if (is_array($this->displaytype) && !is_null($gradedisplayconst)) {
238 $displaytype = $gradedisplayconst;
241 $gradeitem = $this->grade_items[$grade->itemid];
243 // We are going to store the min and max so that we can "reset" the grade_item for later.
244 $grademax = $gradeitem->grademax;
245 $grademin = $gradeitem->grademin;
247 // Updating grade_item with this grade_grades min and max.
248 $gradeitem->grademax = $grade->get_grade_max();
249 $gradeitem->grademin = $grade->get_grade_min();
251 $formattedgrade = grade_format_gradevalue($grade->finalgrade, $gradeitem, false, $displaytype, $this->decimalpoints);
253 // Resetting the grade item in case it is reused.
254 $gradeitem->grademax = $grademax;
255 $gradeitem->grademin = $grademin;
257 return $formattedgrade;
261 * Returns the name of column in export
262 * @param object $grade_item
263 * @param boolean $feedback feedback colum
264 * @param string $gradedisplayname grade display name.
265 * @return string
267 public function format_column_name($grade_item, $feedback=false, $gradedisplayname = null) {
268 $column = new stdClass();
270 if ($grade_item->itemtype == 'mod') {
271 $column->name = get_string('modulename', $grade_item->itemmodule).get_string('labelsep', 'langconfig').$grade_item->get_name();
272 } else {
273 $column->name = $grade_item->get_name(true);
276 // We can't have feedback and display type at the same time.
277 $column->extra = ($feedback) ? get_string('feedback') : get_string($gradedisplayname, 'grades');
279 return html_to_text(get_string('gradeexportcolumntype', 'grades', $column), 0, false);
283 * Returns formatted grade feedback
284 * @param object $feedback object with properties feedback and feedbackformat
285 * @return string
287 public function format_feedback($feedback) {
288 return strip_tags(format_text($feedback->feedback, $feedback->feedbackformat));
292 * Implemented by child class
294 public abstract function print_grades();
297 * Prints preview of exported grades on screen as a feedback mechanism
298 * @param bool $require_user_idnumber true means skip users without idnumber
299 * @deprecated since 2.8 MDL-46548. Previews are not useful on export.
301 public function display_preview($require_user_idnumber=false) {
302 global $OUTPUT;
304 debugging('function grade_export::display_preview is deprecated.', DEBUG_DEVELOPER);
306 $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
307 $formatoptions = new stdClass();
308 $formatoptions->para = false;
310 echo $OUTPUT->heading(get_string('previewrows', 'grades'));
312 echo '<table>';
313 echo '<tr>';
314 foreach ($userprofilefields as $field) {
315 echo '<th>' . $field->fullname . '</th>';
317 if (!$this->onlyactive) {
318 echo '<th>'.get_string("suspended")."</th>";
320 foreach ($this->columns as $grade_item) {
321 echo '<th>'.$this->format_column_name($grade_item).'</th>';
323 /// add a column_feedback column
324 if ($this->export_feedback) {
325 echo '<th>'.$this->format_column_name($grade_item, true).'</th>';
328 echo '</tr>';
329 /// Print all the lines of data.
330 $i = 0;
331 $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
332 $gui->require_active_enrolment($this->onlyactive);
333 $gui->allow_user_custom_fields($this->usercustomfields);
334 $gui->init();
335 while ($userdata = $gui->next_user()) {
336 // number of preview rows
337 if ($this->previewrows and $this->previewrows <= $i) {
338 break;
340 $user = $userdata->user;
341 if ($require_user_idnumber and empty($user->idnumber)) {
342 // some exports require user idnumber so we can match up students when importing the data
343 continue;
346 $gradeupdated = false; // if no grade is update at all for this user, do not display this row
347 $rowstr = '';
348 foreach ($this->columns as $itemid=>$unused) {
349 $gradetxt = $this->format_grade($userdata->grades[$itemid]);
351 // get the status of this grade, and put it through track to get the status
352 $g = new grade_export_update_buffer();
353 $grade_grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$user->id));
354 $status = $g->track($grade_grade);
356 if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) {
357 $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>';
358 } else {
359 $rowstr .= "<td>$gradetxt</td>";
360 $gradeupdated = true;
363 if ($this->export_feedback) {
364 $rowstr .= '<td>'.$this->format_feedback($userdata->feedbacks[$itemid]).'</td>';
368 // if we are requesting updated grades only, we are not interested in this user at all
369 if (!$gradeupdated && $this->updatedgradesonly) {
370 continue;
373 echo '<tr>';
374 foreach ($userprofilefields as $field) {
375 $fieldvalue = grade_helper::get_user_field_value($user, $field);
376 // @see profile_field_base::display_data().
377 echo '<td>' . format_text($fieldvalue, FORMAT_MOODLE, $formatoptions) . '</td>';
379 if (!$this->onlyactive) {
380 $issuspended = ($user->suspendedenrolment) ? get_string('yes') : '';
381 echo "<td>$issuspended</td>";
383 echo $rowstr;
384 echo "</tr>";
386 $i++; // increment the counter
388 echo '</table>';
389 $gui->close();
393 * Returns array of parameters used by dump.php and export.php.
394 * @return array
396 public function get_export_params() {
397 $itemids = array_keys($this->columns);
398 $itemidsparam = implode(',', $itemids);
399 if (empty($itemidsparam)) {
400 $itemidsparam = '-1';
403 // We have a single grade display type constant.
404 if (!is_array($this->displaytype)) {
405 $displaytypes = $this->displaytype;
406 } else {
407 // Implode the grade display types array as moodle_url function doesn't accept arrays.
408 $displaytypes = implode(',', $this->displaytype);
411 if (!empty($this->updatedgradesonly)) {
412 $updatedgradesonly = $this->updatedgradesonly;
413 } else {
414 $updatedgradesonly = 0;
416 $params = array('id' => $this->course->id,
417 'groupid' => $this->groupid,
418 'itemids' => $itemidsparam,
419 'export_letters' => $this->export_letters,
420 'export_feedback' => $this->export_feedback,
421 'updatedgradesonly' => $updatedgradesonly,
422 'decimalpoints' => $this->decimalpoints,
423 'export_onlyactive' => $this->onlyactive,
424 'usercustomfields' => $this->usercustomfields,
425 'displaytype' => $displaytypes,
426 'key' => $this->userkey);
428 return $params;
432 * Either prints a "Export" box, which will redirect the user to the download page,
433 * or prints the URL for the published data.
435 * @deprecated since 2.8 MDL-46548. Call get_export_url and set the
436 * action of the grade_export_form instead.
437 * @return void
439 public function print_continue() {
440 global $CFG, $OUTPUT;
442 debugging('function grade_export::print_continue is deprecated.', DEBUG_DEVELOPER);
443 $params = $this->get_export_params();
445 echo $OUTPUT->heading(get_string('export', 'grades'));
447 echo $OUTPUT->container_start('gradeexportlink');
449 if (!$this->userkey) {
450 // This button should trigger a download prompt.
451 $url = new moodle_url('/grade/export/'.$this->plugin.'/export.php', $params);
452 echo $OUTPUT->single_button($url, get_string('download', 'admin'));
454 } else {
455 $paramstr = '';
456 $sep = '?';
457 foreach($params as $name=>$value) {
458 $paramstr .= $sep.$name.'='.$value;
459 $sep = '&';
462 $link = $CFG->wwwroot.'/grade/export/'.$this->plugin.'/dump.php'.$paramstr.'&key='.$this->userkey;
464 echo get_string('download', 'admin').': ' . html_writer::link($link, $link);
466 echo $OUTPUT->container_end();
468 return;
472 * Generate the export url.
474 * Get submitted form data and create the url to be used on the grade publish feature.
476 * @return moodle_url the url of grade publishing export.
478 public function get_export_url() {
479 return new moodle_url('/grade/export/'.$this->plugin.'/dump.php', $this->get_export_params());
483 * Convert the grade display types parameter into the required array to grade exporting class.
485 * In order to export, the array key must be the display type name and the value must be the grade display type
486 * constant.
488 * Note: Added support for combined display types constants like the (GRADE_DISPLAY_TYPE_PERCENTAGE_REAL) as
489 * the $CFG->grade_export_displaytype config is still used on 2.7 in case of missing displaytype url param.
490 * In these cases, the file will be exported with a column for each display type.
492 * @param string $displaytypes can be a single or multiple display type constants comma separated.
493 * @return array $types
495 public static function convert_flat_displaytypes_to_array($displaytypes) {
496 $types = array();
498 // We have a single grade display type constant.
499 if (is_int($displaytypes)) {
500 $displaytype = clean_param($displaytypes, PARAM_INT);
502 // Let's set a default value, will be replaced below by the grade display type constant.
503 $display[$displaytype] = 1;
504 } else {
505 // Multiple grade display types constants.
506 $display = array_flip(explode(',', $displaytypes));
509 // Now, create the array in the required format by grade exporting class.
510 foreach ($display as $type => $value) {
511 $type = clean_param($type, PARAM_INT);
512 if ($type == GRADE_DISPLAY_TYPE_LETTER) {
513 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
514 } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE) {
515 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
516 } else if ($type == GRADE_DISPLAY_TYPE_REAL) {
517 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
518 } else if ($type == GRADE_DISPLAY_TYPE_REAL_PERCENTAGE) {
519 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
520 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
521 } else if ($type == GRADE_DISPLAY_TYPE_REAL_LETTER) {
522 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
523 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
524 } else if ($type == GRADE_DISPLAY_TYPE_LETTER_REAL) {
525 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
526 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
527 } else if ($type == GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE) {
528 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
529 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
530 } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER) {
531 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
532 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
533 } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE_REAL) {
534 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
535 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
538 return $types;
542 * Convert the item ids parameter into the required array to grade exporting class.
544 * In order to export, the array key must be the grade item id and all values must be one.
546 * @param string $itemids can be a single item id or many item ids comma separated.
547 * @return array $items correctly formatted array.
549 public static function convert_flat_itemids_to_array($itemids) {
550 $items = array();
552 // We just have one single item id.
553 if (is_int($itemids)) {
554 $itemid = clean_param($itemids, PARAM_INT);
555 $items[$itemid] = 1;
556 } else {
557 // Few grade items.
558 $items = array_flip(explode(',', $itemids));
559 foreach ($items as $itemid => $value) {
560 $itemid = clean_param($itemid, PARAM_INT);
561 $items[$itemid] = 1;
564 return $items;
568 * Create the html code of the grade publishing feature.
570 * @return string $output html code of the grade publishing.
572 public function get_grade_publishing_url() {
573 $url = $this->get_export_url();
574 $output = html_writer::start_div();
575 $output .= html_writer::tag('p', get_string('gradepublishinglink', 'grades', html_writer::link($url, $url)));
576 $output .= html_writer::end_div();
577 return $output;
581 * Create a stdClass object from URL parameters to be used by grade_export class.
583 * @param int $id course id.
584 * @param string $itemids grade items comma separated.
585 * @param bool $exportfeedback export feedback option.
586 * @param bool $onlyactive only enrolled active students.
587 * @param string $displaytype grade display type constants comma separated.
588 * @param int $decimalpoints grade decimal points.
589 * @param null $updatedgradesonly recently updated grades only (Used by XML exporting only).
590 * @param null $separator separator character: tab, comma, colon and semicolon (Used by TXT exporting only).
592 * @return stdClass $formdata
594 public static function export_bulk_export_data($id, $itemids, $exportfeedback, $onlyactive, $displaytype,
595 $decimalpoints, $updatedgradesonly = null, $separator = null) {
597 $formdata = new \stdClass();
598 $formdata->id = $id;
599 $formdata->itemids = self::convert_flat_itemids_to_array($itemids);
600 $formdata->exportfeedback = $exportfeedback;
601 $formdata->export_onlyactive = $onlyactive;
602 $formdata->display = self::convert_flat_displaytypes_to_array($displaytype);
603 $formdata->decimals = $decimalpoints;
605 if (!empty($updatedgradesonly)) {
606 $formdata->updatedgradesonly = $updatedgradesonly;
609 if (!empty($separator)) {
610 $formdata->separator = $separator;
613 return $formdata;
618 * This class is used to update the exported field in grade_grades.
619 * It does internal buffering to speedup the db operations.
621 class grade_export_update_buffer {
622 public $update_list;
623 public $export_time;
626 * Constructor - creates the buffer and initialises the time stamp
628 public function __construct() {
629 $this->update_list = array();
630 $this->export_time = time();
634 * Old syntax of class constructor. Deprecated in PHP7.
636 * @deprecated since Moodle 3.1
638 public function grade_export_update_buffer() {
639 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
640 self::__construct();
643 public function flush($buffersize) {
644 global $CFG, $DB;
646 if (count($this->update_list) > $buffersize) {
647 list($usql, $params) = $DB->get_in_or_equal($this->update_list);
648 $params = array_merge(array($this->export_time), $params);
650 $sql = "UPDATE {grade_grades} SET exported = ? WHERE id $usql";
651 $DB->execute($sql, $params);
652 $this->update_list = array();
657 * Track grade export status
658 * @param object $grade_grade
659 * @return string $status (unknow, new, regrade, nochange)
661 public function track($grade_grade) {
663 if (empty($grade_grade->exported) or empty($grade_grade->timemodified)) {
664 if (is_null($grade_grade->finalgrade)) {
665 // grade does not exist yet
666 $status = 'unknown';
667 } else {
668 $status = 'new';
669 $this->update_list[] = $grade_grade->id;
672 } else if ($grade_grade->exported < $grade_grade->timemodified) {
673 $status = 'regrade';
674 $this->update_list[] = $grade_grade->id;
676 } else if ($grade_grade->exported >= $grade_grade->timemodified) {
677 $status = 'nochange';
679 } else {
680 // something is wrong?
681 $status = 'unknown';
684 $this->flush(100);
686 return $status;
690 * Flush and close the buffer.
692 public function close() {
693 $this->flush(0);
698 * Verify that there is a valid set of grades to export.
699 * @param $courseid int The course being exported
701 function export_verify_grades($courseid) {
702 if (grade_needs_regrade_final_grades($courseid)) {
703 throw new moodle_exception('gradesneedregrading', 'grades');