-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.php
1727 lines (1508 loc) · 67.5 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library of report functions.
*
* @package report_ncccscensus
* @author Sean O'Hagan <[email protected]>
* @copyright 2014 Remote Learner - http://www.remote-learner.net/
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir.'/formslib.php');
/**
* REPORT_NCCCSCENSUS_ACTION_VIEW - represents viewing the HTML version of the report
*/
define('REPORT_NCCCSCENSUS_ACTION_VIEW', 1);
/**
* REPORT_NCCCSCENSUS_ACTION_PDF - represents downloading the report in PDF format
*/
define('REPORT_NCCCSCENSUS_ACTION_PDF', 2);
/**
* REPORT_NCCCSCENSUS_ACTION_CSV - represents downloading the report in CSV format
*/
define('REPORT_NCCCSCENSUS_ACTION_CSV', 3);
/**
* EXCLUDE_GROUP_MEMBERS - flag to determine whether group member should be excluded from report
*/
define('REPORT_NCCCSCENSUS_EXCLUDE_GROUP_MEMBERS', 0);
/**
* Class to define the report search form
*
* @copyright 2014 Remote Learner - http://www.remote-learner.net/
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @see moodleform
*/
class report_ncccscensus_setup_query_form extends moodleform {
/**
* __construct
*
* @param mixed $actionurl the action URL of the form
* @param mixed $cid the course ID
*/
public function __construct($actionurl, $cid) {
$this->cid = $cid;
parent::__construct($actionurl);
}
/**
* Method that defines all of the elements of the form.
*
*/
public function definition() {
global $DB, $USER;
$course = $DB->get_record('course', array('id' => $this->cid));
$mform =& $this->_form;
$mform->addElement('header', 'header', get_string('querytitle', 'report_ncccscensus'));
$mform->addElement('hidden', 'id', $this->cid);
$mform->setType('id', PARAM_INT);
// Add the course information.
$mform->addElement('hidden', 'course', $this->cid);
$mform->setType('course', PARAM_INT);
$mform->addElement('static', 'course_label', get_string('course', 'report_ncccscensus'), $course->fullname);
// Determine which groups to display, if any, based on the value of $userid.
$context = context_course::instance($course->id);
if (has_capability('moodle/site:accessallgroups', $context)) {
$userid = 0;
} else if (has_capability('moodle/course:managegroups', $context)) {
$userid = $USER->id;
} else {
$userid = false;
}
if ($userid !== false && ($grouprecs = groups_get_all_groups($course->id, $userid, 0, 'g.id, g.name'))) {
$groups = array();
// Build the groups array.
foreach ($grouprecs as $grouprec) {
$groups[$grouprec->id] = $grouprec->name;
}
if (has_capability('moodle/site:accessallgroups', $context)) { // Could have checked for $user==0 but this is safer.
// Add the "All groups" option.
$groups = array('0' => get_string('allgroups', 'report_ncccscensus')) + $groups;
}
} else {
// Create an N/A option for the groups dropdown.
$groups = array(get_string('na', 'report_ncccscensus'));
// Add a hidden element to flag that the dropdown should be disabled.
$mform->addElement('hidden', 'disablegroups', true);
$mform->setType('disablegroups', PARAM_BOOL);
}
// Add the groups dropdown.
$mform->addElement('select', 'group', get_string('groupselector', 'report_ncccscensus'), $groups);
// Disable the groups dropdown if the hidden element's value is 1.
$mform->disabledIf('group', 'disablegroups', 'eq', 1);
$mform->addElement('date_selector', 'startdate', get_string('from'));
$mform->addElement('date_selector', 'enddate', get_string('to'));
$mform->addElement('html', '<br>');
$bview =& $mform->createElement('radio', 'action', '', get_string('viewreport', 'report_ncccscensus'), REPORT_NCCCSCENSUS_ACTION_VIEW);
$bdlpdf =& $mform->createElement('radio', 'action', '', get_string('downloadreportpdf', 'report_ncccscensus'), REPORT_NCCCSCENSUS_ACTION_PDF);
$bdlcsv =& $mform->createElement('radio', 'action', '', get_string('downloadreportcsv', 'report_ncccscensus'), REPORT_NCCCSCENSUS_ACTION_CSV);
$actions = array($bview, $bdlpdf, $bdlcsv);
$mform->addGroup($actions, 'action', get_string('action', 'report_ncccscensus'), array(' '), false);
$mform->setDefault('action', REPORT_NCCCSCENSUS_ACTION_VIEW);
$mform->addElement('html', '<br>');
$bsubmit =& $mform->createElement('submit', 'submitbutton', get_string('getreport', 'report_ncccscensus'));
$breset =& $mform->createElement('reset', 'resetbutton', get_string('revert'));
$bcancel =& $mform->createElement('cancel');
$submits = array($bsubmit, $breset, $bcancel);
$mform->addGroup($submits, 'submits', ' ', array(' '), false);
}
}
/**
* Class to define the bulk report search form
*
* @copyright 2014 Remote Learner - http://www.remote-learner.net/
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @see moodleform
*/
class report_ncccscensus_setup_bulk_form extends moodleform {
/** @var string Comma seperate list of sections to show categories,courses,teachers */
private $actions = null;
/**
* Constructor to setup form.
*
* @param mixed $pageurl Page url for form.
* @param mixed $actions Actions to show on form.
*/
public function __construct($pageurl, $actions) {
$this->actions = $actions;
parent::__construct($pageurl);
}
/**
* Method that defines all of the elements of the form.
*/
public function definition() {
$mform =& $this->_form;
$mform->addElement('header', 'header', get_string('querytitle', 'report_ncccscensus'));
$mform->addElement('hidden', 'categories', '');
$mform->setType('categories', PARAM_TEXT);
$mform->addElement('hidden', 'courses', '');
$mform->setType('courses', PARAM_TEXT);
$mform->addElement('hidden', 'teachers', '');
$mform->setType('teachers', PARAM_TEXT);
$actions = preg_split('/,/', $this->actions);
if (empty($actions[0])) {
$actions = array('categories', 'courses', 'teachers');
}
foreach ($actions as $action) {
switch ($action) {
case "categories":
$mform->addElement('text', 'categoryids', 'Categories', array('size' => '40'));
$mform->setType('categoryids', PARAM_RAW);
$mform->addElement('html', '<div id="categories_list" class="box generalbox" style="display: none"></div>');
break;
case "courses":
$mform->addElement('text', 'coursesids', 'Courses', array('size' => '40'));
$mform->setType('coursesids', PARAM_RAW);
$mform->addElement('html', '<div id="courses_list" class="box generalbox" style="display: none"></div>');
break;
case "teachers":
$mform->addElement('text', 'teacherids', 'Teachers', array('size' => '40'));
$mform->setType('teacherids', PARAM_RAW);
$mform->addElement('html', '<div id="teachers_list" class="box generalbox" style="display: none"></div>');
break;
}
}
$mform->addElement('date_selector', 'startdate', get_string('from'));
$mform->addElement('date_selector', 'enddate', get_string('to'));
$mform->addElement('html', '<br>');
$bsubmit =& $mform->createElement('submit', 'submitbutton', get_string('generatereport', 'report_ncccscensus'));
$breset =& $mform->createElement('reset', 'resetbutton', get_string('revert'));
$bcancel =& $mform->createElement('cancel');
$submits = array($bsubmit, $breset, $bcancel);
$mform->addGroup($submits, 'submits', ' ', array(' '), false);
}
}
/**
* Cron job to generate the bulk report pdf's and zip.
*
* @return void
* @uses $CFG, $DB
*/
function report_ncccscensus_cron() {
global $DB;
$batches = $DB->get_records('report_ncccscensus_batch', array('status' => 0));
foreach ($batches as $batch) {
report_ncccscensus_process_batch($batch->id);
}
}
/**
* Generates the bulk report pdf's and zip.
*
* @param int $batch The id of the batch.
* @return void
* @uses $CFG, $DB
*/
function report_ncccscensus_process_batch($batch) {
global $CFG, $DB;
require_once($CFG->libdir.'/moodlelib.php');
// Retrieve first 50 reports to generate at a time and prevent cron job from lasting longer than 5 minutes.
$reports = $DB->get_records('report_ncccscensus_reports', array('batchid' => $batch, 'status' => 0), '', '*', 0, 50);
$files = array();
$tempdirused = false;
$dir = make_temp_directory("ncccscensus$batch", false);
foreach ($reports as $report) {
// Create form data.
$formdata = new stdClass;
$formdata->id = $report->course;
$formdata->group = 0;
$formdata->startdate = $report->reportstartdate;
$formdata->enddate = $report->reportenddate;
// Save report pdf.
$date = usergetdate(time(), get_user_timezone());
$filename = date('MdY_Hi', mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']));
$filename = $filename.'-'.$report->course.'.pdf';
// Get temporary file location.
$fullfilename = $dir.'/'.$filename;
if (true === report_ncccscensus_generate_report($formdata, REPORT_NCCCSCENSUS_ACTION_PDF, $fullfilename)) {
$files[$filename] = $fullfilename;
$report->filename = $filename;
$report->fullfilename = $fullfilename;
// Indicate that there was a pdf generated, if not remove as remove in zip will not be called.
$tempdirused = true;
$report->status = 1;
} else {
$report->status = 2;
}
// Mark report generation as complete.
$DB->update_record('report_ncccscensus_reports', $report);
}
if (!$tempdirused) {
rmdir($dir);
}
report_ncccscensus_generate_bulk_zip($batch);
}
/**
* Generates list of zip files in array.
*
* @param int $batch id of batch
* @return array|bool False on no files to add to zip, array on success
* @uses $CFG, $DB
*/
function report_ncccscensus_get_zip_files($batch) {
global $DB;
$files = array();
$filerecords = $DB->get_records('report_ncccscensus_reports', array('batchid' => $batch, 'status' => 1));
foreach ($filerecords as $file) {
if (!empty($file->filename)) {
$files[$file->filename] = $file->fullfilename;
}
}
if (count($files) > 0) {
return $files;
}
return false;
}
/**
* Generates list of zip files in array.
*
* @param int $batch id of batch
* @return array|bool False on no files to add to zip, array on success
* @uses $CFG, $DB
*/
function report_ncccscensus_generate_bulk_zip($batch) {
global $DB, $USER;
// Check if last report.
$left = $DB->count_records('report_ncccscensus_reports', array('batchid' => $batch, 'status' => 0));
if ($left !== 0) {
return false;
}
$files = report_ncccscensus_get_zip_files($batch);
if (!is_array($files)) {
return false;
}
$date = usergetdate(time(), get_user_timezone());
$filename = date('MdY_Hi', mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']));
$filename = $filename.'-'.$batch.'.zip';
$fs = get_file_storage();
// Check to see if file exists.
$contextid = context_system::instance()->id;
$file = $fs->get_file($contextid, 'report_ncccscensus', 'archive', $batch, '/report_ncccscensus/', $filename);
if (!$file) {
// Prepare file record object.
$fileinfo = array(
'contextid' => context_system::instance()->id,
'component' => 'report_ncccscensus',
'filearea' => 'archive',
'itemid' => $batch,
'filepath' => '/report_ncccscensus/',
'filename' => $filename);
$file = $fs->create_file_from_string($fileinfo, '');
}
$parentpath = $file->get_parent_directory()->get_filepath();
$filepath = explode('/', trim($file->get_filepath(), '/'));
$filepath = array_pop($filepath);
// Generate zip.
$zipper = get_file_packer('application/zip');
$record = $DB->get_record('report_ncccscensus_batch', array('id' => $batch));
$contextid = context_system::instance()->id;
$path = 'report_ncccscensus';
$newfile = $zipper->archive_to_storage($files, $contextid, $path, 'archive', $batch, $parentpath, $filename, $USER->id);
if ($newfile) {
// Mark batch as complete.
$record->zipfile = $filename;
}
$record->status = 1;
$DB->update_record('report_ncccscensus_batch', $record);
$info = array();
// Delete pdf files.
foreach ($files as $filename => $fullfilename) {
@unlink($fullfilename);
$info = pathinfo($fullfilename);
}
if (!empty($info['dirname'])) {
@rmdir($info['dirname']);
}
}
/**
* Performs the bulk report function.
*
* @param array $formdata the form data
* @return bool False on failure
* @uses $DB
*/
function report_ncccscensus_generate_bulk_report($formdata) {
global $DB;
$courses = report_ncccscensus_get_courses($formdata);
if (!(is_array($courses) && count($courses) > 0)) {
return false;
}
// Generate random batch id.
$report = new stdClass;
$report->starttime = usertime(time(), get_user_timezone());
$batchid = $DB->insert_record('report_ncccscensus_batch', $report);
foreach ($courses as $course) {
$report = new stdClass;
$report->batchid = $batchid;
$report->course = $course;
$report->starttime = usertime(time(), get_user_timezone());
$report->reportstartdate = $formdata->startdate;
$report->reportenddate = $formdata->enddate;
$DB->insert_record('report_ncccscensus_reports', $report);
}
return $batchid;
}
/**
* Delete all reports.
*
* @return void
* @uses $DB
*/
function report_ncccscensus_bulk_report_delete_all() {
global $DB;
$batches = $DB->get_records('report_ncccscensus_batch', null);
foreach ($batches as $batch) {
report_ncccscensus_bulk_report_cancel($batch->id);
}
}
/**
* Cancel bulk report generation or delete if complete.
*
* @param string $batchid The batchid for the bulk report
* @return void
* @uses $DB
*/
function report_ncccscensus_bulk_report_cancel($batchid) {
global $DB;
$files = report_ncccscensus_get_zip_files($batchid);
$batch = $DB->get_record('report_ncccscensus_batch', array('id' => $batchid));
$reports = $DB->get_records('report_ncccscensus_reports', array('batchid' => $batchid));
$DB->delete_records('report_ncccscensus_batch', array('id' => $batchid));
$DB->delete_records('report_ncccscensus_reports', array('batchid' => $batchid));
if (!empty($batch->zipfile)) {
$fs = get_file_storage();
// Check to see if file exists.
$path = 'report_ncccscensus';
$contextid = context_system::instance()->id;
$file = $fs->get_file($contextid, $path, 'archive', $batch->id, '/report_ncccscensus/', $batch->zipfile);
// Delete it if it exists.
if ($file) {
$file->delete();
}
} else {
if ($files == false) {
return;
}
$info = array();
// Delete temporary pdf files.
foreach ($files as $filename => $fullfilename) {
if (file_exists($fullfilename)) {
@unlink($fullfilename);
}
$info = pathinfo($fullfilename);
}
if (!empty($info['dirname']) && file_exists($info['dirname'])) {
@rmdir($info['dirname']);
}
}
}
/**
* Retrieves a single bulk report status.
*
* @param string $batchid The batchid for the bulk report
* @return bool|array False on failure, array with bulk report status
* @uses $DB
*/
function report_ncccscensus_bulk_report_status($batchid) {
global $DB;
$data = array();
$data['totalcourses'] = $DB->count_records('report_ncccscensus_reports', array('batchid' => $batchid));
if (empty($data['totalcourses']) || $data['totalcourses'] === 0) {
return false;
}
$data['totalcomplete'] = $DB->count_records('report_ncccscensus_reports', array('batchid' => $batchid, 'status' => 1));
$data['totalwaiting'] = $data['totalcourses'] - $data['totalcomplete'];
$record = $DB->get_record('report_ncccscensus_reports', array('batchid' => $batchid), 'starttime');
$data['starttime'] = userdate($record->starttime);
return $data;
}
/**
* Retrieves a all bulk report status.
*
* @return array with bulk report status
* @uses $DB
*/
function report_ncccscensus_bulk_report_status_all() {
global $DB;
$query = 'SELECT nr.batchid, nb.zipfile, COUNT(1) AS totalcourses, SUM(nr.status = 0) AS totalwaiting,
SUM(nr.status = 1) AS totalcomplete, nr.starttime
FROM {report_ncccscensus_reports} nr, {report_ncccscensus_batch} nb WHERE nb.id = nr.batchid
GROUP BY nr.batchid, nb.zipfile, nr.starttime
ORDER BY nr.starttime DESC
LIMIT 200';
$all = $DB->get_records_sql($query);
foreach ($all as $key => $value) {
$all[$key]->starttime = userdate($all[$key]->starttime);
}
return $all;
}
/**
* Locates courses in categories.
*
* @param array $categories List of ids of categories.
* @param bool $limittocourses Whether to limit to courses
* @return bool|array False on failure, Array of courses on success
* @uses $DB
*/
function report_ncccscensus_get_category_courses($categories, $limittocourses = false) {
global $DB;
if (count($categories) == 0) {
return false;
}
$categorycourses = array();
$tempcategory = $DB->get_in_or_equal($categories);
$limittosql = "";
if (is_array($limittocourses) && count($limittocourses) > 0) {
$limittoin = $DB->get_in_or_equal($limittocourses);
$limittosql = " AND id $limittoin[0] ";
foreach ($limittoin[1] as $temp) {
array_push($tempcategory[1], $temp);
}
}
$tempcourses = $DB->get_records_sql("SELECT id FROM {course} WHERE category $tempcategory[0] $limittosql ", $tempcategory[1]);
foreach ($tempcourses as $course) {
$categorycourses[] = $course->id;
}
if (count($categorycourses) == 0) {
return false;
}
return $categorycourses;
}
/**
* Locates courses to report on.
*
* @param array $formdata the form data
* @return bool|array False on failure, Array of courses on success
* @uses $DB
*/
function report_ncccscensus_get_courses($formdata) {
global $CFG, $DB;
require_once($CFG->libdir.'/accesslib.php');
if (empty($formdata->courses) && empty($formdata->teachers) && empty($formdata->categories)) {
// No data to select courses.
return false;
}
if (empty($formdata->courses) && empty($formdata->teachers) && !empty($formdata->categories)) {
// Show all courses in the categories selected.
$categories = preg_split('/,/', $formdata->categories);
return report_ncccscensus_get_category_courses($categories);
}
if (!empty($formdata->courses) && empty($formdata->teachers)) {
// Only courses selected.
$courses = preg_split('/,/', $formdata->courses);
if (count($courses) > 0) {
return $courses;
}
return false;
}
$teachercourses = array();
if (!empty($formdata->teachers)) {
// Load courses by teacher.
$tempin = preg_split('/,/', $formdata->teachers);
if (count($tempin) > 0) {
$teachers = $DB->get_in_or_equal($tempin);
$teachers = $DB->get_in_or_equal($tempin);
$query = "SELECT DISTINCT c.instanceid courseid FROM {role_assignments} ra,";
$query .= " {context} c, {role_capabilities} rc WHERE rc.capability in (?, ?, ?, ?)";
$query .= " AND rc.roleid = ra.roleid AND c.id = ra.contextid AND c.contextlevel = ".CONTEXT_COURSE;
$query .= " AND ra.userid $teachers[0]";
array_unshift($teachers[1], 'mod/quiz:grade');
array_unshift($teachers[1], 'mod/assignment:grade');
array_unshift($teachers[1], 'mod/forum:rate');
array_unshift($teachers[1], 'mod/glossary:rate');
$tempcourses = $DB->get_records_sql($query, $teachers[1]);
foreach ($tempcourses as $course) {
$teachercourses[] = $course->courseid;
}
}
}
if (!empty($formdata->courses) && count($teachercourses) > 0) {
// If there is courses selected and teachers, only show the common courses.
$tempcourses = preg_split('/,/', $formdata->courses);
$courses = array();
foreach ($tempcourses as $course) {
if (in_array($course, $teachercourses)) {
$courses[] = $course;
}
}
if (count($courses) > 0) {
return $courses;
} else {
return false;
}
}
// Categories and teachers selected.
if (!empty($formdata->categories) && count($teachercourses) > 0 && empty($formdata->courses)) {
$categories = preg_split('/,/', $formdata->categories);
return report_ncccscensus_get_category_courses($categories, $teachercourses);
}
if (count($teachercourses) > 0) {
// Only teacher(s) are selected.
return $teachercourses;
}
return false;
}
/**
* Performs the report function.
*
* @param array $formdata the form data
* @param int $type the report type
* @param string $saveto File to save the pdf report to.
* @return bool False on failure
* @uses $CFG, $DB
*/
function report_ncccscensus_generate_report($formdata, $type = REPORT_NCCCSCENSUS_ACTION_VIEW, $saveto = false) {
global $CFG, $DB;
require_once($CFG->libdir.'/moodlelib.php');
$reportname = 'report_ncccscensus';
$cid = $formdata->id;
// In case the form is hacked, set a default startdate to today at midnight.
if (empty($formdata->startdate)) {
$formdata->startdate = usergetmidnight(time(), get_user_timezone());
}
// In case the form is hacked, set a default enddate to today at midnight.
if (empty($formdata->enddate)) {
$formdata->enddate = $formdata->startdate;
}
// Advance enddate to tomorrow's midnight.
$formdata->enddate += DAYSECS - 1;
// This flag determines if we should display grouped users or not.
$nogroups = isset($formdata->disablegroups) ? true : false;
if ($nogroups) {
$group = false;
} else {
// If group specified, do some validation.
$group = isset($formdata->group) ? $formdata->group : false;
// In case the form is hacked, the group could be invalid.
if ($group === false || $group < 0) {
throw new report_ncccscensus_exception('cannotfindgroup');
}
if ($group > 0) {
// Validate the group ID.
if (!groups_group_exists($group)) {
throw new report_ncccscensus_exception('cannotfindgroup');
}
// Validate the group ID with respect to the course ID.
$groupdata = groups_get_course_data($cid);
$groupfound = false;
foreach ($groupdata->groups as $groupobject) {
if ($groupobject->id == $group) {
$groupfound = true;
break;
}
}
if (!$groupfound) {
throw new report_ncccscensus_exception('invalidgroupid');
}
// User could still hack form to view a group that they don't have the capability to see.
$context = context_course::instance($cid);
if (has_capability('moodle/site:accessallgroups', $context)) {
$userid = 0;
} else if (has_capability('moodle/course:managegroups', $context)) {
$userid = $USER->id;
} else {
$userid = false;
}
if ($userid === false) {
throw new report_ncccscensus_exception('invalidgroupid');
}
if ($userid != 0) {
$grouprecs = groups_get_all_groups($course->id, $userid, 0, 'g.id, g.name');
$groupnotfound = true;
foreach ($grouprecs as $grouprec) {
if ($grouprec->id == $group) {
$groupnotfound = false;
break;
}
}
if ($groupnotfound) {
throw new report_ncccscensus_exception('invalidgroupid');
}
}
}
}
$users = array();
$search = null;
if ($nogroups) {
$search = REPORT_NCCCSCENSUS_EXCLUDE_GROUP_MEMBERS;
} else if ($group > 0) {
$search = $group;
}
$users = report_ncccscensus_get_users($cid, $search);
$results = report_ncccscensus_build_grades_array($cid, $users, $formdata->startdate, $formdata->enddate);
if (empty($results)) {
return false;
}
if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
$headers = array('student' => get_string('studentfullnamehtml', $reportname));
$showstudentid = report_ncccscensus_check_field_status('showstudentid', 'html');
} else if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) {
$headers = array('student' => get_string('studentfullnamecsv', $reportname));
$showstudentid = report_ncccscensus_check_field_status('showstudentid', 'csv');
} else {
$headers = array('student' => get_string('studentfullnamepdf', $reportname));
$showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf');
}
if ($showstudentid) {
$headers['studentid'] = get_string('studentid', $reportname);
}
$headers['activity'] = get_string('activityname', $reportname);
$headers['module'] = get_string('activitymodule', $reportname);
$headers['status'] = get_string('submissionstatus', $reportname);
$headers['datesubmitted'] = get_string('submissiondate', $reportname);
$headers['grade'] = get_string('grade', $reportname);
$headers['gradedate'] = get_string('gradedate', $reportname);
$context = context_course::instance($cid);
$namesarrayview = array();
$namesarraypdf = array();
$instructors = ' - ';
$viewlink = ': <a href="'.$CFG->wwwroot.'/user/view.php?id=';
if (!empty($CFG->coursecontact)) {
$coursecontactroles = explode(',', $CFG->coursecontact);
sort($coursecontactroles);
// If a user has multiple roles, we do not want to show user multiple times as a contact.
$teachers = array();
foreach ($coursecontactroles as $roleid) {
$roleid = (int)$roleid;
if ($users = get_role_users($roleid, $context, true)) {
$role = $DB->get_record('role', array('id' => $roleid));
$rolename = format_string(role_get_name($role, $context));
foreach ($users as $teacher) {
// The $teachers array tracks whether a user is already a course contact.
if (!isset($teachers[$teacher->id])) {
$teachers[$teacher->id] = true;
$fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
$namesarrayview[] = $rolename.$viewlink.$teacher->id.'&course='.SITEID.'">'.$fullname.'</a>';
$namesarraycsv[] = $rolename.': '.$fullname;
$namesarraypdf[] = $rolename.': '.$fullname;
}
}
}
}
}
if ($type != REPORT_NCCCSCENSUS_ACTION_PDF) {
if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
// Create legend for HTML view.
$legend = new html_table();
$legend->head = array(get_string('legend', $reportname));
$legend->headspan = array(2);
$legendrow1colour = new html_table_cell();
$legendrow1colour->style = 'width: 50px; background-color: '.get_config('report_ncccscensus', 'gradeoverridecolour');
$legendrow1[] = $legendrow1colour;
$legendrow1[] = get_string('legendgradeoverride', $reportname);
$legendrow2colour = new html_table_cell();
$legendrow2colour->style = 'width: 50px; background-color: '.get_config('report_ncccscensus', 'gradenogradecolour');
$legendrow2[] = $legendrow2colour;
$legendrow2[] = get_string('legendnograde', $reportname);
$legend->data = array($legendrow1, $legendrow2);
$legendalign = array('center', 'left');
$legend->align = $legendalign;
}
$table = new html_table();
$table->head = $headers;
$align = array('left');
$numheaders = count($headers);
for ($i = 1; $i < $numheaders; $i++) {
$align[] = 'center';
}
$table->align = $align;
$table->data = array();
foreach ($results as $result) {
$datum = array();
$datum[] = $result->student;
if ($showstudentid) {
$datum[] = $result->studentid;
}
$datum[] = $result->activity;
$datum[] = $result->module;
$status = $result->status;
$grade = $result->grade;
if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) {
$specialstatus = new html_table_cell($status);
$specialstatus->style = 'background-color: '.get_config('report_ncccscensus', 'gradenogradecolour');
$status = $specialstatus;
} else if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) {
$specialstatus = new html_table_cell($status);
$specialstatus->style = 'background-color: '.get_config('report_ncccscensus', 'gradeoverridecolour');
$status = $specialstatus;
}
$datum[] = $status;
$datum[] = $result->submitdate;
if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) {
$nograde = new html_table_cell($grade);
$nograde->style = 'background-color: '.get_config('report_ncccscensus', 'gradenogradecolour');
$grade = $nograde;
} else if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) {
$overriddengrade = new html_table_cell($grade);
$overriddengrade->style = 'background-color: '.get_config('report_ncccscensus', 'gradeoverridecolour');
$grade = $overriddengrade;
}
$datum[] = $grade;
$datum[] = $result->date;
$table->data[] = $datum;
}
}
$course = $DB->get_record('course', array('id' => $cid));
if ($group > 0) {
$groupname = groups_get_group_name($group);
}
$datestring = 'n/j/y';
$reportrange = date($datestring, $formdata->startdate).' - '.date($datestring, $formdata->enddate);
if ($type != REPORT_NCCCSCENSUS_ACTION_VIEW) {
$date = usergetdate(time(), get_user_timezone());
$filename = 'CensusRpt2_';
$filename .= date('MdY_Hi', mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']));
}
if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
if (report_ncccscensus_check_field_status('showcoursename', 'html')) {
echo '<b>'.get_string('coursetitle', $reportname).':</b> '.$course->fullname.'<br>';
}
if (report_ncccscensus_check_field_status('showcoursecode', 'html')) {
echo '<b>'.get_string('coursecode', $reportname).':</b> '.$course->shortname.'<br>';
}
// Only show course ID if present.
if (report_ncccscensus_check_field_status('showcourseid', 'html') && $course->idnumber !== '') {
echo '<b>'.get_string('courseid', $reportname).':</b> '.$course->idnumber.'<br>';
}
if (report_ncccscensus_check_field_status('showteachername', 'html')) {
if (!empty($namesarrayview)) {
$instructors = implode(', ', $namesarrayview);
echo '<b>'.get_string('instructor', $reportname).':</b> '.$instructors.'<br>';
}
}
echo '<b>'.get_string('reportrange', $reportname).':</b> '.$reportrange.'<br>';
if (isset($groupname)) {
echo '<b>'.get_string('section', $reportname).':</b> '.$groupname.'<br>';
} else {
echo '<b>'.get_string('section', $reportname).':</b> '.get_string('allgroupspdf', $reportname).'<br>';
}
echo '<br>';
echo html_writer::table($table);
echo '<div id="studentfootnote" style="font-size:10px;">'.get_string('studentfootnote', $reportname).'</div>';
echo '<br>';
echo html_writer::table($legend);
echo '<br><div align="center"><a href="'.$CFG->wwwroot.'/report/ncccscensus/index.php?id='.$formdata->id.'">';
echo get_string('backtoreport', 'report_ncccscensus').'</a></div>';
} else if ($type == REPORT_NCCCSCENSUS_ACTION_PDF) {
$topheaders = array();
$topheaders['student'] = get_string('student', $reportname);
$topheaders['activity'] = get_string('activity', $reportname);
$topheaders['submission'] = get_string('submission', $reportname);
$topheaders['grade'] = get_string('grade', $reportname);
$bottomheaders = array();
$bottomheaders['student'] = array('fullname' => get_string('studentfullnamepdf', $reportname));
$showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf');
if ($showstudentid) {
$bottomheaders['student']['id'] = get_string('studentidpdf', $reportname);
}
$bottomheaders['activity'] = array('name' => get_string('activityname', $reportname),
'module' => get_string('activitymodule', $reportname));
$bottomheaders['submission'] = array('status' => get_string('submissionstatus', $reportname),
'date' => get_string('submissiondate', $reportname));
$bottomheaders['grade'] = array('grade' => get_string('grade', $reportname),
'date' => get_string('gradedatepdf', $reportname));
require_once('report.class.php');
$censusreport = new report_ncccscensus_report();
$censusreport->topheaders = $topheaders;
$censusreport->bottomheaders = $bottomheaders;
$censusreport->data = array();
foreach ($results as $result) {
$fieldarray = array();
$fieldarray['studentfullname'] = $result->student;
if ($showstudentid) {
$fieldarray['studentid'] = $result->studentid;
}
$fieldarray['activityname'] = $result->activity;
$fieldarray['activitymodule'] = $result->module;
$fieldarray['submissionstatus'] = $result->status;
$fieldarray['submissiondate'] = $result->submitdate;
$fieldarray['gradegrade'] = $result->grade;
$fieldarray['gradedate'] = $result->date;
$censusreport->data[] = array('data' => $fieldarray, 'override' => ($result->overridden != 0) ? true : false,
'nograde' => ($result->grade == get_string('nograde', $reportname) ? true : false));
}
$censusreport->filename = $filename.'.pdf';
if (report_ncccscensus_check_field_status('showcoursename', 'pdf')) {
$censusreport->top[] = array(get_string('coursetitlepdf', $reportname).':', $course->fullname);
}
if (report_ncccscensus_check_field_status('showcoursecode', 'pdf')) {
$censusreport->top[] = array(get_string('coursecodepdf', $reportname).':', $course->shortname);
}
if (report_ncccscensus_check_field_status('showcourseid', 'pdf') && $course->idnumber !== '') {
$censusreport->top[] = array(get_string('courseid', $reportname).':', $course->idnumber);
}
if (report_ncccscensus_check_field_status('showteachername', 'pdf')) {
if (!empty($namesarrayview)) {
$instructors = implode(', ', $namesarrayview);
}
$censusreport->top[] = array(get_string('instructor', $reportname).':', strip_tags($instructors));
}
$censusreport->top[] = array(get_string('reportrangepdf', $reportname).':', $reportrange);
if (isset($groupname)) {
$censusreport->top[] = array(get_string('group', $reportname).':', $groupname);
} else if ($group !== false) {
$censusreport->top[] = array(get_string('group', $reportname).':', get_string('allgroupspdf', $reportname));
}
if (report_ncccscensus_check_field_status('showsignatureline', 'pdf')) {
$censusreport->signatureline = true;
}
if (report_ncccscensus_check_field_status('showdateline', 'pdf')) {
$censusreport->dateline = true;
}
if ($footermessage = get_config('report_ncccscensus', 'footermessage')) {
$censusreport->bottom .= $footermessage;
}
$censusreport->download($saveto);
return true;
} else if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) {
if (!empty($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) {
header('Expires: 0');
header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, must-revalidate');
header('Connection: Keep-Alive');
header('Content-Language: '.current_language());
header('Keep-Alive: timeout=5, max=100');
header('Pragma: no-cache');
header('Pragma: expires');
header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
}
header('Content-Transfer-Encoding: ascii');
header('Content-Disposition: attachment; filename='.$filename.'.csv');
header('Content-Type: text/comma-separated-values');
$output = fopen('php://output', 'w');