Merge branch 'MDL-40264-m25-essay-zero' of git://github.com/ktemkin/moodle into MOODL...
[moodle.git] / grade / export / lib.php
blobb7fa140c11c7c51399cb156088307940362a7769
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 $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
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
42 public $onlyactive; // only include users with an active enrolment
43 public $usercustomfields; // include users custom fields
45 /**
46 * Constructor should set up all the private variables ready to be pulled
47 * @access public
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
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
57 * @note Exporting as letters will lead to data loss if that exported set it re-imported.
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) {
60 $this->course = $course;
61 $this->groupid = $groupid;
62 $this->grade_items = grade_item::fetch_all(array('courseid'=>$this->course->id));
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
67 $this->columns = array();
68 if (!empty($itemlist)) {
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];
80 } else {
81 foreach ($this->grade_items as $itemid=>$unused) {
82 $this->columns[$itemid] =& $this->grade_items[$itemid];
86 $this->export_feedback = $export_feedback;
87 $this->userkey = '';
88 $this->previewrows = false;
89 $this->updatedgradesonly = $updatedgradesonly;
91 $this->displaytype = $displaytype;
92 $this->decimalpoints = $decimalpoints;
93 $this->onlyactive = $onlyactive;
94 $this->usercustomfields = $usercustomfields;
97 /**
98 * Init object based using data from form
99 * @param object $formdata
101 function process_form($formdata) {
102 global $USER;
104 $this->columns = array();
105 if (!empty($formdata->itemids)) {
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];
115 } else {
116 foreach ($this->grade_items as $itemid=>$unused) {
117 $this->columns[$itemid] =& $this->grade_items[$itemid];
121 if (isset($formdata->key)) {
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);
126 $this->userkey = $formdata->key;
129 if (isset($formdata->export_letters)) {
130 $this->export_letters = $formdata->export_letters;
133 if (isset($formdata->export_feedback)) {
134 $this->export_feedback = $formdata->export_feedback;
137 if (isset($formdata->export_onlyactive)) {
138 $this->onlyactive = $formdata->export_onlyactive;
141 if (isset($formdata->previewrows)) {
142 $this->previewrows = $formdata->previewrows;
148 * Update exported field in grade_grades table
149 * @return boolean
151 public function track_exports() {
152 global $CFG;
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;
158 } else {
159 return false;
161 } else {
162 return false;
167 * Returns string representation of final grade
168 * @param $object $grade instance of grade_grade class
169 * @return string
171 public function format_grade($grade) {
172 return grade_format_gradevalue($grade->finalgrade, $this->grade_items[$grade->itemid], false, $this->displaytype, $this->decimalpoints);
176 * Returns the name of column in export
177 * @param object $grade_item
178 * @param boolena $feedback feedback colum
179 * &return string
181 public function format_column_name($grade_item, $feedback=false) {
182 if ($grade_item->itemtype == 'mod') {
183 $name = get_string('modulename', $grade_item->itemmodule).get_string('labelsep', 'langconfig').$grade_item->get_name();
184 } else {
185 $name = $grade_item->get_name();
188 if ($feedback) {
189 $name .= ' ('.get_string('feedback').')';
192 return strip_tags($name);
196 * Returns formatted grade feedback
197 * @param object $feedback object with properties feedback and feedbackformat
198 * @return string
200 public function format_feedback($feedback) {
201 return strip_tags(format_text($feedback->feedback, $feedback->feedbackformat));
205 * Implemented by child class
207 public abstract function print_grades();
210 * Prints preview of exported grades on screen as a feedback mechanism
211 * @param bool $require_user_idnumber true means skip users without idnumber
213 public function display_preview($require_user_idnumber=false) {
214 global $OUTPUT;
216 $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
217 $formatoptions = new stdClass();
218 $formatoptions->para = false;
220 echo $OUTPUT->heading(get_string('previewrows', 'grades'));
222 echo '<table>';
223 echo '<tr>';
224 foreach ($userprofilefields as $field) {
225 echo '<th>' . $field->fullname . '</th>';
227 if (!$this->onlyactive) {
228 echo '<th>'.get_string("suspended")."</th>";
230 foreach ($this->columns as $grade_item) {
231 echo '<th>'.$this->format_column_name($grade_item).'</th>';
233 /// add a column_feedback column
234 if ($this->export_feedback) {
235 echo '<th>'.$this->format_column_name($grade_item, true).'</th>';
238 echo '</tr>';
239 /// Print all the lines of data.
240 $i = 0;
241 $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
242 $gui->require_active_enrolment($this->onlyactive);
243 $gui->allow_user_custom_fields($this->usercustomfields);
244 $gui->init();
245 while ($userdata = $gui->next_user()) {
246 // number of preview rows
247 if ($this->previewrows and $this->previewrows <= $i) {
248 break;
250 $user = $userdata->user;
251 if ($require_user_idnumber and empty($user->idnumber)) {
252 // some exports require user idnumber so we can match up students when importing the data
253 continue;
256 $gradeupdated = false; // if no grade is update at all for this user, do not display this row
257 $rowstr = '';
258 foreach ($this->columns as $itemid=>$unused) {
259 $gradetxt = $this->format_grade($userdata->grades[$itemid]);
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);
266 if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) {
267 $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>';
268 } else {
269 $rowstr .= "<td>$gradetxt</td>";
270 $gradeupdated = true;
273 if ($this->export_feedback) {
274 $rowstr .= '<td>'.$this->format_feedback($userdata->feedbacks[$itemid]).'</td>';
278 // if we are requesting updated grades only, we are not interested in this user at all
279 if (!$gradeupdated && $this->updatedgradesonly) {
280 continue;
283 echo '<tr>';
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>';
289 if (!$this->onlyactive) {
290 $issuspended = ($user->suspendedenrolment) ? get_string('yes') : '';
291 echo "<td>$issuspended</td>";
293 echo $rowstr;
294 echo "</tr>";
296 $i++; // increment the counter
298 echo '</table>';
299 $gui->close();
303 * Returns array of parameters used by dump.php and export.php.
304 * @return array
306 public function get_export_params() {
307 $itemids = array_keys($this->columns);
308 $itemidsparam = implode(',', $itemids);
309 if (empty($itemidsparam)) {
310 $itemidsparam = '-1';
313 $params = array('id' =>$this->course->id,
314 'groupid' =>$this->groupid,
315 'itemids' =>$itemidsparam,
316 'export_letters' =>$this->export_letters,
317 'export_feedback' =>$this->export_feedback,
318 'updatedgradesonly' =>$this->updatedgradesonly,
319 'displaytype' =>$this->displaytype,
320 'decimalpoints' =>$this->decimalpoints,
321 'export_onlyactive' =>$this->onlyactive,
322 'usercustomfields' =>$this->usercustomfields);
324 return $params;
328 * Either prints a "Export" box, which will redirect the user to the download page,
329 * or prints the URL for the published data.
330 * @return void
332 public function print_continue() {
333 global $CFG, $OUTPUT;
335 $params = $this->get_export_params();
337 echo $OUTPUT->heading(get_string('export', 'grades'));
339 echo $OUTPUT->container_start('gradeexportlink');
341 if (!$this->userkey) { // this button should trigger a download prompt
342 echo $OUTPUT->single_button(new moodle_url('/grade/export/'.$this->plugin.'/export.php', $params), get_string('download', 'admin'));
344 } else {
345 $paramstr = '';
346 $sep = '?';
347 foreach($params as $name=>$value) {
348 $paramstr .= $sep.$name.'='.$value;
349 $sep = '&';
352 $link = $CFG->wwwroot.'/grade/export/'.$this->plugin.'/dump.php'.$paramstr.'&key='.$this->userkey;
354 echo get_string('download', 'admin').': ' . html_writer::link($link, $link);
356 echo $OUTPUT->container_end();
361 * This class is used to update the exported field in grade_grades.
362 * It does internal buffering to speedup the db operations.
364 class grade_export_update_buffer {
365 public $update_list;
366 public $export_time;
369 * Constructor - creates the buffer and initialises the time stamp
371 public function grade_export_update_buffer() {
372 $this->update_list = array();
373 $this->export_time = time();
376 public function flush($buffersize) {
377 global $CFG, $DB;
379 if (count($this->update_list) > $buffersize) {
380 list($usql, $params) = $DB->get_in_or_equal($this->update_list);
381 $params = array_merge(array($this->export_time), $params);
383 $sql = "UPDATE {grade_grades} SET exported = ? WHERE id $usql";
384 $DB->execute($sql, $params);
385 $this->update_list = array();
390 * Track grade export status
391 * @param object $grade_grade
392 * @return string $status (unknow, new, regrade, nochange)
394 public function track($grade_grade) {
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;
405 } else if ($grade_grade->exported < $grade_grade->timemodified) {
406 $status = 'regrade';
407 $this->update_list[] = $grade_grade->id;
409 } else if ($grade_grade->exported >= $grade_grade->timemodified) {
410 $status = 'nochange';
412 } else {
413 // something is wrong?
414 $status = 'unknown';
417 $this->flush(100);
419 return $status;
423 * Flush and close the buffer.
425 public function close() {
426 $this->flush(0);
431 * Verify that there is a valid set of grades to export.
432 * @param $courseid int The course being exported
434 function export_verify_grades($courseid) {
435 $regraderesult = grade_regrade_final_grades($courseid);
436 if (is_array($regraderesult)) {
437 throw new moodle_exception('gradecantregrade', 'error', '', implode(', ', array_unique($regraderesult)));