Merge branch 'MDL-48679-master' of git://github.com/lameze/moodle
[moodle.git] / grade / export / lib.php
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.
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/>.
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
24  */
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).
42      *
43      *  This attribute is an integer for XML file export. Otherwise is an array for all other formats (ODS, XLS and TXT).
44      *
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.
48      */
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.
57      */
58     public $previewrows;
60     /**
61      * Constructor should set up all the private variables ready to be pulled.
62      *
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.
65      *
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.
71      */
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);
76         }
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);
83     }
85     /**
86      * Old deprecated constructor.
87      *
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.
90      *
91      * @deprecated since 2.8 MDL-46548. Instead call the shortened constructor which accepts the data
92      * directly from the grade_export_form.
93      */
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];
123                     }
124                 }
125             }
126         } else {
127             foreach ($this->grade_items as $itemid=>$unused) {
128                 $this->columns[$itemid] =& $this->grade_items[$itemid];
129             }
130         }
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;
141     }
143     /**
144      * Init object based using data from form
145      * @param object $formdata
146      */
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];
158                     }
159                 }
160             }
161         } else {
162             foreach ($this->grade_items as $itemid=>$unused) {
163                 $this->columns[$itemid] =& $this->grade_items[$itemid];
164             }
165         }
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);
171             }
172             $this->userkey = $formdata->key;
173         }
175         if (isset($formdata->decimals)) {
176             $this->decimalpoints = $formdata->decimals;
177         }
179         if (isset($formdata->export_letters)) {
180             $this->export_letters = $formdata->export_letters;
181         }
183         if (isset($formdata->export_feedback)) {
184             $this->export_feedback = $formdata->export_feedback;
185         }
187         if (isset($formdata->export_onlyactive)) {
188             $this->onlyactive = $formdata->export_onlyactive;
189         }
191         if (isset($formdata->previewrows)) {
192             $this->previewrows = $formdata->previewrows;
193         }
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);
202             }
203         }
205         if (isset($formdata->updatedgradesonly)) {
206             $this->updatedgradesonly = $formdata->updatedgradesonly;
207         }
208     }
210     /**
211      * Update exported field in grade_grades table
212      * @return boolean
213      */
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;
223           }
224         } else {
225             return false;
226         }
227     }
229     /**
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
234      */
235     public function format_grade($grade, $gradedisplayconst = null) {
236         $displaytype = $this->displaytype;
237         if (is_array($this->displaytype) && !is_null($gradedisplayconst)) {
238             $displaytype = $gradedisplayconst;
239         }
240         return grade_format_gradevalue($grade->finalgrade, $this->grade_items[$grade->itemid], false, $displaytype, $this->decimalpoints);
241     }
243     /**
244      * Returns the name of column in export
245      * @param object $grade_item
246      * @param boolean $feedback feedback colum
247      * @param string $gradedisplayname grade display name.
248      * @return string
249      */
250     public function format_column_name($grade_item, $feedback=false, $gradedisplayname = null) {
251         $column = new stdClass();
253         if ($grade_item->itemtype == 'mod') {
254             $column->name = get_string('modulename', $grade_item->itemmodule).get_string('labelsep', 'langconfig').$grade_item->get_name();
255         } else {
256             $column->name = $grade_item->get_name();
257         }
259         // We can't have feedback and display type at the same time.
260         $column->extra = ($feedback) ? get_string('feedback') : get_string($gradedisplayname, 'grades');
262         return html_to_text(get_string('gradeexportcolumntype', 'grades', $column), 0, false);
263     }
265     /**
266      * Returns formatted grade feedback
267      * @param object $feedback object with properties feedback and feedbackformat
268      * @return string
269      */
270     public function format_feedback($feedback) {
271         return strip_tags(format_text($feedback->feedback, $feedback->feedbackformat));
272     }
274     /**
275      * Implemented by child class
276      */
277     public abstract function print_grades();
279     /**
280      * Prints preview of exported grades on screen as a feedback mechanism
281      * @param bool $require_user_idnumber true means skip users without idnumber
282      * @deprecated since 2.8 MDL-46548. Previews are not useful on export.
283      */
284     public function display_preview($require_user_idnumber=false) {
285         global $OUTPUT;
287         debugging('function grade_export::display_preview is deprecated.', DEBUG_DEVELOPER);
289         $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
290         $formatoptions = new stdClass();
291         $formatoptions->para = false;
293         echo $OUTPUT->heading(get_string('previewrows', 'grades'));
295         echo '<table>';
296         echo '<tr>';
297         foreach ($userprofilefields as $field) {
298             echo '<th>' . $field->fullname . '</th>';
299         }
300         if (!$this->onlyactive) {
301             echo '<th>'.get_string("suspended")."</th>";
302         }
303         foreach ($this->columns as $grade_item) {
304             echo '<th>'.$this->format_column_name($grade_item).'</th>';
306             /// add a column_feedback column
307             if ($this->export_feedback) {
308                 echo '<th>'.$this->format_column_name($grade_item, true).'</th>';
309             }
310         }
311         echo '</tr>';
312         /// Print all the lines of data.
313         $i = 0;
314         $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
315         $gui->require_active_enrolment($this->onlyactive);
316         $gui->allow_user_custom_fields($this->usercustomfields);
317         $gui->init();
318         while ($userdata = $gui->next_user()) {
319             // number of preview rows
320             if ($this->previewrows and $this->previewrows <= $i) {
321                 break;
322             }
323             $user = $userdata->user;
324             if ($require_user_idnumber and empty($user->idnumber)) {
325                 // some exports require user idnumber so we can match up students when importing the data
326                 continue;
327             }
329             $gradeupdated = false; // if no grade is update at all for this user, do not display this row
330             $rowstr = '';
331             foreach ($this->columns as $itemid=>$unused) {
332                 $gradetxt = $this->format_grade($userdata->grades[$itemid]);
334                 // get the status of this grade, and put it through track to get the status
335                 $g = new grade_export_update_buffer();
336                 $grade_grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$user->id));
337                 $status = $g->track($grade_grade);
339                 if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) {
340                     $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>';
341                 } else {
342                     $rowstr .= "<td>$gradetxt</td>";
343                     $gradeupdated = true;
344                 }
346                 if ($this->export_feedback) {
347                     $rowstr .=  '<td>'.$this->format_feedback($userdata->feedbacks[$itemid]).'</td>';
348                 }
349             }
351             // if we are requesting updated grades only, we are not interested in this user at all
352             if (!$gradeupdated && $this->updatedgradesonly) {
353                 continue;
354             }
356             echo '<tr>';
357             foreach ($userprofilefields as $field) {
358                 $fieldvalue = grade_helper::get_user_field_value($user, $field);
359                 // @see profile_field_base::display_data().
360                 echo '<td>' . format_text($fieldvalue, FORMAT_MOODLE, $formatoptions) . '</td>';
361             }
362             if (!$this->onlyactive) {
363                 $issuspended = ($user->suspendedenrolment) ? get_string('yes') : '';
364                 echo "<td>$issuspended</td>";
365             }
366             echo $rowstr;
367             echo "</tr>";
369             $i++; // increment the counter
370         }
371         echo '</table>';
372         $gui->close();
373     }
375     /**
376      * Returns array of parameters used by dump.php and export.php.
377      * @return array
378      */
379     public function get_export_params() {
380         $itemids = array_keys($this->columns);
381         $itemidsparam = implode(',', $itemids);
382         if (empty($itemidsparam)) {
383             $itemidsparam = '-1';
384         }
386         // We have a single grade display type constant.
387         if (!is_array($this->displaytype)) {
388             $displaytypes = $this->displaytype;
389         } else {
390             // Implode the grade display types array as moodle_url function doesn't accept arrays.
391             $displaytypes = implode(',', $this->displaytype);
392         }
393         
394         if (!empty($this->updatedgradesonly)) {
395             $updatedgradesonly = $this->updatedgradesonly;
396         } else {
397             $updatedgradesonly = 0;
398         }
399         $params = array('id'                => $this->course->id,
400                         'groupid'           => $this->groupid,
401                         'itemids'           => $itemidsparam,
402                         'export_letters'    => $this->export_letters,
403                         'export_feedback'   => $this->export_feedback,
404                         'updatedgradesonly' => $updatedgradesonly,
405                         'decimalpoints'     => $this->decimalpoints,
406                         'export_onlyactive' => $this->onlyactive,
407                         'usercustomfields'  => $this->usercustomfields,
408                         'displaytype'       => $displaytypes,
409                         'key'               => $this->userkey);
411         return $params;
412     }
414     /**
415      * Either prints a "Export" box, which will redirect the user to the download page,
416      * or prints the URL for the published data.
417      *
418      * @deprecated since 2.8 MDL-46548. Call get_export_url and set the
419      *             action of the grade_export_form instead.
420      * @return void
421      */
422     public function print_continue() {
423         global $CFG, $OUTPUT;
425         debugging('function grade_export::print_continue is deprecated.', DEBUG_DEVELOPER);
426         $params = $this->get_export_params();
428         echo $OUTPUT->heading(get_string('export', 'grades'));
430         echo $OUTPUT->container_start('gradeexportlink');
432         if (!$this->userkey) {
433             // This button should trigger a download prompt.
434             $url = new moodle_url('/grade/export/'.$this->plugin.'/export.php', $params);
435             echo $OUTPUT->single_button($url, get_string('download', 'admin'));
437         } else {
438             $paramstr = '';
439             $sep = '?';
440             foreach($params as $name=>$value) {
441                 $paramstr .= $sep.$name.'='.$value;
442                 $sep = '&';
443             }
445             $link = $CFG->wwwroot.'/grade/export/'.$this->plugin.'/dump.php'.$paramstr.'&key='.$this->userkey;
447             echo get_string('download', 'admin').': ' . html_writer::link($link, $link);
448         }
449         echo $OUTPUT->container_end();
451         return;
452     }
454     /**
455      * Generate the export url.
456      *
457      * Get submitted form data and create the url to be used on the grade publish feature.
458      *
459      * @return moodle_url the url of grade publishing export.
460      */
461     public function get_export_url() {
462         return new moodle_url('/grade/export/'.$this->plugin.'/dump.php', $this->get_export_params());
463     }
465     /**
466      * Convert the grade display types parameter into the required array to grade exporting class.
467      *
468      * In order to export, the array key must be the display type name and the value must be the grade display type
469      * constant.
470      *
471      * Note: Added support for combined display types constants like the (GRADE_DISPLAY_TYPE_PERCENTAGE_REAL) as
472      *       the $CFG->grade_export_displaytype config is still used on 2.7 in case of missing displaytype url param.
473      *       In these cases, the file will be exported with a column for each display type.
474      *
475      * @param string $displaytypes can be a single or multiple display type constants comma separated.
476      * @return array $types
477      */
478     public static function convert_flat_displaytypes_to_array($displaytypes) {
479         $types = array();
481         // We have a single grade display type constant.
482         if (is_int($displaytypes)) {
483             $displaytype = clean_param($displaytypes, PARAM_INT);
485             // Let's set a default value, will be replaced below by the grade display type constant.
486             $display[$displaytype] = 1;
487         } else {
488             // Multiple grade display types constants.
489             $display = array_flip(explode(',', $displaytypes));
490         }
492         // Now, create the array in the required format by grade exporting class.
493         foreach ($display as $type => $value) {
494             $type = clean_param($type, PARAM_INT);
495             if ($type == GRADE_DISPLAY_TYPE_LETTER) {
496                 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
497             } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE) {
498                 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
499             } else if ($type == GRADE_DISPLAY_TYPE_REAL) {
500                 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
501             } else if ($type == GRADE_DISPLAY_TYPE_REAL_PERCENTAGE) {
502                 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
503                 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
504             } else if ($type == GRADE_DISPLAY_TYPE_REAL_LETTER) {
505                 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
506                 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
507             } else if ($type == GRADE_DISPLAY_TYPE_LETTER_REAL) {
508                 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
509                 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
510             } else if ($type == GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE) {
511                 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
512                 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
513             } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER) {
514                 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
515                 $types['letter'] = GRADE_DISPLAY_TYPE_LETTER;
516             } else if ($type == GRADE_DISPLAY_TYPE_PERCENTAGE_REAL) {
517                 $types['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
518                 $types['real'] = GRADE_DISPLAY_TYPE_REAL;
519             }
520         }
521         return $types;
522     }
524     /**
525      * Convert the item ids parameter into the required array to grade exporting class.
526      *
527      * In order to export, the array key must be the grade item id and all values must be one.
528      *
529      * @param string $itemids can be a single item id or many item ids comma separated.
530      * @return array $items correctly formatted array.
531      */
532     public static function convert_flat_itemids_to_array($itemids) {
533         $items = array();
535         // We just have one single item id.
536         if (is_int($itemids)) {
537             $itemid = clean_param($itemids, PARAM_INT);
538             $items[$itemid] = 1;
539         } else {
540             // Few grade items.
541             $items = array_flip(explode(',', $itemids));
542             foreach ($items as $itemid => $value) {
543                 $itemid = clean_param($itemid, PARAM_INT);
544                 $items[$itemid] = 1;
545             }
546         }
547         return $items;
548     }
550     /**
551      * Create the html code of the grade publishing feature.
552      *
553      * @return string $output html code of the grade publishing.
554      */
555     public function get_grade_publishing_url() {
556         $url = $this->get_export_url();
557         $output =  html_writer::start_div();
558         $output .= html_writer::tag('p', get_string('gradepublishinglink', 'grades', html_writer::link($url, $url)));
559         $output .=  html_writer::end_div();
560         return $output;
561     }
563     /**
564      * Create a stdClass object from URL parameters to be used by grade_export class.
565      *
566      * @param int $id course id.
567      * @param string $itemids grade items comma separated.
568      * @param bool $exportfeedback export feedback option.
569      * @param bool $onlyactive only enrolled active students.
570      * @param string $displaytype grade display type constants comma separated.
571      * @param int $decimalpoints grade decimal points.
572      * @param null $updatedgradesonly recently updated grades only (Used by XML exporting only).
573      * @param null $separator separator character: tab, comma, colon and semicolon (Used by TXT exporting only).
574      *
575      * @return stdClass $formdata
576      */
577     public static function export_bulk_export_data($id, $itemids, $exportfeedback, $onlyactive, $displaytype,
578                                                    $decimalpoints, $updatedgradesonly = null, $separator = null) {
580         $formdata = new \stdClass();
581         $formdata->id = $id;
582         $formdata->itemids = self::convert_flat_itemids_to_array($itemids);
583         $formdata->exportfeedback = $exportfeedback;
584         $formdata->export_onlyactive = $onlyactive;
585         $formdata->display = self::convert_flat_displaytypes_to_array($displaytype);
586         $formdata->decimals = $decimalpoints;
588         if (!empty($updatedgradesonly)) {
589             $formdata->updatedgradesonly = $updatedgradesonly;
590         }
592         if (!empty($separator)) {
593             $formdata->separator = $separator;
594         }
596         return $formdata;
597     }
600 /**
601  * This class is used to update the exported field in grade_grades.
602  * It does internal buffering to speedup the db operations.
603  */
604 class grade_export_update_buffer {
605     public $update_list;
606     public $export_time;
608     /**
609      * Constructor - creates the buffer and initialises the time stamp
610      */
611     public function grade_export_update_buffer() {
612         $this->update_list = array();
613         $this->export_time = time();
614     }
616     public function flush($buffersize) {
617         global $CFG, $DB;
619         if (count($this->update_list) > $buffersize) {
620             list($usql, $params) = $DB->get_in_or_equal($this->update_list);
621             $params = array_merge(array($this->export_time), $params);
623             $sql = "UPDATE {grade_grades} SET exported = ? WHERE id $usql";
624             $DB->execute($sql, $params);
625             $this->update_list = array();
626         }
627     }
629     /**
630      * Track grade export status
631      * @param object $grade_grade
632      * @return string $status (unknow, new, regrade, nochange)
633      */
634     public function track($grade_grade) {
636         if (empty($grade_grade->exported) or empty($grade_grade->timemodified)) {
637             if (is_null($grade_grade->finalgrade)) {
638                 // grade does not exist yet
639                 $status = 'unknown';
640             } else {
641                 $status = 'new';
642                 $this->update_list[] = $grade_grade->id;
643             }
645         } else if ($grade_grade->exported < $grade_grade->timemodified) {
646             $status = 'regrade';
647             $this->update_list[] = $grade_grade->id;
649         } else if ($grade_grade->exported >= $grade_grade->timemodified) {
650             $status = 'nochange';
652         } else {
653             // something is wrong?
654             $status = 'unknown';
655         }
657         $this->flush(100);
659         return $status;
660     }
662     /**
663      * Flush and close the buffer.
664      */
665     public function close() {
666         $this->flush(0);
667     }
670 /**
671  * Verify that there is a valid set of grades to export.
672  * @param $courseid int The course being exported
673  */
674 function export_verify_grades($courseid) {
675     $regraderesult = grade_regrade_final_grades($courseid);
676     if (is_array($regraderesult)) {
677         throw new moodle_exception('gradecantregrade', 'error', '', implode(', ', array_unique($regraderesult)));
678     }