Revert "Merge branch 'm28_MDL-46431' of https://github.com/totara/moodle"
[moodle.git] / grade / export / lib.php
CommitLineData
e060e33d 1<?php
c10ddfb3 2
e060e33d 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.
14//
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/>.
ce34ed3a 17
89bd8357 18require_once($CFG->dirroot.'/lib/gradelib.php');
19require_once($CFG->dirroot.'/grade/lib.php');
a5bc4e6e 20require_once($CFG->dirroot.'/grade/export/grade_export_form.php');
0eeada79 21
1b074625 22/**
23 * Base export class
24 */
5c75a0a3 25abstract class grade_export {
ba74762b 26
5c75a0a3 27 public $plugin; // plgin name - must be filled in subclasses!
caffc55a 28
5c75a0a3 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
caffc55a 33
5c75a0a3 34 public $previewrows; // number of rows in preview
35 public $export_letters; // export letters
36 public $export_feedback; // export feedback
37 public $userkey; // export using private user key
caffc55a 38
5c75a0a3 39 public $updatedgradesonly; // only export updated grades
40 public $displaytype; // display type (e.g. real, percentages, letter) for exports
41 public $decimalpoints; // number of decimal points for exports
78ab98bc 42 public $onlyactive; // only include users with an active enrolment
61c8e0d7
FM
43 public $usercustomfields; // include users custom fields
44
c10ddfb3 45 /**
46 * Constructor should set up all the private variables ready to be pulled
5c75a0a3 47 * @access public
caffc55a 48 * @param object $course
49 * @param int $groupid id of selected group, 0 means all
50 * @param string $itemlist comma separated list of item ids, empty means all
51 * @param boolean $export_feedback
61c8e0d7
FM
52 * @param boolean $updatedgradesonly
53 * @param string $displaytype
54 * @param int $decimalpoints
55 * @param boolean $onlyactive
56 * @param boolean $usercustomfields include user custom field in export
0eeada79 57 * @note Exporting as letters will lead to data loss if that exported set it re-imported.
c10ddfb3 58 */
61c8e0d7 59 public function grade_export($course, $groupid=0, $itemlist='', $export_feedback=false, $updatedgradesonly = false, $displaytype = GRADE_DISPLAY_TYPE_REAL, $decimalpoints = 2, $onlyactive = false, $usercustomfields = false) {
caffc55a 60 $this->course = $course;
61 $this->groupid = $groupid;
62 $this->grade_items = grade_item::fetch_all(array('courseid'=>$this->course->id));
63
112fdf47
AD
64 //Populating the columns here is required by /grade/export/(whatever)/export.php
65 //however index.php, when the form is submitted, will construct the collection here
66 //with an empty $itemlist then reconstruct it in process_form() using $formdata
caffc55a 67 $this->columns = array();
68 if (!empty($itemlist)) {
112fdf47
AD
69 if ($itemlist=='-1') {
70 //user deselected all items
71 } else {
72 $itemids = explode(',', $itemlist);
73 // remove items that are not requested
74 foreach ($itemids as $itemid) {
75 if (array_key_exists($itemid, $this->grade_items)) {
76 $this->columns[$itemid] =& $this->grade_items[$itemid];
77 }
caffc55a 78 }
79 }
80 } else {
81 foreach ($this->grade_items as $itemid=>$unused) {
82 $this->columns[$itemid] =& $this->grade_items[$itemid];
83 }
84 }
0e2d708e 85
caffc55a 86 $this->export_feedback = $export_feedback;
87 $this->userkey = '';
88 $this->previewrows = false;
59a7447a 89 $this->updatedgradesonly = $updatedgradesonly;
d24832f9 90
864d1f8c 91 $this->displaytype = $displaytype;
92 $this->decimalpoints = $decimalpoints;
78ab98bc 93 $this->onlyactive = $onlyactive;
61c8e0d7 94 $this->usercustomfields = $usercustomfields;
caffc55a 95 }
96
97 /**
98 * Init object based using data from form
99 * @param object $formdata
100 */
101 function process_form($formdata) {
102 global $USER;
103
104 $this->columns = array();
105 if (!empty($formdata->itemids)) {
112fdf47
AD
106 if ($formdata->itemids=='-1') {
107 //user deselected all items
108 } else {
109 foreach ($formdata->itemids as $itemid=>$selected) {
110 if ($selected and array_key_exists($itemid, $this->grade_items)) {
111 $this->columns[$itemid] =& $this->grade_items[$itemid];
112 }
caffc55a 113 }
114 }
115 } else {
116 foreach ($this->grade_items as $itemid=>$unused) {
117 $this->columns[$itemid] =& $this->grade_items[$itemid];
118 }
0e2d708e 119 }
120
0e2d708e 121 if (isset($formdata->key)) {
caffc55a 122 if ($formdata->key == 1 && isset($formdata->iprestriction) && isset($formdata->validuntil)) {
123 // Create a new key
124 $formdata->key = create_user_key('grade/export', $USER->id, $this->course->id, $formdata->iprestriction, $formdata->validuntil);
0e2d708e 125 }
126 $this->userkey = $formdata->key;
127 }
ba74762b 128
caffc55a 129 if (isset($formdata->export_letters)) {
130 $this->export_letters = $formdata->export_letters;
c10ddfb3 131 }
ba74762b 132
caffc55a 133 if (isset($formdata->export_feedback)) {
134 $this->export_feedback = $formdata->export_feedback;
135 }
c10ddfb3 136
78ab98bc
AD
137 if (isset($formdata->export_onlyactive)) {
138 $this->onlyactive = $formdata->export_onlyactive;
139 }
140
caffc55a 141 if (isset($formdata->previewrows)) {
142 $this->previewrows = $formdata->previewrows;
0bfbab47 143 }
144
caffc55a 145 }
146
147 /**
148 * Update exported field in grade_grades table
149 * @return boolean
150 */
5c75a0a3 151 public function track_exports() {
caffc55a 152 global $CFG;
153
154 /// Whether this plugin is entitled to update export time
155 if ($expplugins = explode(",", $CFG->gradeexport)) {
156 if (in_array($this->plugin, $expplugins)) {
157 return true;
11745964 158 } else {
caffc55a 159 return false;
160 }
161 } else {
162 return false;
11745964 163 }
caffc55a 164 }
b8ff92b6 165
caffc55a 166 /**
167 * Returns string representation of final grade
168 * @param $object $grade instance of grade_grade class
169 * @return string
170 */
5c75a0a3 171 public function format_grade($grade) {
864d1f8c 172 return grade_format_gradevalue($grade->finalgrade, $this->grade_items[$grade->itemid], false, $this->displaytype, $this->decimalpoints);
11745964 173 }
d9617050 174
caffc55a 175 /**
176 * Returns the name of column in export
177 * @param object $grade_item
178 * @param boolena $feedback feedback colum
179 * &return string
180 */
5c75a0a3 181 public function format_column_name($grade_item, $feedback=false) {
caffc55a 182 if ($grade_item->itemtype == 'mod') {
995f2d51 183 $name = get_string('modulename', $grade_item->itemmodule).get_string('labelsep', 'langconfig').$grade_item->get_name();
f67e327e 184 } else {
caffc55a 185 $name = $grade_item->get_name();
d9617050 186 }
ba74762b 187
caffc55a 188 if ($feedback) {
189 $name .= ' ('.get_string('feedback').')';
ba74762b 190 }
caffc55a 191
70be4430 192 return html_to_text($name, 0, false);
c10ddfb3 193 }
ba74762b 194
c10ddfb3 195 /**
caffc55a 196 * Returns formatted grade feedback
197 * @param object $feedback object with properties feedback and feedbackformat
198 * @return string
c10ddfb3 199 */
5c75a0a3 200 public function format_feedback($feedback) {
caffc55a 201 return strip_tags(format_text($feedback->feedback, $feedback->feedbackformat));
202 }
ba74762b 203
1b074625 204 /**
caffc55a 205 * Implemented by child class
1b074625 206 */
5c75a0a3 207 public abstract function print_grades();
11745964 208
caffc55a 209 /**
210 * Prints preview of exported grades on screen as a feedback mechanism
30f188f0 211 * @param bool $require_user_idnumber true means skip users without idnumber
caffc55a 212 */
30f188f0 213 public function display_preview($require_user_idnumber=false) {
c018f973 214 global $OUTPUT;
61c8e0d7
FM
215
216 $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
217 $formatoptions = new stdClass();
218 $formatoptions->para = false;
219
c018f973 220 echo $OUTPUT->heading(get_string('previewrows', 'grades'));
567883c8 221
f5f4967e 222 echo '<table>';
223 echo '<tr>';
61c8e0d7 224 foreach ($userprofilefields as $field) {
293f42b6
CF
225 echo '<th>' . $field->fullname . '</th>';
226 }
38c1dd19
RT
227 if (!$this->onlyactive) {
228 echo '<th>'.get_string("suspended")."</th>";
229 }
caffc55a 230 foreach ($this->columns as $grade_item) {
231 echo '<th>'.$this->format_column_name($grade_item).'</th>';
ba74762b 232
233 /// add a column_feedback column
caffc55a 234 if ($this->export_feedback) {
235 echo '<th>'.$this->format_column_name($grade_item, true).'</th>';
ba74762b 236 }
1b074625 237 }
f5f4967e 238 echo '</tr>';
1b074625 239 /// Print all the lines of data.
f6eb15ad 240 $i = 0;
caffc55a 241 $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
78ab98bc 242 $gui->require_active_enrolment($this->onlyactive);
61c8e0d7 243 $gui->allow_user_custom_fields($this->usercustomfields);
caffc55a 244 $gui->init();
245 while ($userdata = $gui->next_user()) {
f6eb15ad 246 // number of preview rows
bb9f1b4a 247 if ($this->previewrows and $this->previewrows <= $i) {
97599c0a 248 break;
f6eb15ad 249 }
caffc55a 250 $user = $userdata->user;
30f188f0 251 if ($require_user_idnumber and empty($user->idnumber)) {
7ce5df86 252 // some exports require user idnumber so we can match up students when importing the data
30f188f0 253 continue;
254 }
d24832f9 255
bb9f1b4a 256 $gradeupdated = false; // if no grade is update at all for this user, do not display this row
257 $rowstr = '';
caffc55a 258 foreach ($this->columns as $itemid=>$unused) {
259 $gradetxt = $this->format_grade($userdata->grades[$itemid]);
d24832f9 260
59a7447a 261 // get the status of this grade, and put it through track to get the status
262 $g = new grade_export_update_buffer();
263 $grade_grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$user->id));
264 $status = $g->track($grade_grade);
558cb86b 265
59a7447a 266 if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) {
bb9f1b4a 267 $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>';
59a7447a 268 } else {
bb9f1b4a 269 $rowstr .= "<td>$gradetxt</td>";
270 $gradeupdated = true;
59a7447a 271 }
d24832f9 272
caffc55a 273 if ($this->export_feedback) {
bb9f1b4a 274 $rowstr .= '<td>'.$this->format_feedback($userdata->feedbacks[$itemid]).'</td>';
ba74762b 275 }
1b074625 276 }
bb9f1b4a 277
d24832f9 278 // if we are requesting updated grades only, we are not interested in this user at all
bb9f1b4a 279 if (!$gradeupdated && $this->updatedgradesonly) {
d24832f9 280 continue;
bb9f1b4a 281 }
282
283 echo '<tr>';
61c8e0d7
FM
284 foreach ($userprofilefields as $field) {
285 $fieldvalue = grade_helper::get_user_field_value($user, $field);
286 // @see profile_field_base::display_data().
287 echo '<td>' . format_text($fieldvalue, FORMAT_MOODLE, $formatoptions) . '</td>';
293f42b6 288 }
38c1dd19
RT
289 if (!$this->onlyactive) {
290 $issuspended = ($user->suspendedenrolment) ? get_string('yes') : '';
291 echo "<td>$issuspended</td>";
292 }
bb9f1b4a 293 echo $rowstr;
f5f4967e 294 echo "</tr>";
d24832f9 295
bb9f1b4a 296 $i++; // increment the counter
f5f4967e 297 }
298 echo '</table>';
caffc55a 299 $gui->close();
1b074625 300 }
0e2d708e 301
302 /**
caffc55a 303 * Returns array of parameters used by dump.php and export.php.
304 * @return array
305 */
5c75a0a3 306 public function get_export_params() {
caffc55a 307 $itemids = array_keys($this->columns);
112fdf47
AD
308 $itemidsparam = implode(',', $itemids);
309 if (empty($itemidsparam)) {
310 $itemidsparam = '-1';
311 }
caffc55a 312
59a7447a 313 $params = array('id' =>$this->course->id,
314 'groupid' =>$this->groupid,
112fdf47 315 'itemids' =>$itemidsparam,
59a7447a 316 'export_letters' =>$this->export_letters,
317 'export_feedback' =>$this->export_feedback,
864d1f8c 318 'updatedgradesonly' =>$this->updatedgradesonly,
319 'displaytype' =>$this->displaytype,
78ab98bc 320 'decimalpoints' =>$this->decimalpoints,
61c8e0d7
FM
321 'export_onlyactive' =>$this->onlyactive,
322 'usercustomfields' =>$this->usercustomfields);
caffc55a 323
324 return $params;
325 }
326
327 /**
328 * Either prints a "Export" box, which will redirect the user to the download page,
329 * or prints the URL for the published data.
0e2d708e 330 * @return void
331 */
5c75a0a3 332 public function print_continue() {
c018f973 333 global $CFG, $OUTPUT;
0e2d708e 334
6c3ef410 335 $params = $this->get_export_params();
567883c8 336
c018f973 337 echo $OUTPUT->heading(get_string('export', 'grades'));
567883c8 338
03fcc729 339 echo $OUTPUT->container_start('gradeexportlink');
340
567883c8 341 if (!$this->userkey) { // this button should trigger a download prompt
a6855934 342 echo $OUTPUT->single_button(new moodle_url('/grade/export/'.$this->plugin.'/export.php', $params), get_string('download', 'admin'));
0e2d708e 343
344 } else {
caffc55a 345 $paramstr = '';
346 $sep = '?';
347 foreach($params as $name=>$value) {
348 $paramstr .= $sep.$name.'='.$value;
03fcc729 349 $sep = '&';
caffc55a 350 }
351
52f1a9ff 352 $link = $CFG->wwwroot.'/grade/export/'.$this->plugin.'/dump.php'.$paramstr.'&key='.$this->userkey;
0e2d708e 353
75015e5f 354 echo get_string('download', 'admin').': ' . html_writer::link($link, $link);
0e2d708e 355 }
03fcc729 356 echo $OUTPUT->container_end();
0e2d708e 357 }
c10ddfb3 358}
359
eb859919 360/**
361 * This class is used to update the exported field in grade_grades.
362 * It does internal buffering to speedup the db operations.
363 */
364class grade_export_update_buffer {
5c75a0a3 365 public $update_list;
366 public $export_time;
eb859919 367
368 /**
369 * Constructor - creates the buffer and initialises the time stamp
370 */
5c75a0a3 371 public function grade_export_update_buffer() {
eb859919 372 $this->update_list = array();
373 $this->export_time = time();
374 }
375
5c75a0a3 376 public function flush($buffersize) {
377 global $CFG, $DB;
eb859919 378
379 if (count($this->update_list) > $buffersize) {
5c75a0a3 380 list($usql, $params) = $DB->get_in_or_equal($this->update_list);
381 $params = array_merge(array($this->export_time), $params);
382
383 $sql = "UPDATE {grade_grades} SET exported = ? WHERE id $usql";
655b09ca 384 $DB->execute($sql, $params);
eb859919 385 $this->update_list = array();
386 }
387 }
388
389 /**
390 * Track grade export status
391 * @param object $grade_grade
392 * @return string $status (unknow, new, regrade, nochange)
393 */
5c75a0a3 394 public function track($grade_grade) {
59a7447a 395
eb859919 396 if (empty($grade_grade->exported) or empty($grade_grade->timemodified)) {
397 if (is_null($grade_grade->finalgrade)) {
398 // grade does not exist yet
399 $status = 'unknown';
400 } else {
401 $status = 'new';
402 $this->update_list[] = $grade_grade->id;
403 }
404
405 } else if ($grade_grade->exported < $grade_grade->timemodified) {
406 $status = 'regrade';
407 $this->update_list[] = $grade_grade->id;
408
409 } else if ($grade_grade->exported >= $grade_grade->timemodified) {
410 $status = 'nochange';
411
412 } else {
413 // something is wrong?
414 $status = 'unknown';
415 }
416
417 $this->flush(100);
418
419 return $status;
420 }
421
422 /**
423 * Flush and close the buffer.
424 */
5c75a0a3 425 public function close() {
eb859919 426 $this->flush(0);
427 }
428}
6c3ef410 429
459843d4
AD
430/**
431 * Verify that there is a valid set of grades to export.
432 * @param $courseid int The course being exported
433 */
434function export_verify_grades($courseid) {
435 $regraderesult = grade_regrade_final_grades($courseid);
436 if (is_array($regraderesult)) {
63d2081e 437 throw new moodle_exception('gradecantregrade', 'error', '', implode(', ', array_unique($regraderesult)));
459843d4
AD
438 }
439}