forked from vfremaux/moodle-block_dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_dashboard.php
1711 lines (1479 loc) · 60.6 KB
/
block_dashboard.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 //$Id: block_dashboard.php,v 1.2 2012-09-12 20:07:31 vf Exp $
/**
*
* @package block-dashboard
* @category blocks
* @author Valery Fremaux (valery@club-internet.fr)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @version Moodle 2.x
*/
require_once $CFG->dirroot.'/blocks/dashboard/lib.php';
require_once $CFG->dirroot.'/blocks/dashboard/extradblib.php';
if (file_exists($CFG->libdir.'/jqplotlib.php')){
$graphlibs = $CFG->libdir;
$graphwww = '/lib';
} else {
$graphlibs = '_goodies/lib';
$graphwww = '/blocks/dashboard/_goodies/lib';
}
require_once $graphlibs.'/jqplotlib.php';
require_once $graphlibs.'/googleplotlib.php';
require_once $graphlibs.'/timelinelib.php';
include_once $CFG->libdir.'/tablelib.php';
require_jqplot_libs($graphwww);
timeline_require_js($graphwww);
global $PAGE;
$PAGE->requires->js('/blocks/dashboard/js/module.js');
$PAGE->requires->js('/blocks/dashboard/js/dhtmlxCalendar/codebase/dhtmlxcalendar.css');
$PAGE->requires->js('/blocks/dashboard/js/dhtmlxCalendar/codebase/skins/dhtmlxcalendar_dhx_web.css');
class block_dashboard extends block_base {
var $devmode = true; // use local moodle database to develop virual tools.
var $filtervalues; // collects effective filter values set by user
var $paramvalues; // collects effective param values set by user
var $filters; // stores filter definitions
var $params; // stores user parameter definitions
var $output; // stores output definition from query
var $outputf; // stores output formats specifiers from query
var $benches; // stores SQL bench info
function init() {
$this->title = get_string('blockname', 'block_dashboard');
$this->version = 2013032600;
$this->filtervalues = array();
$this->paramvalues = array();
$this->params = array();
$this->filters = array();
$this->output = array();
$this->outputf = array();
}
function specialization(){
if (!empty($this->config->title)) {
$this->title = $this->config->title;
}
}
function hide_header(){
if (!isset($this->config->hidetitle)) return false;
return $this->config->hidetitle;
}
function has_config() {
return true;
}
function instance_allow_multiple() {
return true;
}
function instance_allow_config() {
return true;
}
function instance_config_save($data, $notused = false){
global $USER;
// check if curent user forcing a filelocationadminoverride can really do it
// in case it seems to be forced, set it to empty anyway.
if (!has_capability('block/dashboard:systempathaccess', context_system::instance())){
$data->filepathadminoverride = '';
}
// retrieve sql params directly from POST
$data->sqlparams = @$_POST['sqlparams'];
// print_object($data);
return parent::instance_config_save($data, $notused);
}
function applicable_formats() {
// Default case: the block can be used in all course types
return array('all' => true,
'site' => true);
}
function get_content() {
global $EXTRADBCONNECT, $CFG, $COURSE;
@raise_memory_limit('256M');
// special patch for 1.9 queries
if (preg_match('/block_instance\b/', @$this->config->query)){
$this->content = new StdClass;
$this->content->text = get_string('obsoletequery', 'block_dashboard');
$this->content->footer = '';
return $this->content;
}
if ($this->content !== NULL) {
return $this->content;
}
$this->content = new StdClass;
if (@$this->config->inblocklayout){
$this->content->text = $this->print_dashboard();
$this->content->text = '';
} else {
$viewdashboardstr = get_string('viewdashboard', 'block_dashboard');
$this->content->text .= "<a href=\"{$CFG->wwwroot}/blocks/dashboard/view.php?id={$COURSE->id}&blockid={$this->instance->id}\">$viewdashboardstr</a>";
}
$this->content->footer = '';
return $this->content;
}
/**
* Real raster that prints graphs and data
*
*/
function print_dashboard(){
global $CFG, $EXTRADBCONNECT, $COURSE, $DB, $OUTPUT;
/*
$text = '<link type="text/css" rel="stylesheet" href="'.$CFG->wwwroot.'/blocks/dashboard/js/dhtmlxCalendar/codebase/dhtmlxcalendar.css" />';
$text .= '<link type="text/css" rel="stylesheet" href="'.$CFG->wwwroot.'/blocks/dashboard/js/dhtmlxCalendar/codebase/skins/dhtmlxcalendar_dhx_web.css" />';
*/
$text = '';
if (!isset($this->config)){
$this->config = new StdClass;
}
$this->config->limit = 20;
$coursepage = '';
if ($COURSE->format == 'page'){
include_once($CFG->dirroot.'/course/format/page/lib.php');
$pageid = optional_param('page', 0, PARAM_INT); // flexipage page number
if (!$pageid){
$flexpage = course_page::get_current_page($COURSE->id);
} else {
$flexpage = new StdClass;
$flexpage->id = $pageid;
}
$coursepage = "&page=".$flexpage->id;
}
$rpage = optional_param('rpage'.$this->instance->id, 0, PARAM_INT); // result page
if ($rpage < 0){
$rpage = 0;
}
// unlogged people cannot see their status
if ((!isloggedin() || isguestuser()) && @$this->config->guestsallowed){
$text = get_string('guestsnotallowed', 'block_dashboard');
$loginstr = get_string('login');
$text .= "<a href=\"{$wwwroot}/login/index.php\">$loginstr</a>";
return $text;
}
if (!isset($this->config) || empty($this->config->query)){
$noquerystr = get_string('noquerystored', 'block_dashboard');
$text = $noquerystr;
return $text;
}
if (!isset($CFG->block_dashboard_big_result_threshold)) $CFG->block_dashboard_big_result_threshold = 500;
// connecting
if ($this->config->target == 'moodle'){
// already connected
} else {
$error = '';
if (!isset($EXTRADBCONNECT)) $EXTRADBCONNECT = extra_db_connect(true, $error);
if ($error){
$text = $error;
return $text;
}
}
// prepare all params from config
$this->prepare_config();
$graphdata = array();
$ticks = array();
$filterquerystring = '';
if (!empty($this->config->filters)){
try {
$filterquerystring = $this->prepare_filters();
} catch (Exception $e) {
if (debugging()){
echo $e->error;
}
return get_string('invalidorobsoletefilterquery', 'block_dashboard');
}
} else {
$this->filteredsql = str_replace('<%%FILTERS%%>', '', $this->sql);
}
$this->sql = str_replace('<%%FILTERS%%>', '', $this->sql); // needed to prepare for filter range prefetch
if (!empty($this->params)){
$filterquerystring = ($filterquerystring) ? $filterquerystring.'&'.$this->prepare_params() : $this->prepare_params() ;
} else {
$this->sql = str_replace('<%%PARAMS%%>', '', $this->sql); // needed to prepare for filter range prefetch
$this->filteredsql = str_replace('<%%PARAMS%%>', '', $this->filteredsql); // needed to prepare for filter range prefetch
}
$sort = optional_param('tsort'.$this->instance->id, @$this->config->defaultsort, PARAM_TEXT);
if (!empty($sort)){
// do not sort if already sorted in explained query
if (!preg_match('/ORDER\s+BY/si', $this->sql))
$this->filteredsql .= " ORDER BY $sort";
}
$this->filteredsql = $this->protect($this->filteredsql);
// ######### GETTING RESULTS
$countres = $this->count_records($error);
// if too many results, we force paging mode
if (empty($this->config->pagesize) && ($countres > $CFG->block_dashboard_big_result_threshold) && !empty($this->config->bigresult)){
$text .= '<span class="error">'.get_string('toomanyrecordsusepaging', 'block_dashboard').'</span><br/>';
$this->config->pagesize = $CFG->block_dashboard_big_result_threshold;
$rpage = 0;
}
// getting real results including page and offset
if (!empty($this->config->pagesize)){
$offset = $rpage * $this->config->pagesize;
} else {
$offset = '';
}
try {
$results = $this->fetch_dashboard_data($this->filteredsql, @$this->config->pagesize, $offset);
} catch (Exception $e){
return get_string('invalidorobsoletequery', 'block_dashboard', $this->config->query);
}
if ($results){
$table = new flexible_table('mod-dashboard'.$this->instance->id);
$instancecontrolvars = array(
TABLE_VAR_PAGE => 'rpage'.$this->instance->id,
TABLE_VAR_SORT => 'tsort'.$this->instance->id,
TABLE_VAR_HIDE => 'thide'.$this->instance->id,
TABLE_VAR_SHOW => 'tshow'.$this->instance->id,
);
$table->set_control_variables($instancecontrolvars); // use full not to collide with flexipage paging
$tablecolumns = array();
$tableheaders = array();
foreach($this->output as $field => $label){
$tablecolumns[] = $field;
$tableheaders[] = $label;
}
$table->define_columns($tablecolumns);
$table->define_headers($tableheaders);
$filterquerystringadd = (isset($filterquerystring)) ? "&$filterquerystring" : '' ;
if (@$this->config->inblocklayout){
$table->define_baseurl($CFG->wwwroot.'/course/view.php?id='.$COURSE->id.$coursepage.$filterquerystringadd);
} else {
$table->define_baseurl($CFG->wwwroot.'/blocks/dashboard/view.php?id='.$COURSE->id.'&blockid='.$this->instance->id.$coursepage.$filterquerystringadd);
}
if (!empty($this->config->sortable)) $table->sortable(true, $this->config->xaxisfield, SORT_DESC); //sorted by xaxisfield by default
$table->collapsible(true);
$table->initialbars(true);
$table->set_attribute('cellspacing', '0');
$table->set_attribute('id', 'dashboard'.$this->instance->id);
$table->set_attribute('class', 'dashboard');
$table->set_attribute('width', '100%');
foreach($this->output as $field => $label){
$table->column_class($field, $field);
}
$table->setup();
/*
$where = $table->get_sql_where();
$sortsql = $table->get_sql_sort();
*/
if (!empty($this->config->pagesize)){
$table->pagesize($this->config->pagesize, $countres); // no paginating at start
}
$graphseries = array();
$treedata = array();
$treekeys = array();
$lastvalue = array();
$hcols = array();
$splitnumsonsort = @$this->config->splitsumsonsort;
foreach($results as $result){
// prepare for subsums
if (!empty($splitnumsonsort)){
$orderkeyed = strtoupper($result->$splitnumsonsort);
if (!isset($oldorderkeyed)) $oldorderkeyed = $orderkeyed; // first time
}
// pre-aggregates sums
if (!empty($this->config->shownumsums)){
foreach(array_keys($this->numsumsf) as $numsum){
if (empty($numsum)) continue;
if (!isset($result->$numsum)) continue;
// make subaggregates (only for linear tables and when sorting criteria is the split column)
// post aggregate after table output
if (!isset($aggr)) $aggr = new StdClass;
$aggr->$numsum = 0 + (float)@$aggr->$numsum + (float)$result->$numsum;
if (!empty($splitnumsonsort) && @$this->config->tabletype == 'linear' && (preg_match("/\\b$splitnumsonsort\\b/", $sort))){
$this->subaggr[$orderkeyed]->$numsum = 0 + (float)@$this->subaggr[$orderkeyed]->$numsum + (float)$result->$numsum;
}
}
}
if (!empty($splitnumsonsort) && @$this->config->tabletype == 'linear' && (preg_match("/\\b$splitnumsonsort\\b/", $sort))){
if ($orderkeyed != $oldorderkeyed){ // when range changes
$k = 0;
$tabledata = null;
foreach(array_keys($this->output) as $field){
if (in_array($field, array_keys($this->numsumsf))){
if (is_null($tabledata)){
$tabledata = array();
for ($j = 0 ; $j < $k ; $j++){
$tabledata[$j] = '';
}
}
$tabledata[$k] = '<b>Tot: '.@$this->subaggr[$oldorderkeyed]->$field.'</b>';
}
$k++;
}
if (!is_null($tabledata)){
$table->add_data($tabledata);
}
$oldorderkeyed = $orderkeyed;
}
}
// Print data in results
if (!empty($this->config->showdata)){
if (empty($this->config->tabletype) || $this->config->tabletype == 'linear'){
$tabledata = array();
foreach(array_keys($this->output) as $field){
if (empty($field)) continue;
// did we ask for cumulative results ?
$cumulativeix = null;
if (preg_match('/S\((.+?)\)/', $field, $matches)){
$field = $matches[1];
$cumulativeix = $this->instance->id.'_'.$field;
}
if (!empty($this->outputf[$field])){
$datum = dashboard_format_data($this->outputf[$field], $result->$field, $cumulativeix);
} else {
$datum = dashboard_format_data(null, @$result->$field, $cumulativeix);
}
// process coloring if required
if (!empty($this->config->colorfield) && $this->config->colorfield == $field){
$datum = dashboard_colour_code($this, $datum, $this->colourcoding);
}
if (!empty($this->config->cleandisplay)){
if (!array_key_exists($field, $lastvalue) || ($lastvalue[$field] != $datum)){
$lastvalue[$field] = $datum;
$tabledata[] = $datum;
} else {
$tabledata[] = ''; // if same as above, add blanck
}
} else {
$tabledata[] = $datum;
}
}
$table->add_data($tabledata);
} else if ($this->config->tabletype == 'tabular') {
// this is a tabular table
/* in a tabular table, data can be placed :
* - in first columns in order of vertical keys
* the results are grabbed sequentially and spread into the matrix
*/
$keystack = array();
$matrix = array();
foreach(array_keys($this->vertkeys->formats) as $vkey){
if (empty($vkey)) continue;
$vkeyvalue = $result->$vkey;
$matrix[] = "['".addslashes($vkeyvalue)."']";
}
$hkey = $this->config->horizkey;
$hkeyvalue = (!empty($hkey)) ? $result->$hkey : '' ;
$matrix[] = "['".addslashes($hkeyvalue)."']";
$matrixst = "\$m".implode($matrix);
if (!in_array($hkeyvalue, $hcols)) $hcols[] = $hkeyvalue;
// now put the cell value in it
$outvalues = array();
foreach(array_keys($this->output) as $field){
// did we ask for cumulative results ?
$cumulativeix = null;
if (preg_match('/S\((.+?)\)/', $field, $matches)){
$field = $matches[1];
$cumulativeix = $this->instance->id.'_'.$field;
}
if (!empty($this->outputf[$field])){
$datum = dashboard_format_data($this->outputf[$field], $result->$field, $cumulativeix);
} else {
$datum = dashboard_format_data(null, @$result->$field, $cumulativeix);
}
if (!empty($this->config->colorfield) && $this->config->colorfield == $field){
$datum = dashboard_colour_code($this, $datum, $this->colourcoding);
}
$outvalues[] = str_replace("\"", "\\\"", $datum);
}
$matrixst .= ' = "'.implode(' ',$outvalues).'"';
// make the matrix in memory
eval($matrixst.";");
} else {
$debug = optional_param('debug', false, PARAM_BOOL);
// treeview
$resultarr = array_values((array)$result);
$resultid = $resultarr[0];
if (!empty($parentserie)){
if (!empty($result->$parentserie)){
// non root node, attache to his parent if we found it
if (array_key_exists($result->$parentserie, $treekeys)){
if (!empty($debug)) echo 'binding to '. $result->$parentserie.'. ';
$treekeys[$result->$parentserie]->childs[$resultid] = $result;
if (!array_key_exists($resultid, $treekeys)){
$treekeys[$resultid] = $result;
}
} else {
// in case nodes do not come in correct order, do not connect but register only
if (!empty($debug)) echo 'waiting for '. $result->$parentserie.'. ';
$waitingnodes[$resultid] = $result;
if (!array_key_exists($resultid, $treekeys)){
$treekeys[$resultid] = $result;
}
}
} else {
// root node
if (!empty($debug)) echo 'root as '. $resultid.'. ';
if (!array_key_exists($resultid, $treekeys)){
$treekeys[$resultid] = $result;
}
$treedata[$resultid] = &$treekeys[$resultid];
}
} else {
if (!array_key_exists($resultid, $treekeys)){
$treekeys[$resultid] = $result;
}
}
}
}
// Prepare data for graphs
if (!empty($this->config->showgraph)){
if (!empty($this->config->xaxisfield) && $this->config->graphtype != 'googlemap' && $this->config->graphtype != 'timeline'){
$xaxisfield = $this->config->xaxisfield;
if ($this->config->graphtype != 'pie'){
// TODO : check if $this->config->xaxisfield exists really (misconfiguration)
$ticks[] = addslashes($result->$xaxisfield);
$ys = 0;
foreach(array_keys($this->yseriesf) as $yserie){
if (!isset($result->$yserie)) continue;
// did we ask for cumulative results ?
$cumulativeix = null;
if (preg_match('/S\((.+?)\)/', $yserie, $matches)){
$yserie = $matches[1];
$cumulativeix = $this->instance->id.'_'.$yserie;
}
if ($this->config->graphtype != 'timegraph'){
if (!empty($this->yseriesf[$yserie])){
$graphseries[$yserie][] = dashboard_format_data($this->yseriesf[$yserie], $result->$yserie, $cumulativeix);
} else {
$graphseries[$yserie][] = dashboard_format_data(null, $result->$yserie, $cumulativeix);
}
} else {
if (!empty($this->yseriesf[$yserie])){
$timeelm = array($result->$xaxisfield, dashboard_format_data($this->yseriesf[$yserie], $result->$yserie, $cumulativeix));
$graphseries[$ys][] = $timeelm;
} else {
$timeelm = array($result->$xaxisfield, dashboard_format_data(null, $result->$yserie, $cumulativeix));
$graphseries[$ys][] = $timeelm;
}
}
$ys++;
}
} elseif ($this->config->graphtype == 'pie') {
foreach($yseries as $yserie){
if (empty($result->$xaxisfield)) $result->$xaxisfield = 'N.C.';
if (!empty($this->yseriesf[$field])){
$graphseries[$yserie][] = array($result->$xaxisfield, dashboard_format_data($this->yseriesf[$field], $result->$yserie, false));
} else {
$graphseries[$yserie][] = array($result->$xaxisfield, $result->$yserie);
}
}
}
} else {
$data[] = $result;
}
}
$graphdata = array_values($graphseries);
}
//************ post aggregating last subtotal *************//
if (!empty($this->config->shownumsums) && $results){
if (!empty($splitnumsonsort) && @$this->config->tabletype == 'linear' && (preg_match("/\\b$splitnumsonsort\\b/", $sort))){
$k = 0;
$tabledata = null;
foreach(array_keys($this->output) as $field){
if (in_array($field, array_keys($this->numsumsf))){
if (is_null($tabledata)){
$tabledata = array();
for ($j = 0 ; $j < $k ; $j++){
$tabledata[$j] = '';
}
}
$tabledata[$k] = '<b>Tot: '.@$this->subaggr[$orderkeyed]->$field.'</b>';
}
$k++;
}
$oldorderkeyed = $orderkeyed;
if (!is_null($tabledata)){
$table->add_data($tabledata);
}
}
}
//************ Starting outputing data ************************//
// if treeview, need to post process waiting nodes
if (@$this->config->tabletype == 'treeview'){
if(!empty($waitingnodes)){
foreach($waitingnodes as $wnid => $wn){
if (array_key_exists($wn->$parentserie, $treekeys)){
if (!empty($debug)) echo ' postbinding to '. $wn->$parentserie.'. ';
$treekeys[$wn->$parentserie]->childs[$wnid] = $wn;
unset($waitingnodes[$wnid]); // free some stuff
}
}
}
}
if (@$this->config->inblocklayout){
$url = $CFG->wwwroot.'/course/view.php?id='.$COURSE->id.$coursepage.'&tsort'.$this->instance->id.'='.$sort;
} else {
$url = $CFG->wwwroot.'/blocks/dashboard/view.php?id='.$COURSE->id.'&blocksid='.$this->instance->id.$coursepage.'&tsort'.$this->instance->id.'='.$sort;
}
$text .= dashboard_render_filters_and_params_form($this, $sort);
if ($this->config->showdata){
$allexportstr = get_string('exportall', 'block_dashboard');
$tableexportstr = get_string('exportdataastable', 'block_dashboard');
$filteredexportstr = get_string('exportfiltered', 'block_dashboard');
$filterquerystring = (!empty($filterquerystring)) ? '&'.$filterquerystring : '' ;
if (empty($this->config->tabletype) || @$this->config->tabletype == 'linear'){
ob_start();
$table->print_html();
$text .= ob_get_clean();
$text .= "<div style=\"text-align:right\">";
$text .= "<a href=\"{$CFG->wwwroot}/blocks/dashboard/export/export_csv.php?id={$COURSE->id}&instance={$this->instance->id}&tsort{$this->instance->id}={$sort}&alldata=1\">$allexportstr</a>";
if ($filterquerystring){
$text .= " - <a href=\"{$CFG->wwwroot}/blocks/dashboard/export/export_csv.php?id={$COURSE->id}&instance={$this->instance->id}&tsort{$this->instance->id}={$sort}{$filterquerystring}\">$filteredexportstr</a>";
}
$text .= "</div>";
} elseif (@$this->config->tabletype == 'tabular') {
// forget table and use $m matrix for making display
$text .= print_cross_table($this, $m, $hcols, $this->config->horizkey, $this->vertkeys, $this->config->horizlabel, true);
$text .= "<div style=\"text-align:right\"><a href=\"{$CFG->wwwroot}/blocks/dashboard/export/export_csv.php?id={$COURSE->id}&instance={$this->instance->id}&tsort{$this->instance->id}={$sort}&alldata=1\">$allexportstr</a></div>";
$text .= "<div style=\"text-align:right\"><a href=\"{$CFG->wwwroot}/blocks/dashboard/export/export_csv_tabular.php?id={$COURSE->id}&instance={$this->instance->id}&tsort{$this->instance->id}={$sort}{$filterquerystring}\">$tableexportstr</a></div>";
} else {
$text .= dashboard_print_tree_view($this, $treedata, $this->treeoutput, $this->output, $this->outputf, $this->colourcoding, true);
$text .= "<div style=\"text-align:right\"><a href=\"{$CFG->wwwroot}/blocks/dashboard/export/export_csv.php?id={$COURSE->id}&instance={$this->instance->id}&tsort{$this->instance->id}={$sort}&alldata=1\">$allexportstr</a></div>";
}
} else {
$text .= '';
}
} else {
// no data, but render filters anyway
$text .= dashboard_render_filters_and_params_form($this, $sort);
}
// showing graph
if ($this->config->showgraph && !empty($this->config->graphtype)){
$text .= $OUTPUT->box_start('dashboard-graph-box');
$graphdesc = $this->dashboard_graph_properties();
if ($this->config->graphtype != 'googlemap' && $this->config->graphtype != 'timeline'){
$data = $graphdata;
$text .= jqplot_print_graph('dashboard'.$this->instance->id, $graphdesc, $data, $this->config->graphwidth, $this->config->graphheight, '', true, $ticks);
} elseif ($this->config->graphtype == 'googlemap') {
$text .= dashboard_render_googlemaps_data($this, $data, $graphdesc);
} else {
// timeline graph
if (empty($this->config->timelineeventstart) || empty($this->config->timelineeventend)){
$text .= $OUTPUT->notification("Missing mappings (start or titles)", 'notifyproblem');
} else {
$text .= timeline_print_graph($this, 'dashboard'.$this->instance->id, $this->config->graphwidth, $this->config->graphheight, $data, true);
}
}
$text .= $OUTPUT->box_end();
}
// showing bottom summators
if ($this->config->numsums){
$text .= dashboard_render_numsums($this, $aggr);
}
// showing query
if (@$this->config->showquery){
$text .= '<div class="dashboard-query-box" style="padding:1px;border:1px solid #808080;margin:2px;font-size:0.75em;font-family:monospace">';
$text .= '<pre>'.$this->filteredsql.'</pre>';
$text .= '</div>';
}
// showing SQL benches
if (@$this->config->showbenches){
$text .= '<div class="dashboard-benches-box" style="padding:1px;border:1px solid #808080;margin:2px;font-size:0.75em;font-family:monospace">';
$text .= '<table width="100%">';
foreach($this->benches as $bench){
$value = $bench->end - $bench->start;
$text .= "<tr><td>{$bench->name}</td><td>{$value} sec.</td></tr>";
}
$text .= '</table>';
$text .= '</div>';
}
return $text;
}
/**
* build a graph descriptor, taking some defaults decisions
*
*/
function dashboard_graph_properties(){
$jqplot = array();
$yserieslabels = explode(';', $this->config->serieslabels);
$labelarray = array();
foreach($yserieslabels as $label){
$labelarray[] = array('label' => $label);
}
if ($this->config->graphtype == 'line'){
$jqplot = array(
'axesDefaults' => array(
'labelRenderer' => '$.jqplot.CanvasAxisLabelRenderer'
),
'axes' => array(
'xaxis' => array(
'label' => @$this->config->xaxislabel,
'renderer' => '$.jqplot.CategoryAxisRenderer',
'tickRenderer' => '$.jqplot.CanvasAxisTickRenderer',
'tickOptions' => array(
'angle' => @$this->config->yaxistickangle
)
),
'yaxis' => array(
'autoscale' => true,
'pad' => 0,
'tickOptions' => array('formatString' => '%2d'),
'label' => @$this->config->yaxislabel,
'labelRenderer' => '$.jqplot.CanvasAxisLabelRenderer',
'labelOptions' => array('angle' => 90)
)
),
);
if (@$this->config->yaxisscale == 'log'){
$jqplot['axes']['yaxis']['renderer'] = '$.jqplot.LogAxisRenderer';
$jqplot['axes']['yaxis']['rendererOptions'] = array('base' => 10, 'tickDistribution' => 'even');
}
} elseif($this->config->graphtype == 'bar') {
$jqplot = array(
'seriesDefaults' => array(
'renderer' => '$.jqplot.BarRenderer',
'rendererOptions' => array(
'fillToZero' => true
),
),
'series' => $labelarray,
'axes' => array(
'xaxis' => array(
'tickRenderer' => '$.jqplot.CanvasAxisTickRenderer',
'tickOptions' => array(
'angle' => @$this->config->yaxistickangle
),
'renderer' => '$.jqplot.CategoryAxisRenderer',
'label' => @$this->config->xaxislabel,
'ticks' => '$$.ticks',
),
'yaxis' => array(
'autoscale' => true,
'padMax' => 5,
'label' => @$this->config->yaxislabel,
'rendererOptions' => array('forceTickAt0' => true),
'tickOptions' => array('formatString' => '%2d'),
'labelRenderer' => '$.jqplot.CanvasAxisLabelRenderer',
'labelOptions' => array('angle' => 90),
),
),
);
if (@$this->config->yaxisscale == 'log'){
$jqplot['axes']['yaxis']['renderer'] = '$.jqplot.LogAxisRenderer';
}
} elseif($this->config->graphtype == 'pie') {
$jqplot = array(
'seriesDefaults' => array(
'renderer' => '$.jqplot.PieRenderer',
'rendererOptions' => array(
'showDataLabels' => true
),
),
'cursor' => array(
'useAxesFormatters' => false,
'show' => false,
),
'highlighter' => array(
'useAxesFormatters' => false,
),
);
} elseif($this->config->graphtype == 'donut') {
$jqplot = array(
'seriesDefaults' => array(
'renderer' => '$.jqplot.DonutRenderer',
'rendererOptions' => array(
'showDataLabels' => true
),
),
'cursor' => array(
'useAxesFormatters' => false,
'show' => false,
),
'highlighter' => array(
'useAxesFormatters' => false,
),
);
} elseif($this->config->graphtype == 'timegraph') {
$jqplot = array(
'axesDefaults' => array(
'labelRenderer' => '$.jqplot.CanvasAxisLabelRenderer'
),
'axes' => array(
'xaxis' => array(
'label' => @$this->config->xaxislabel,
'renderer' => '$.jqplot.DateAxisRenderer',
'tickRenderer' => '$.jqplot.CanvasAxisTickRenderer',
'tickOptions' => array(
'angle' => @$this->config->yaxistickangle
),
),
'yaxis' => array(
'autoscale' => true,
'pad' => 0,
'tickOptions' => array('formatString' => '%2d'),
'label' => @$this->config->yaxislabel,
'labelRenderer' => '$.jqplot.CanvasAxisLabelRenderer',
'labelOptions' => array('angle' => 90)
)
),
);
if (@$this->config->yaxisscale == 'log'){
$jqplot['axes']['yaxis']['renderer'] = '$.jqplot.LogAxisRenderer';
$jqplot['axes']['yaxis']['rendererOptions'] = array('base' => 10, 'tickDistribution' => 'even');
}
} elseif($this->config->graphtype == 'googlemap') {
if (empty($this->config->maptype)) $this->config->maptype = 'ROADMAP';
if (empty($this->config->zoom)) $this->config->zoom = 6;
$jqplot = array(
'zoom' => $this->config->zoom,
'center' => 'latlng',
'mapTypeId' => 'google.maps.MapTypeId.'.$this->config->maptype
);
}
if (!empty($this->config->showlegend)){
$jqplot['legend'] = array(
'show' => true,
'location' => 'e',
'placement' => 'outsideGrid',
'showSwatch' => true,
'marginLeft' => '10px',
'border' => '1px solid #808080',
'labels' => $yserieslabels,
);
}
if (!empty($this->config->ymin) || @$this->config->ymin === 0){
$jqplot['axes']['yaxis']['min'] = (integer)$this->config->ymin;
$jqplot['axes']['yaxis']['autoscale'] = false;
}
if (!empty($this->config->ymax) || @$this->config->ymax === 0){
$jqplot['axes']['yaxis']['max'] = (integer)$this->config->ymax;
$jqplot['axes']['yaxis']['autoscale'] = false;
}
if (!empty($this->config->tickspacing)){
$jqplot['axes']['yaxis']['tickInterval'] = (integer)$this->config->tickspacing;
}
return $jqplot;
}
/**
* this function protects the final queries against any harmfull
* attempt to change something in the database
*
* rule 1 : avoiding any SQL words that refer to a change. Will resul in syntax error
* rule 2 : avoiding closing char ";" to appear so a query cannot close to start a new one
*/
function protect($sql){
$sql = preg_replace('/\b(UPDATE|ALTER|DELETE|INSERT|DROP|CREATE)\b/i', '', $sql);
$sql = preg_replace('/;/', '', $sql);
return $sql;
}
/**
*
*
*/
function get_count_records_sql($sql){
$sql = "SELECT COUNT(*) FROM ($sql) as fullrecs ";
// $sql = preg_replace('/^\s*SELECT(.*?)\sFROM\s/si', 'SELECT COUNT(*) FROM', $sql);
// $sql = preg_replace('/\s*ORDER BY.*/si', '', $sql); // remove any ordering
return $sql;
}
/**
* provides constraint values from filters
*
*/
function filter_get_results($fielddef, $fieldname, $specialvalue = '', $forcereload = false, &$printoutbuffer = null){
static $FILTERSETS;
global $CFG, $DB, $PAGE;
$tracing = 0;
// computes filter query
if (empty($this->filterfields->queries[$fielddef])){
// if not explicit query, make an implicit one
$sql = preg_replace('/<%%FILTERS%%>|<%%PARAMS%%>/', '', $this->sql);
if ($this->allow_filter_desaggregate($fielddef)){
// try desagregate
$sql = preg_replace('/MAX\(([^\(]+)\)/si', '$1', $sql);
$sql = preg_replace('/SUM\((.*?)\) AS/si', '$1 AS', $sql);
$sql = preg_replace('/COUNT\((?:DISTINCT)?([^\(]+)\)/si', '$1', $sql);
// purge from unwanted clauses
if (preg_match('/\bGROUP BY\b/si', $sql)){
$sql = preg_replace('/GROUP BY.*(?!GROUP BY).*$/si', '', $sql);
}
if (preg_match('/\bORDER BY\b/si', $sql)){
$sql = preg_replace('/ORDER BY.*?$/si', '', $sql);
}
}
$filtersql = 'SELECT DISTINCT '.$fieldname.' FROM ( '.$sql.' ) as subreq ';
$filtersql .= " ORDER BY $fieldname ";
} else {
// explicit query, manager will have to ensure consistency of output values to filter requirement
$filtersql = $this->filterfields->queries[$fielddef];
}
$filtersql = $this->protect($filtersql);
// filter values return from cache
if (isset($FILTERSETS) && array_key_exists($fielddef, $FILTERSETS) && empty($specialvalue)){
if (!empty($this->config->showfilterqueries)){
if (!is_null($printoutbuffer))
$printoutbuffer .= "<div class=\"dashboard-filter-query\" style=\"padding:1px;border:1px solid #808080;margin:2px;font-size;0.75em;font-family:monospace\"><b>STATIC CACHED DATA FILTER :</b> $filtersql</div>";
}
return $FILTERSETS[$fielddef];
}
// check DB cache
$sqlkey = md5($filtersql);
if (@$this->config->showbenches){
$bench = new StdClass;
$bench->name = 'Filter cache prefetch '.$fielddef;
$bench->start = time();
}
$cachefootprint = $DB->get_record('block_dashboard_filter_cache', array('querykey' => $sqlkey, 'access' => $this->config->target));
if (@$this->config->showbenches){
$bench->end = time();
$this->benches[] = $bench;
}
if ((!$PAGE->user_is_editing() || !@$CFG->block_dashboard_enable_isediting_security) && (!@$this->config->uselocalcaching || !$cachefootprint || ($cachefootprint && $cachefootprint->timereloaded < time() - @$this->config->cachingttl * 60) || $forcereload)){
$DB->delete_records('block_dashboard_filter_cache', array('querykey' => $sqlkey, 'access' => $this->config->target));
list($usec, $sec) = explode(' ', microtime());
$t1 = (float)$usec + (float)$sec;
if ($this->config->target == 'moodle'){
if (@$this->config->showbenches){
$bench = new StdClass;
$bench->name = 'Filter pre-query '.$fielddef;
$bench->start = time();
}
$FILTERSET[$fielddef] = $DB->get_records_sql($filtersql);
if (@$this->config->showbenches){
$bench->end = time();
$this->benches[] = $bench;
}
} else {
if (!isediting() || !@$CFG->block_dashboard_enable_isediting_security){
$FILTERSET[$fielddef] = extra_db_query($filtersql, false, true, $error);
if ($error){
$this->content->text .= $error;
}
} else {
$FILTERSET[$fielddef] = array();
}
}
list($usec, $sec) = explode(' ', microtime());
$t2 = (float)$usec + (float)$sec;
// echo $t2 - $t1; // benching
// make a footprint
if(!empty($this->config->uselocalcaching)){
$cacherec = new StdClass;
$cacherec->access = $this->config->target;
$cacherec->querykey = $sqlkey;
$cacherec->filterrecord = base64_encode(serialize($FILTERSET[$fielddef]));
$cacherec->timereloaded = time();
if ($tracing) mtrace('Inserting filter cache');
$DB->insert_record('block_dashboard_filter_cache', $cacherec);
}