forked from vfremaux/moodle-block_dashboard
-
Notifications
You must be signed in to change notification settings - Fork 1
/
block_dashboard.php
1533 lines (1333 loc) · 62.2 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
// 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/>.
/**
* @package block_dashboard
* @category blocks
* @author Valery Fremaux ([email protected])
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
*/
defined('MOODLE_INTERNAL') || die();
define('DASHBOARD_MAX_QUERY_PARAMS', 10);
require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
require_once($CFG->dirroot.'/blocks/dashboard/lib.php');
require_once($CFG->dirroot.'/blocks/dashboard/classes/filter_query_exception.class.php');
require_once($CFG->dirroot.'/blocks/dashboard/classes/filter_query_cache_exception.class.php');
require_once($CFG->dirroot.'/blocks/dashboard/lib.php');
require_once($CFG->dirroot.'/blocks/dashboard/extradblib.php');
require_once($CFG->dirroot.'/local/vflibs/jqplotlib.php');
if (block_dashboard_supports_feature('result/rotate')) {
include_once($CFG->dirroot.'/blocks/dashboard/pro/lib.php');
}
require_once($CFG->dirroot.'/blocks/dashboard/lib.php');
class block_dashboard extends block_base {
protected $devmode = true; // Use local moodle database to develop virual tools.
public $filtervalues; // Collects effective filter values set by user.
public $paramvalues; // Collects effective param values set by user.
public $filters; // Stores filter definitions.
public $filteredsql; // Stores filter filtered sql.
public $params; // Stores user parameter definitions.
public $output; // Stores output definition from query.
public $outputf; // Stores output formats specifiers from query.
protected $benches; // Stores SQL bench info.
public 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();
$this->filteredsql = '';
}
public function specialization() {
if (!empty($this->config->title)) {
$this->title = $this->config->title;
}
}
public function hide_header() {
if (!isset($this->config->hidetitle)) {
return false;
}
return $this->config->hidetitle;
}
public function has_config() {
return true;
}
public function instance_allow_multiple() {
return true;
}
public function instance_allow_config() {
return true;
}
public function instance_config_save($data, $nolongerused = false) {
global $USER;
/*
* Check if current 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'];
// Reset cron activation internal switches.
$data->isrunning = 0;
$data->lastcron = 0;
$config = clone($data);
// Move embedded files into a proper filearea and adjust HTML links to match
$config->description = file_save_draft_area_files(@$data->description['itemid'], $this->context->id, 'block_dashboard', 'description',
0, array('subdirs'=>true), @$data->description['text']);
$config->descriptionformat = @$data->description['format'];
return parent::instance_config_save($config, $nolongerused);
}
public function applicable_formats() {
// Default case: the block can be used in all course types.
return array('all' => true, 'site' => true);
}
public function get_content() {
global $extradbcnx, $COURSE, $PAGE, $CFG;
$this->get_required_javascript();
$context = context_block::instance($this->instance->id);
$renderer = $PAGE->get_renderer('block_dashboard');
@raise_memory_limit('512M');
if (!empty($this->config->query)) {
preg_replace('/block_instance\b/', 'block_instances', $this->config->query);
preg_replace('/\{(.*?)\}/', $CFG->prefix."\\1", $this->config->query);
}
if ($this->content !== null) {
return $this->content;
}
$this->content = new StdClass;
if (@$this->config->inblocklayout) {
$this->content->text = $renderer->render_dashboard($this);
} else {
$viewdashboardstr = get_string('viewdashboard', 'block_dashboard');
$params = array('id' => $COURSE->id, 'blockid' => $this->instance->id);
$dashboardviewurl = new moodle_url('/blocks/dashboard/view.php', $params);
$this->content->text = '<a href="'.$dashboardviewurl.'">'.$viewdashboardstr.'</a>';
}
if (has_capability('block/dashboard:configure', $context) && $PAGE->user_is_editing()) {
$params = array();
$params['id'] = $COURSE->id;
$params['instance'] = $this->instance->id;
$options['href'] = new moodle_url('/blocks/dashboard/setup.php', $params);
$options['class'] = 'smalltext';
$editlink = html_writer::tag('a', get_string('configure', 'block_dashboard'), $options);
$this->content->footer = $editlink;
} else {
$this->content->footer = '';
}
return $this->content;
}
function content_is_trusted() {
global $SCRIPT;
if (!$context = context::instance_by_id($this->instance->parentcontextid, IGNORE_MISSING)) {
return false;
}
//find out if this block is on the profile page
if ($context->contextlevel == CONTEXT_USER) {
if ($SCRIPT === '/my/index.php') {
// this is exception - page is completely private, nobody else may see content there
// that is why we allow JS here
return true;
} else {
// no JS on public personal pages, it would be a big security issue
return false;
}
}
return true;
}
/**
* build a graph descriptor, taking some defaults decisions
*
*/
public function dashboard_graph_properties() {
$jqplot = array();
$yserieslabels = array_values($this->yseries);
$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');
}
} else if ($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';
}
} else if ($this->config->graphtype == 'pie') {
$jqplot = array(
'seriesDefaults' => array(
'renderer' => '$.jqplot.PieRenderer',
'rendererOptions' => array(
'padding' => 2,
'sliceMargin' => 2,
'showDataLabels' => true
),
),
'cursor' => array(
'useAxesFormatters' => false,
'show' => false,
),
'highlighter' => array(
'useAxesFormatters' => false,
),
);
} else if ($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,
),
);
} else if ($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');
}
} else if ($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
*/
public function protect($sql) {
$sql = preg_replace('/\b(UPDATE|ALTER|DELETE|INSERT|DROP|CREATE|GRANT)\b/i', '', $sql);
$sql = preg_replace('/;/', '', $sql);
return $sql;
}
/**
*
*
*/
public function get_count_records_sql($sql) {
$sql = "
SELECT
COUNT(*)
FROM
($sql) as fullrecs
";
return $sql;
}
/**
* provides constraint values from filters
*
*/
public function filter_get_results($fielddef, $fieldname, $specialvalue = '', $forcereload = false, &$printoutbuffer = null) {
static $FILTERSET;
global $CFG, $DB, $PAGE;
$config = get_config('block_dashboard');
$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);
$this->filteredsql = $filtersql;
// Filter values return from cache.
if (isset($FILTERSET) && array_key_exists($fielddef, $FILTERSET) && empty($specialvalue)) {
if (!empty($this->config->showfilterqueries)) {
if (!is_null($printoutbuffer)) {
$printoutbuffer .= '<div class="dashboard-filter-query"><b>STATIC CACHED DATA FILTER :</b> '.$filtersql.'</div>';
}
}
return $FILTERSET[$fielddef];
}
// Check DB cache.
$sqlkey = md5($filtersql);
if (@$this->config->showbenches) {
$bench = new StdClass;
$bench->name = 'Filter cache prefetch '.$fielddef;
$bench->start = time();
}
$params = array('querykey' => $sqlkey, 'access' => $this->config->target);
$cachefootprint = $DB->get_record('block_dashboard_filter_cache', $params);
if (@$this->config->showbenches) {
$bench->end = time();
$this->benches[] = $bench;
}
if (empty($this->config->cachingttl)) {
$this->config->cachingttl = 0;
}
if ((!$PAGE->user_is_editing() ||
!@$config->enable_isediting_security) &&
(!@$this->config->uselocalcaching ||
!$cachefootprint ||
($cachefootprint &&
$cachefootprint->timereloaded < time() - $this->config->cachingttl * 60) ||
$forcereload)) {
$params = array('querykey' => $sqlkey, 'access' => $this->config->target);
try {
$DB->delete_records('block_dashboard_filter_cache', $params);
} catch (Exception $e) {
throw new \block_dashboard\filter_query_cache_exception($DB->get_last_error());
}
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();
}
try {
$FILTERSET[$fielddef] = $DB->get_records_sql($filtersql);
} catch (Exception $e) {
throw new \block_dashboard\filter_query_exception($DB->get_last_error());
}
if (@$this->config->showbenches) {
$bench->end = time();
$this->benches[] = $bench;
}
} else {
if (!isediting() || empty($config->enable_isediting_security)) {
try {
$FILTERSET[$fielddef] = extra_db_query($filtersql, false, true, $error);
} catch (Exception $e) {
throw new \block_dashboard\filter_query_exception($DB->get_last_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);
}
if (!empty($this->config->showfilterqueries)) {
if (!is_null($printoutbuffer)) {
$printoutbuffer .= '<div class="dashboard-filter-query"><b>FILTER :</b> '.$filtersql.'</div>';
}
}
} else {
if ($cachefootprint) {
if ($tracing) {
mtrace('Getting filter data from cache');
}
list($usec, $sec) = explode(' ', microtime());
$t1 = (float)$usec + (float)$sec;
$FILTERSET[$fielddef] = unserialize(base64_decode($cachefootprint->filterrecord));
list($usec, $sec) = explode(' ', microtime());
$t2 = (float)$usec + (float)$sec;
} else {
$notretrievablestr = get_string('filternotretrievable', 'block_dashboard');
$this->content->text .= "<div class=\"dashboard-special\">$notretrievablestr</div>";
}
if (!empty($this->config->showfilterqueries)) {
if (!is_null($printoutbuffer)) {
$printoutbuffer .= '<div class="dashboard-filter-query"><b>DB CACHED FILTER :</b> '.$filtersql.'</div>';
}
}
}
$result = false;
if (is_array($FILTERSET[$fielddef])) {
switch ($specialvalue) {
case 'LAST':
$values = array_values($FILTERSET[$fielddef]);
$lastvalue = end($values);
if ($lastvalue) {
$result = $lastvalue->$fieldname;
}
return $result;
case 'FIRST':
$values = array_values($FILTERSET[$fielddef]);
$firstvalue = reset($values);
if ($firstvalue) {
$result = $firstvalue->$fieldname ;
}
return $result;
default:
return $FILTERSET[$fielddef];
}
}
}
/**
* fetches data and applies a cache strategy if required
* The cache strategy will store complete "unlimited" results
* in a local table as serialized records. Only one data set is stored
* by SQL radical (i.e., removing LIMIT and OFFSET clauses
* LIMIT and OFFSET are applied to the local proxy.
* @param string $sql
* @param arrayref &$results
* @param int $limit
* @param int $offset
* @param bool $forcereload
* @param bool $tracing
*
* @return a string status as complementary info on the data
*/
public function fetch_dashboard_data($sql, &$results, $limit = '', $offset = '', $forcereload = false, $tracing = false) {
global $extra_db_CNX, $CFG, $DB, $PAGE;
$config = get_config('block_dashboard');
$sqlrad = preg_replace('/LIMIT.*/si', '', $sql);
$sqlkey = md5("$sql LIMIT $limit OFFSET $offset");
$cachefootprint = $DB->get_record('block_dashboard_cache', array('querykey' => $sqlkey));
$results = array();
/*
* we can get real data :
* Only if we are NOT editing => secures acces in case of bad strangled query
* If we have no cache footprint and are needing one (cache expired or using cache and having no footprint)
* If reload is forced
*/
if ((!$PAGE->user_is_editing() ||
!@$config->enable_isediting_security) &&
(!@$this->config->uselocalcaching ||
!$cachefootprint ||
($cachefootprint && $cachefootprint->timereloaded < time() - @$this->config->cachingttl * 60) ||
$forcereload)) {
$params = array('querykey' => $sqlkey, 'access' => $this->config->target);
$DB->delete_records('block_dashboard_cache', $params);
$DB->delete_records('block_dashboard_cache_data', $params);
list($usec, $sec) = explode(" ", microtime());
$t1 = (float)$usec + (float)$sec;
if ($this->config->target == 'moodle') {
return $this->get_moodle_results($sql, $results, $limit, $offset);
} else {
// This is a pro feature.
// TODO : enhance performance by using recordsets.
if (empty($extra_db_CNX)) {
extra_db_connect(false, $error);
}
if ($allresults = extra_db_query($sql, false, true, $error)) {
foreach ($allresults as $reckey => $rec) {
if (!empty($this->config->uselocalcaching)) {
$cacherec = new StdClass;
$cacherec->access = $this->config->target;
$cacherec->querykey = $sqlkey;
$cacherec->recordid = $reckey; // Get first column in result as key.
$cacherec->record = base64_encode(serialize($rec));
$DB->insert_record('block_dashboard_cache_data', str_replace("'", "''", $cacherec));
}
}
}
if ($error) {
return '<span class="error">'.$error.'</span>';
}
if (!empty($limit)) {
$sqlpaged = $sql.' LIMIT '.$limit.' OFFSET '.$offset;
$results = extra_db_query($sqlpaged, false, true, $error);
} else {
$results = $allresults;
}
if ($error) {
return '<span class="error">'.$error.'</span>';
}
}
if (!empty($this->config->uselocalcaching) && empty($error)) {
$timerec = new StdClass;
$timerec->access = $this->config->target;
$timerec->querykey = $sqlkey;
$timerec->timereloaded = time();
$DB->insert_record('block_dashboard_cache', $timerec);
}
list($usec, $sec) = explode(' ', microtime());
$t2 = (float)$usec + (float)$sec;
if (@$this->config->showbenches) {
$this->benches[] = $$t2 - $t1;
}
$this->add_param_output_cols($results);
} else {
if ($cachefootprint) {
$results = $this->get_data_from_cache($sqlkey, $limit, $offset);
$this->add_param_output_cols($results);
return '<div class="dashboard-special">'.get_string('cacheddata', 'block_dashboard').'</div>';
} else {
$notretrievablestr = get_string('notretrievable', 'block_dashboard');
return '<div class="dashboard-special">'.$notretrievablestr.'</div>';
}
}
}
/**
* Internally get results in the current moodle.
* @param string $sql
* @param arrayref $results
* @param int $limit
* @param int $offset
*/
protected function get_moodle_results($sql, &$results, $limit, $offset) {
global $DB;
$sqlkey = md5("$sql LIMIT $limit OFFSET $offset");
// Get all results for cache.
$allresults = array();
if (@$this->config->showbenches) {
$bench = new StdClass;
$bench->name = "main query";
$bench->start = time();
}
if (!empty($limit)) {
$sql = preg_replace('/LIMIT.*$/', '', $sql);
$sql .= " LIMIT $limit OFFSET $offset ";
}
if ($rs = $DB->get_recordset_sql($sql)) {
while ($rs->valid()) {
$rec = $rs->current();
$recarr = array_values((array)$rec);
$allresults[$recarr[0]] = $rec;
if (!empty($this->config->uselocalcaching)) {
$cacherec = new StdClass;
$cacherec->access = $this->config->target;
$cacherec->querykey = $sqlkey;
$cacherec->recordid = $recarr[0]; // Get first column in result as key.
$cacherec->record = base64_encode(serialize($rec));
$DB->insert_record('block_dashboard_cache_data', $cacherec);
}
$rs->next();
}
$rs->close();
} else {
$error = $DB->get_last_error();
if ($error) {
return '<span class="error">'.$error.'</span>';
}
}
if ($limit) {
if ($rs = $DB->get_recordset_sql($sql, $offset, $limit)) {
while ($rs->valid()) {
$rec = $rs->current();
$recarr = array_values((array)$rec);
$results[$recarr[0]] = $rec;
$rs->next();
}
$rs->close();
} else {
$error = $DB->get_last_error();
if ($error) {
return '<span class="error">'.$error.'</span>';
}
}
} else {
$results = $allresults;
}
if (@$this->config->showbenches) {
$bench->end = time();
$this->benches[] = $bench;
}
$this->add_param_output_cols($results);
}
/**
* Internally read from dashboard DB cache
*/
protected function get_data_from_cache($sqlkey, $limit, $offset) {
global $DB;
if (!isset($this->content)) {
$this->content = new StdClass;
$this->content->text = '';
}
$this->content->text .= '<div class="dashboard-special">Cache</div>';
list($usec, $sec) = explode(' ', microtime());
$t1 = (float)$usec + (float)$sec;
$rs = $DB->get_recordset('block_dashboard_cache_data', array('querykey' => $sqlkey), 'id', '*', $offset, $limit);
while ($rs->valid()) {
$rec = $rs->current();
$results[$rec->recordid] = unserialize(base64_decode($rec->record));
$rs->next();
}
$rs->close();
list($usec, $sec) = explode(' ', microtime());
$t2 = (float)$usec + (float)$sec;
if (@$this->config->showbenches) {
$this->benches[] = $$t2 - $t1;
}
return $results;
}
/**
* provides ability to defer cache update to croned delayed period.
*/
static public function crontask() {
global $CFG, $DB, $SITE, $PAGE;
$config = get_config('block_dashboard');
mtrace("\nDashboard cron...");
if ($alldashboards = $DB->get_records('block_instances', array('blockname' => 'dashboard'))) {
$dashtrace = "[".strftime('%Y-%m-%d %H:%M:%S', time())."] Processing dashboards\n";
foreach ($alldashboards as $dsh) {
$dashtrace .= "\tProcessing dashboard $dsh->id\n";
$instance = block_instance('dashboard', $dsh);
if (!$instance->prepare_config()) {
continue;
}
$context = context_block::instance($dsh->id);
if (empty($instance->config->cronmode) || (@$instance->config->cronmode == 'norefresh')) {
$dashtrace .= "\tNo cron programmed for $dsh->id\n";
mtrace("$dsh->id Skipping norefresh");
continue;
}
if (!@$instance->config->uselocalcaching) {
$dashtrace .= "\tOutputting in files needs caching being enabled\n";
mtrace("$dsh->id Skipping as not cached ");
continue;
}
$needscron = false;
if (@$instance->config->cronmode == 'global') {
$chour = 0 + @$config->cron_hour;
$cmin = 0 + @$config->cron_min;
$cfreq = @$config->cron_freq;
} else {
$chour = 0 + @$instance->config->cronhour;
$cmin = 0 + @$instance->config->cronmin;
$cfreq = @$instance->config->cronfrequency;
}
$now = time();
$nowdt = getdate($now);
$lastdate = getdate(0 + @$instance->config->lastcron);
$crondebug = optional_param('crondebug', false, PARAM_BOOL);
// First check we did'nt already refreshed it today (or a new year is starting).
if ($CFG->debug == DEBUG_DEVELOPER) {
mtrace("Day check : Now ".$nowdt['yday']." > Last ".$lastdate['yday'].' ');
}
if (($nowdt['yday'] > $lastdate['yday']) || ($lastdate['yday'] == 0) || $crondebug || ($nowdt['yday'] == 0)) {
// We wait the programmed time is passed, and check we are an allowed day to run and no query is already running.
if (($cfreq == 'daily') || ($nowdt['wday'] == $cfreq) || $crondebug || ($nowdt['yday'] == 0)) {
if (((($nowdt['hours'] * 60 + $nowdt['minutes']) >= ($chour * 60 + $cmin)) &&
!@$instance->config->isrunning) ||
$crondebug) {
$instance->config->isrunning = true;
$instance->config->lastcron = $now;
$newval = base64_encode(serialize($instance->config));
$DB->set_field('block_instances', 'configdata', $newval, array('id' => $dsh->id)); // Save config.
// Process data caching.
$limit = '';
$offset = '';
// TODO : compute correct values for $limit and $offset.
// We cannot here rely on any filtering or params given by the interactive GUI.
$sql = str_replace('<%%FILTERS%%>', '', $instance->config->query);
$sql = str_replace('<%%PARAMS%%>', '', $sql);
$logbuf = "\t ... refreshing for instance {$dsh->id} \n";
$status = $instance->fetch_dashboard_data($sql, $results, $limit, $offset, true, true /* with mtracing */);
if (empty($results)) {
$logbuf = "\tEmpty result on query : {$sql} \n";
$eventparams = array(
'context' => context_block::instance($dsh->id),
'other' => array(
'blockid' => $dsh->id
),
);
$event = \block_dashboard\event\export_task_empty::create($eventparams);
$event->trigger();
} else {
// Generate output file if required.
$logbuf = "\tOutputting file for instance {$dsh->id} \n";
$csvrenderer = $PAGE->get_renderer('block_dashboard', 'csv');
$csvrenderer->generate_output_file($instance, $results);
$eventparams = array(
'context' => context_block::instance($dsh->id),
'other' => array(
'blockid' => $dsh->id
),
);
$event = \block_dashboard\event\export_task_processed::create($eventparams);
$event->trigger();
}
// Ugly way to do it....
$blockconfig = unserialize(base64_decode($DB->get_field('block_instances', 'configdata', array('id' => $dsh->id))));
$blockconfig->isrunning = false;
$blockconfig->lastcron = time();
$DB->set_field('block_instances', 'configdata', base64_encode(serialize($blockconfig)), array('id' => $dsh->id)); // Save config
mtrace($logbuf);
$dashtrace .= $logbuf;
if (!empty($blockconfig->cronadminnotifications)) {
$admins = get_admins();
foreach ($admins as $admin) {
email_to_user($admin, $admin, $SITE->fullname.': Dashboard export task '.$dsh->id, '', '');
}
}
} else {
$msg = ' waiting for valid time for instance '.$dsh->id;
mtrace($msg);
$dashtrace .= "\t".$msg;
}
} else {
$msg = ' waiting for valid day for instance '.$dsh->id;
mtrace($msg);
$dashtrace .= "\t".$msg;
}
} else {
$msg = ' waiting for next unprocessed day for instance '.$dsh->id;
mtrace($msg);
$dashtrace .= "\t".$msg;
}
}
if (!empty($config->cron_trace_on)) {
if ($DASHTRACE = fopen($CFG->dataroot.'/dashboards.log', 'a')) {
fputs($DASHTRACE, $dashtrace);
fclose($DASHTRACE);
}
}
} else {
mtrace('no instances to process...');
}
return true;
}
/**
* Add some additional virtual columns from user params. Additional "fixed value" output cols
* may be defined as user params of 'outputcol' type. The param var key generates a new result column
* in the output result. This may be usefull to produce static/parametric fields in an output CSV file.
*
* The post processing occurs in @see block_dashboard::fetch_dashboard_data()
*
* @param arrayref &$results
* @return Void. the incomming results array is processed by reference.
*/
protected function add_param_output_cols(&$results) {
if (empty($results)) {
return;
}
$addedcolumns = array();
foreach ($this->params as $up) {
if ($up->paramas == 'outputcol') {
$addedcolumns[] = $up->key;
}
}
if (!empty($addedcolumns)) {
foreach ($results as $r) {
foreach ($addedcolumns as $key) {
$r->$key = $this->params[$key]->value;
}
}
}
}
/**
* determines if filter is global
* a global filter will be catched by all dashboard instances in the same page
*/
public function is_filter_global($filterkey) {
return strstr($this->filterfields->options[$filterkey], 'g') !== false;