Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ViewDataTable.php « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d063c7f08b8a656f72b251e440b202aa69a4e0dc (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik
 * @package Piwik
 */
namespace Piwik;

use Piwik\API\Request;
use Piwik\DataTable;
use Piwik\Period;
use Piwik\Period\Range;
use Piwik\Plugins\API\API;
use Piwik\ViewDataTable\Properties;
use Piwik\ViewDataTable\VisualizationPropertiesProxy;

/**
 * This class is used to load (from the API) and customize the output of a given DataTable.
 * The main() method will create an object implementing ViewInterface
 * You can customize the dataTable using the disable* methods.
 *
 * You can also customize the dataTable rendering using row metadata:
 * - 'html_label_prefix': If this metadata is present on a row, it's contents will be prepended
 *                        the label in the HTML output.
 * - 'html_label_suffix': If this metadata is present on a row, it's contents will be appended
 *                        after the label in the HTML output.
 *
 * Example:
 * In the Controller of the plugin VisitorInterest
 * <pre>
 *    function getNumberOfVisitsPerVisitDuration( $fetch = false)
 *  {
 *        $view = ViewDataTable::factory( 'cloud' );
 *        $view->init( $this->pluginName,  __FUNCTION__, 'VisitorInterest.getNumberOfVisitsPerVisitDuration' );
 *        $view->setColumnsToDisplay( array('label','nb_visits') );
 *        $view->disableSort();
 *        $view->disableExcludeLowPopulation();
 *        $view->disableOffsetInformation();
 *
 *        return $this->renderView($view, $fetch);
 *    }
 * </pre>
 *
 * @see \Piwik\ViewDataTable\Properties - for core DataTable display properties.
 * @see factory() for all the available output (cloud tags, html table, pie chart, vertical bar chart)
 * @package Piwik
 * @subpackage ViewDataTable
 */
class ViewDataTable
{
    /**
     * This event is called before a visualization is created. Plugins can use this event to
     * override view properties for individual reports or visualizations.
     * 
     * Themes can use this event to make sure reports look nice with their themes. Plugins
     * that provide new visualizations can use this event to make sure certain reports
     * are configured differently when viewed with the new visualization.
     * 
     * Callback Signature: function (ViewDataTable $view) {}
     */
    const CONFIGURE_VIEW_EVENT = 'ViewDataTable.configureReportView';

    /**
     * The class name of the visualization to use.
     * 
     * @var string|null
     */
    private $visualizationClass;

    /**
     * Cache for getAllReportDisplayProperties result.
     * 
     * @var array
     */
    public static $reportPropertiesCache = null;

    /**
     * Array of properties that are available in the view
     * Used to store UI properties, eg. "show_footer", "show_search", etc.
     *
     * @var array
     */
    protected $viewProperties = array();

    /**
     * If the current dataTable refers to a subDataTable (eg. keywordsBySearchEngineId for id=X) this variable is set to the Id
     *
     * @var bool|int
     */
    protected $idSubtable = false;

    /**
     * DataTable loaded from the API for this ViewDataTable.
     *
     * @var DataTable
     */
    protected $dataTable = null;

    /**
     * @see init()
     * @var string
     */
    protected $currentControllerAction;

    /**
     * @see init()
     * @var string
     */
    protected $currentControllerName;

    /**
     * This view should be an implementation of the Interface ViewInterface
     * The $view object should be created in the main() method.
     *
     * @var \Piwik\View\ViewInterface
     */
    protected $view = null;

    /**
     * Default constructor.
     */
    public function __construct($currentControllerAction,
                                $apiMethodToRequestDataTable,
                                $viewProperties = array(),
                                $visualizationId = null)
    {
        $visualizationClass = $visualizationId ? DataTableVisualization::getClassFromId($visualizationId) : null;
        $this->visualizationClass = $visualizationClass;

        list($currentControllerName, $currentControllerAction) = explode('.', $currentControllerAction);
        $this->currentControllerName = $currentControllerName;
        $this->currentControllerAction = $currentControllerAction;

        $this->viewProperties['visualization_properties'] = new VisualizationPropertiesProxy($visualizationClass);
        $this->viewProperties['metadata'] = array();
        $this->viewProperties['translations'] = array();
        $this->viewProperties['filters'] = array();
        $this->viewProperties['after_data_loaded_functions'] = array();
        $this->viewProperties['related_reports'] = array();
        $this->viewProperties['subtable_controller_action'] = $currentControllerAction;

        $this->setDefaultProperties();
        $this->setViewProperties($viewProperties);

        $this->idSubtable = Common::getRequestVar('idSubtable', false, 'int');
        $this->viewProperties['show_footer_icons'] = ($this->idSubtable == false);
        $this->viewProperties['apiMethodToRequestDataTable'] = $apiMethodToRequestDataTable;

        $this->viewProperties['report_id'] = $currentControllerName . '.' . $currentControllerAction;
        $this->viewProperties['self_url'] = $this->getBaseReportUrl($currentControllerName, $currentControllerAction);

        // the exclude low population threshold value is sometimes obtained by requesting data.
        // to avoid issuing unecessary requests when display properties are determined by metadata,
        // we allow it to be a closure.
        if (isset($this->viewProperties['filter_excludelowpop_value'])
            && $this->viewProperties['filter_excludelowpop_value'] instanceof \Closure
        ) {
            $function = $this->viewProperties['filter_excludelowpop_value'];
            $this->viewProperties['filter_excludelowpop_value'] = $function();
        }

        $this->overrideViewPropertiesWithQueryParams();

        $this->loadDocumentation();
    }

    /**
     * Returns the API method that will be called to obatin the report data.
     * 
     * @return string e.g. 'Actions.getPageUrls'
     */
    public function getReportApiMethod()
    {
        return $this->viewProperties['apiMethodToRequestDataTable'];
    }

    /**
     * Returns the view's associated visualization class name.
     * 
     * @return string
     */
    public function getVisualizationClass()
    {
        return $this->visualizationClass;
    }

    /**
     * Gets a view property by reference.
     * 
     * @param string $name A valid view property name. @see Properties for all
     *                     valid view properties.
     * @return mixed
     * @throws \Exception if the property name is invalid.
     */
    public function &__get($name)
    {
        Properties::checkValidPropertyName($name);
        return $this->viewProperties[$name];
    }

    /**
     * Sets a view property.
     * 
     * @param string $name A valid view property name. @see Properties for all
     *                     valid view properties.
     * @param mixed $value
     * @return mixed Returns $value.
     * @throws \Exception if the property name is invalid.
     */
    public function __set($name, $value)
    {
        Properties::checkValidPropertyName($name);
        return $this->viewProperties[$name] = $value;
    }

    /**
     * Hack to allow property access in Twig (w/ property name checking).
     */
    public function __call($name, $arguments)
    {
        return $this->$name;
    }

    /**
     * Unique string ID that defines the format of the dataTable, eg. "pieChart", "table", etc.
     *
     * @return string
     */
    public function getViewDataTableId()
    {
        $klass = $this->visualizationClass;
        return $klass::getViewDataTableId($this);
    }

    /**
     * Returns a Piwik_ViewDataTable_* object.
     * By default it will return a ViewDataTable_Html
     * If there is a viewDataTable parameter in the URL, a ViewDataTable of this 'viewDataTable' type will be returned.
     * If defaultType is specified and if there is no 'viewDataTable' in the URL, a ViewDataTable of this $defaultType will be returned.
     * If force is set to true, a ViewDataTable of the $defaultType will be returned in all cases.
     *
     * @param string      $defaultType Any of these: table, cloud, graphPie, graphVerticalBar, graphEvolution, sparkline, generateDataChart*
     * @param string|bool $apiAction
     * @param string|bool $controllerAction
     * @param bool        $forceDefault
     *
     * @return ViewDataTable
     */
    static public function factory($defaultType = null, $apiAction = false, $controllerAction = false, $forceDefault = false)
    {
        if ($controllerAction === false) {
            $controllerAction = $apiAction;
        }

        $defaultProperties = self::getDefaultPropertiesForReport($apiAction);
        if (!empty($defaultProperties['default_view_type'])
            && !$forceDefault
        ) {
            $defaultType = $defaultProperties['default_view_type'];
        }

        $type = Common::getRequestVar('viewDataTable', $defaultType ?: 'table', 'string');

        if ($type == 'sparkline') {
            $result = new ViewDataTable\Sparkline($controllerAction, $apiAction, $defaultProperties);
        } else {
            $result = new ViewDataTable($controllerAction, $apiAction, $defaultProperties, $type);
        }

        return $result;
    }

    /**
     * Returns the list of view properties that should be sent with the HTML response
     * as JSON. These properties are visible to the UI JavaScript, but are not passed
     * with every request.
     *
     * @return array
     */
    public function getClientSideProperties()
    {
        return $this->getPropertyNameListWithMetaProperty(Properties::$clientSideProperties, __FUNCTION__);
    }

    /**
     * Returns the list of view properties that should be sent with the HTML response
     * and resent by the UI JavaScript in every subsequent AJAX request.
     *
     * @return array
     */
    public function getClientSideParameters()
    {
        return $this->getPropertyNameListWithMetaProperty(Properties::$clientSideParameters, __FUNCTION__);
    }

    /**
     * Returns the list of view properties that can be overriden by query parameters.
     * 
     * @return array
     */
    public function getOverridableProperties()
    {
        return $this->getPropertyNameListWithMetaProperty(Properties::$overridableProperties, __FUNCTION__);
    }

    public function getCurrentControllerAction()
    {
        return $this->currentControllerAction;
    }

    public function getCurrentControllerName()
    {
        return $this->currentControllerName;
    }

    /**
     * Returns the DataTable loaded from the API
     *
     * @return DataTable
     * @throws \Exception if not yet defined
     */
    public function getDataTable()
    {
        if (is_null($this->dataTable)) {
            throw new \Exception("The DataTable object has not yet been created");
        }
        return $this->dataTable;
    }

    /**
     * To prevent calling an API multiple times, the DataTable can be set directly.
     * It won't be loaded again from the API in this case
     *
     * @param $dataTable
     * @return void $dataTable DataTable
     */
    public function setDataTable($dataTable)
    {
        $this->dataTable = $dataTable;
    }

    /**
     * Returns the defaut view properties for a report, if any.
     *
     * Plugins can associate callbacks with the ViewDataTable.getReportDisplayProperties
     * event to set the default properties of reports.
     *
     * @param string $apiAction
     * @return array
     */
    private static function getDefaultPropertiesForReport($apiAction)
    {
        $reportDisplayProperties = self::getAllReportDisplayProperties();
        return isset($reportDisplayProperties[$apiAction]) ? $reportDisplayProperties[$apiAction] : array();
    }

    /**
     * Returns the list of display properties for all available reports.
     * 
     * @return array
     */
    private static function getAllReportDisplayProperties()
    {
        if (self::$reportPropertiesCache === null) {
            self::$reportPropertiesCache = array();
            Piwik_PostEvent('ViewDataTable.getReportDisplayProperties', array(&self::$reportPropertiesCache));
        }

        return self::$reportPropertiesCache;
    }

    /**
     * Sets a view property by name. This function handles special view properties
     * like 'translations' & 'related_reports' that store arrays.
     *
     * @param string $name
     * @param mixed $value For array properties, $value can be a comma separated string.
     * @throws \Exception
     */
    private function setViewProperty($name, $value)
    {
        if (isset($this->viewProperties[$name])
            && is_array($this->viewProperties[$name])
            && is_string($value)
        ) {
            $value = Piwik::getArrayFromApiParameter($value);
        }

        if ($name == 'translations'
            || $name == 'filters'
            || $name == 'after_data_loaded_functions'
        ) {
            $this->viewProperties[$name] = array_merge($this->viewProperties[$name], $value);
        } else if ($name == 'related_reports') { // TODO: should process after (in overrideViewProperties)
            $this->addRelatedReports($value);
        } else if ($name == 'visualization_properties') {
            $this->setVisualizationPropertiesFromMetadata($value);
        } else if (Properties::isCoreViewProperty($name)) {
            $this->viewProperties[$name] = $value;
        } else {
            $report = $this->currentControllerName . '.' . $this->currentControllerAction;
            throw new \Exception("Invalid view property '$name' specified in view property metadata for '$report'.");
        }
    }

    /**
     * Sets visualization properties using data in a visualization's default property values
     * array.
     */
    private function setVisualizationPropertiesFromMetadata($properties)
    {
        if ($this->visualizationClass === null) {
            return null;
        }

        $visualizationIds = DataTableVisualization::getVisualizationIdsWithInheritance($this->visualizationClass);
        foreach ($visualizationIds as $visualizationId) {
            if (empty($properties[$visualizationId])) {
                continue;
            }

            foreach ($properties[$visualizationId] as $key => $value) {
                if (Properties::isCoreViewProperty($key)) {
                    $this->viewProperties[$key] = $value;
                } else {
                    $this->viewProperties['visualization_properties']->$key = $value;
                }
            }
        }
    }

    /**
     * Function called by the ViewDataTable objects in order to fetch data from the API.
     * The function init() must have been called before, so that the object knows which API module and action to call.
     * It builds the API request string and uses Request to call the API.
     * The requested DataTable object is stored in $this->dataTable.
     */
    protected function loadDataTableFromAPI()
    {
        if (!is_null($this->dataTable)) {
            // data table is already there
            // this happens when setDataTable has been used
            return;
        }

        // we build the request (URL) to call the API
        $requestArray = $this->getRequestArray();

        // we make the request to the API
        $request = new Request($requestArray);

        // and get the DataTable structure
        $dataTable = $request->process();

        $this->dataTable = $dataTable;
    }

    /**
     * Checks that the API returned a normal DataTable (as opposed to DataTable_Array)
     * @throws \Exception
     * @return void
     */
    protected function checkStandardDataTable()
    {
        Piwik::checkObjectTypeIs($this->dataTable, array('\Piwik\DataTable'));
    }

    private function getFiltersToRun()
    {
        $priorityFilters = array();
        $presentationFilters = array();

        foreach ($this->viewProperties['filters'] as $filterInfo) {
            if ($filterInfo instanceof \Closure) {
                $nameOrClosure = $filterInfo;
                $parameters = array();
                $priority = false;
            } else {
                @list($nameOrClosure, $parameters, $priority) = $filterInfo;
            }

            if ($nameOrClosure instanceof \Closure) {
                $parameters[] = $this;
            }

            if ($priority) {
                $priorityFilters[] = array($nameOrClosure, $parameters);
            } else {
                $presentationFilters[] = array($nameOrClosure, $parameters);
            }
        }

        return array($priorityFilters, $presentationFilters);
    }

    /**
     * Hook called after the dataTable has been loaded from the API
     * Can be used to add, delete or modify the data freshly loaded
     *
     * @return bool
     */
    protected function postDataTableLoadedFromAPI()
    {
        $columns = $this->dataTable->getColumns();
        $haveNbVisits = in_array('nb_visits', $columns);
        $haveNbUniqVisitors = in_array('nb_uniq_visitors', $columns);

        // default columns_to_display to label, nb_uniq_visitors/nb_visits if those columns exist in the
        // dataset. otherwise, default to all columns in dataset.
        if (empty($this->viewProperties['columns_to_display'])) {
            if ($haveNbVisits
                || $haveNbUniqVisitors
            ) {
                $columnsToDisplay = array('label');
                
                // if unique visitors data is available, show it, otherwise just visits
                if ($haveNbUniqVisitors) {
                    $columnsToDisplay[] = 'nb_uniq_visitors';
                } else {
                    $columnsToDisplay[] = 'nb_visits';
                }
            } else {
                $columnsToDisplay = $columns;
            }

            $this->viewProperties['columns_to_display'] = array_filter($columnsToDisplay);
        }

        $this->removeEmptyColumnsFromDisplay();

        // default sort order to visits/visitors data
        if (empty($this->viewProperties['filter_sort_column'])) {
            if ($haveNbUniqVisitors
                && in_array('nb_uniq_visitors', $this->viewProperties['columns_to_display'])
            ) {
                $this->viewProperties['filter_sort_column'] = 'nb_uniq_visitors';
            } else {
                $this->viewProperties['filter_sort_column'] = 'nb_visits';
            }
            $this->viewProperties['filter_sort_order'] = 'desc';
        }

        // deal w/ table metadata
        if ($this->dataTable instanceof DataTable) {
            $this->viewProperties['metadata'] = $this->dataTable->getAllTableMetadata();

            if (isset($this->viewProperties['metadata'][DataTable::ARCHIVED_DATE_METADATA_NAME])) {
                $this->viewProperties['metadata'][DataTable::ARCHIVED_DATE_METADATA_NAME] =
                    $this->makePrettyArchivedOnText();
            }
        }

        list($priorityFilters, $otherFilters) = $this->getFiltersToRun();

        // First, filters that delete rows
        foreach ($priorityFilters as $filter) {
            $this->dataTable->filter($filter[0], $filter[1]);
        }

        if (!$this->areGenericFiltersDisabled()) {
            // Second, generic filters (Sort, Limit, Replace Column Names, etc.)
            $requestArray = $this->getRequestArray();
            $request = Request::getRequestArrayFromString($requestArray);

            if ($this->viewProperties['enable_sort'] === false) {
                $request['filter_sort_column'] = $request['filter_sort_order'] = '';
            }

            $genericFilter = new \Piwik\API\DataTableGenericFilter($request);
            $genericFilter->filter($this->dataTable);
        }

        // Finally, apply datatable filters that were queued (should be 'presentation' filters that
        // do not affect the number of rows)
        if (!$this->areQueuedFiltersDisabled()) {
            $this->applyQueuedFilters();

            foreach ($otherFilters as $filter) {
                $this->dataTable->filter($filter[0], $filter[1]);
            }
        }

        return true;
    }

    /**
     * Returns true if generic filters have been disabled, false if otherwise.
     *
     * @return bool
     */
    private function areGenericFiltersDisabled()
    {
        // if disable_generic_filters query param is set to '1', generic filters are disabled
        if (Common::getRequestVar('disable_generic_filters', '0', 'string') == 1) {
            return true;
        }

        // if $this->disableGenericFilters() was called, generic filters are disabled
        if (isset($this->viewProperties['disable_generic_filters'])
            && $this->viewProperties['disable_generic_filters'] === true
        ) {
            return true;
        }

        return false;
    }

    /**
     * Returns true if queued filters have been disabled, false if otherwise.
     *
     * @return bool
     */
    private function areQueuedFiltersDisabled()
    {
        return isset($this->viewProperties['disable_queued_filters'])
            && $this->viewProperties['disable_queued_filters'];
    }

    /**
     * Returns prettified and translated text that describes when a report was last updated.
     *
     * @return string
     */
    private function makePrettyArchivedOnText()
    {
        $dateText = $this->viewProperties['metadata'][DataTable::ARCHIVED_DATE_METADATA_NAME];
        $date = Date::factory($dateText);
        $today = mktime(0, 0, 0);
        if ($date->getTimestamp() > $today) {
            $elapsedSeconds = time() - $date->getTimestamp();
            $timeAgo = MetricsFormatter::getPrettyTimeFromSeconds($elapsedSeconds);

            return Piwik_Translate('CoreHome_ReportGeneratedXAgo', $timeAgo);
        }

        $prettyDate = $date->getLocalized("%longYear%, %longMonth% %day%") . $date->toString('S');
        return Piwik_Translate('CoreHome_ReportGeneratedOn', $prettyDate);
    }

    /**
     * @return string URL to call the API, eg. "method=Referers.getKeywords&period=day&date=yesterday"...
     */
    protected function getRequestArray()
    {
        // we prepare the array to give to the API Request
        // we setup the method and format variable
        // - we request the method to call to get this specific DataTable
        // - the format = original specifies that we want to get the original DataTable structure itself, not rendered
        $requestArray = array(
            'method'                  => $this->viewProperties['apiMethodToRequestDataTable'],
            'format'                  => 'original',
            'disable_generic_filters' => Common::getRequestVar('disable_generic_filters', 1, 'int'),
            'disable_queued_filters'  => Common::getRequestVar('disable_queued_filters', 1, 'int')
        );

        $toSetEventually = array(
            'filter_limit',
            'keep_summary_row',
            'filter_sort_column',
            'filter_sort_order',
            'filter_excludelowpop',
            'filter_excludelowpop_value',
            'filter_column',
            'filter_pattern',
        );

        foreach ($toSetEventually as $varToSet) {
            $value = $this->getDefaultOrCurrent($varToSet);
            if (false !== $value) {
                $requestArray[$varToSet] = $value;
            }
        }
        
        $segment = Request::getRawSegmentFromRequest();
        if(!empty($segment)) {
            $requestArray['segment'] = $segment;
        }

        if (self::shouldLoadExpanded()) {
            $requestArray['expanded'] = 1;
        }

        $requestArray = array_merge($requestArray, $this->request_parameters_to_modify);

        if (!empty($requestArray['filter_limit'])
            && $requestArray['filter_limit'] === 0
        ) {
            unset($requestArray['filter_limit']);
        }

        return $requestArray;
    }

    /**
     * This functions reads the customization values for the DataTable and returns an array (name,value) to be printed in Javascript.
     * This array defines things such as:
     * - name of the module & action to call to request data for this table
     * - optional filters information, eg. filter_limit and filter_offset
     * - etc.
     *
     * The values are loaded:
     * - from the generic filters that are applied by default @see Piwik_API_DataTableGenericFilter.php::getGenericFiltersInformation()
     * - from the values already available in the GET array
     * - from the values set using methods from this class (eg. setSearchPattern(), setLimit(), etc.)
     *
     * @return array eg. array('show_offset_information' => 0, 'show_...
     */
    protected function getJavascriptVariablesToSet()
    {
        // build javascript variables to set
        $javascriptVariablesToSet = array();

        foreach ($this->viewProperties['custom_parameters'] as $name => $value) {
            $javascriptVariablesToSet[$name] = $value;
        }

        foreach ($_GET as $name => $value) {
            try {
                $requestValue = Common::getRequestVar($name);
            } catch (\Exception $e) {
                $requestValue = '';
            }
            $javascriptVariablesToSet[$name] = $requestValue;
        }

        foreach ($this->getClientSideParameters() as $name) {
            if (!isset($javascriptVariablesToSet[$name])) {
                if (isset($this->viewProperties[$name])
                    && $this->viewProperties[$name] !== false
                ) {
                    $javascriptVariablesToSet[$name] = $this->convertForJson($this->viewProperties[$name]);
                } else if (Properties::isValidVisualizationProperty($this->visualizationClass, $name)) {
                    $javascriptVariablesToSet[$name] =
                        $this->convertForJson($this->viewProperties['visualization_properties']->$name);
                }
            }
        }

        if ($this->dataTable instanceof DataTable) {
            // we override the filter_sort_column with the column used for sorting,
            // which can be different from the one specified (eg. if the column doesn't exist)
            $javascriptVariablesToSet['filter_sort_column'] = $this->dataTable->getSortedByColumnName();
            // datatable can return "2" but we want to write "nb_visits" in the js
            if (isset(Metrics::$mappingFromIdToName[$javascriptVariablesToSet['filter_sort_column']])) {
                $javascriptVariablesToSet['filter_sort_column'] = Metrics::$mappingFromIdToName[$javascriptVariablesToSet['filter_sort_column']];
            }
        }

        $javascriptVariablesToSet['module'] = $this->currentControllerName;
        $javascriptVariablesToSet['action'] = $this->currentControllerAction;
        if (!isset($javascriptVariablesToSet['viewDataTable'])) {
            $javascriptVariablesToSet['viewDataTable'] = $this->getViewDataTableId();
        }

        if ($this->dataTable &&
            // Set doesn't have the method
            !($this->dataTable instanceof DataTable\Map)
            && empty($javascriptVariablesToSet['totalRows'])
        ) {
            $javascriptVariablesToSet['totalRows'] = $this->dataTable->getRowsCountBeforeLimitFilter();
        }

        // we escape the values that will be displayed in the javascript footer of each datatable
        // to make sure there is no malicious code injected (the value are already htmlspecialchar'ed as they
        // are loaded with Common::getRequestVar()
        foreach ($javascriptVariablesToSet as &$value) {
            if (is_array($value)) {
                $value = array_map('addslashes', $value);
            } else {
                $value = addslashes($value);
            }
        }

        $deleteFromJavascriptVariables = array(
            'filter_excludelowpop',
            'filter_excludelowpop_value',
        );
        foreach ($deleteFromJavascriptVariables as $name) {
            if (isset($javascriptVariablesToSet[$name])) {
                unset($javascriptVariablesToSet[$name]);
            }
        }

        $rawSegment = Request::getRawSegmentFromRequest();
        if(!empty($rawSegment)) {
            $javascriptVariablesToSet['segment'] = $rawSegment;
        }

        return $javascriptVariablesToSet;
    }

    /**
     * Returns array of properties that should be visible to client side JavaScript. The data
     * will be available in the data-props HTML attribute of the .dataTable div.
     * 
     * @return array Maps property names w/ property values.
     */
    private function getClientSidePropertiesToSet()
    {
        $result = array();
        foreach ($this->getClientSideProperties() as $name) {
            if (isset($this->viewProperties[$name])) {
                $result[$name] = $this->convertForJson($this->viewProperties[$name]);
            } else if (Properties::isValidVisualizationProperty($this->visualizationClass, $name)) {
                $result[$name] = $this->convertForJson($this->viewProperties['visualization_properties']->$name);
            }
        }
        return $result;
    }

    /**
     * Returns, for a given parameter, the value of this parameter in the REQUEST array.
     * If not set, returns the default value for this parameter @see getDefault()
     *
     * @param string $nameVar
     * @return string|mixed Value of this parameter
     */
    protected function getDefaultOrCurrent($nameVar)
    {
        if (isset($_GET[$nameVar])) {
            return Common::sanitizeInputValue($_GET[$nameVar]);
        }
        $default = $this->getDefault($nameVar);
        return $default;
    }

    /**
     * Returns the default value for a given parameter.
     * For example, these default values can be set using the disable* methods.
     *
     * @param string $nameVar
     * @return mixed
     */
    protected function getDefault($nameVar)
    {
        if (!isset($this->viewProperties[$nameVar])) {
            return false;
        }
        return $this->viewProperties[$nameVar];
    }

    /** Load documentation from the API */
    private function loadDocumentation()
    {
        $this->viewProperties['metrics_documentation'] = array();

        $report = API::getInstance()->getMetadata(0, $this->currentControllerName, $this->currentControllerAction);
        $report = $report[0];

        if (isset($report['metricsDocumentation'])) {
            $this->viewProperties['metrics_documentation'] = $report['metricsDocumentation'];
        }

        if (isset($report['documentation'])) {
            $this->viewProperties['documentation'] = $report['documentation'];
        }
    }

    private function removeEmptyColumnsFromDisplay()
    {
        if (empty($this->dataTable)) {
            return;
        }
        if ($this->dataTable instanceof DataTable\Map) {
            $emptyColumns = $this->dataTable->getMetadataIntersectArray(DataTable::EMPTY_COLUMNS_METADATA_NAME);
        } else {
            $emptyColumns = $this->dataTable->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME);
        }
        if (is_array($emptyColumns)) {
            foreach ($emptyColumns as $emptyColumn) {
                $key = array_search($emptyColumn, $this->viewProperties['columns_to_display']);
                if ($key !== false) {
                    unset($this->viewProperties['columns_to_display'][$key]);
                }
            }
            $this->viewProperties['columns_to_display'] = array_values($this->viewProperties['columns_to_display']);
        }
    }

    private function addRelatedReport($module, $action, $title, $queryParams = array())
    {
        // don't add the related report if it references this report
        if ($this->currentControllerName == $module && $this->currentControllerAction == $action) {
            return;
        }

        $url = $this->getBaseReportUrl($module, $action, $queryParams);
        $this->viewProperties['related_reports'][$url] = $title;
    }

    private function addRelatedReports($relatedReports)
    {
        foreach ($relatedReports as $report => $title) {
            list($module, $action) = explode('.', $report);
            $this->addRelatedReport($module, $action, $title);
        }
    }

    /**
     * Returns true if it is likely that the data for this report has been purged and if the
     * user should be told about that.
     *
     * In order for this function to return true, the following must also be true:
     * - The data table for this report must either be empty or not have been fetched.
     * - The period of this report is not a multiple period.
     * - The date of this report must be older than the delete_reports_older_than config option.
     * @return bool
     */
    public function hasReportBeenPurged()
    {
        $strPeriod = Common::getRequestVar('period', false);
        $strDate = Common::getRequestVar('date', false);

        if ($strPeriod !== false
            && $strDate !== false
            && (is_null($this->dataTable)
                || (!empty($this->dataTable) && $this->dataTable->getRowsCount() == 0))) {
            // if range, only look at the first date
            if ($strPeriod == 'range') {
                $idSite = Common::getRequestVar('idSite', '');
                if (intval($idSite) != 0) {
                    $site = new Site($idSite);
                    $timezone = $site->getTimezone();
                } else {
                    $timezone = 'UTC';
                }

                $period = new Range('range', $strDate, $timezone);
                $reportDate = $period->getDateStart();
            } // if a multiple period, this function is irrelevant
            else if (Period::isMultiplePeriod($strDate, $strPeriod)) {
                return false;
            } // otherwise, use the date as given
            else {
                $reportDate = Date::factory($strDate);
            }

            $reportYear = $reportDate->toString('Y');
            $reportMonth = $reportDate->toString('m');

            if (PluginsManager::getInstance()->isPluginActivated('PrivacyManager')
                && Plugins\PrivacyManager\PrivacyManager::shouldReportBePurged($reportYear, $reportMonth)
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns URL for this report w/o any filter parameters.
     *
     * @param string $module
     * @param string $action
     * @param array $queryParams
     * @return string
     */
    private function getBaseReportUrl($module, $action, $queryParams = array())
    {
        $params = array_merge($queryParams, array('module' => $module, 'action' => $action));
        return Request::getCurrentUrlWithoutGenericFilters($params);
    }

    /**
     * Convenience method that creates and renders a ViewDataTable for a API method.
     *
     * @param string $pluginName The name of the plugin (eg, UserSettings).
     * @param string $apiAction The name of the API action (eg, getResolution).
     * @param bool $fetch If true, the result is returned, if false it is echo'd.
     * @throws \Exception
     * @return string|null See $fetch.
     */
    static public function renderReport($pluginName, $apiAction, $fetch = true)
    {
        $namespacedApiClassName = "\\Piwik\\Plugins\\$pluginName\\API";
        if (!method_exists($namespacedApiClassName::getInstance(), $apiAction)) {
            throw new \Exception("$namespacedApiClassName Invalid action name '$apiAction' for '$pluginName' plugin.");
        }
        
        $view = self::factory(null, $pluginName.'.'.$apiAction);
        $rendered = $view->render();
        
        if ($fetch) {
            return $rendered;
        } else {
            echo $rendered;
        }
    }

    /**
     * Convenience function. Calls main() & renders the view that gets built.
     * 
     * @return string The result of rendering.
     */
    public function render()
    {
        $this->buildView();
        return $this->view->render();
    }
    
    /**
     * Returns whether the DataTable result will have to be expanded for the
     * current request before rendering.
     *
     * @return bool
     */
    public static function shouldLoadExpanded()
    {
        // if filter_column_recursive & filter_pattern_recursive are supplied, and flat isn't supplied
        // we have to load all the child subtables.
        return Common::getRequestVar('filter_column_recursive', false) !== false
            && Common::getRequestVar('filter_pattern_recursive', false) !== false
            && Common::getRequestVar('flat', false) === false;
    }

    protected function overrideViewProperties()
    {
        if (!PluginsManager::getInstance()->isPluginActivated('Goals')) {
            $this->viewProperties['show_goals'] = false;
        }
    }

    protected function buildView()
    {
        Piwik_PostEvent(self::CONFIGURE_VIEW_EVENT, array($this));

        $visualization = new $this->visualizationClass($this);
        $this->overrideViewProperties();

        try {
            $this->loadDataTableFromAPI();
            $this->postDataTableLoadedFromAPI();
            $this->executeAfterDataLoadedCallbacks();
        } catch (NoAccessException $e) {
            throw $e;
        } catch (\Exception $e) {
            Piwik::log("Failed to get data from API: " . $e->getMessage());

            $loadingError = array('message' => $e->getMessage());
        }

        $template = $this->viewProperties['datatable_template'];
        $view = new View($template);

        if (!empty($loadingError)) {
            $view->error = $loadingError;
        }

        $view->visualization = $visualization;
        $view->visualizationCssClass = $this->getDefaultDataTableCssClass();

        if (!$this->dataTable === null) {
            $view->dataTable = null;
        } else {
            // TODO: this hook seems inappropriate. should be able to find data that is requested for (by site/date) and check if that
            //       has data.
            if (method_exists($visualization, 'isThereDataToDisplay')) {
                $view->dataTableHasNoData = !$visualization->isThereDataToDisplay($this->dataTable, $this);
            }

            $view->dataTable = $this->dataTable;

            // if it's likely that the report data for this data table has been purged,
            // set whether we should display a message to that effect.
            $view->showReportDataWasPurgedMessage = $this->hasReportBeenPurged();
            $view->deleteReportsOlderThan = Piwik_GetOption('delete_reports_older_than');
        }
        $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet();
        $view->clientSidePropertiesToSet = $this->getClientSidePropertiesToSet();
        $view->properties = $this->viewProperties; // TODO: should be $this. need to move non-view properties from the class
        $view->footerIcons = $this->getFooterIconsToShow();

        $this->view = $view;
    }

    private function executeAfterDataLoadedCallbacks()
    {
        foreach ($this->after_data_loaded_functions as $callback) {
            $callback($this->dataTable, $this);
        }
    }

    private function getFooterIconsToShow()
    {
        $result = array();

        // add normal view icons (eg, normal table, all columns, goals)
        $normalViewIcons = array(
            'class' => 'tableAllColumnsSwitch',
            'buttons' => array(),
        );

        if ($this->show_table) {
            $normalViewIcons['buttons'][] = array(
                'id' => 'table',
                'title' => Piwik_Translate('General_DisplaySimpleTable'),
                'icon' => 'plugins/Zeitgeist/images/table.png',
            );
        }

        if ($this->show_table_all_columns) {
            $normalViewIcons['buttons'][] = array(
                'id' => 'tableAllColumns',
                'title' => Piwik_Translate('General_DisplayTableWithMoreMetrics'),
                'icon' => 'plugins/Zeitgeist/images/table_more.png'
            );
        }

        if ($this->show_goals) {
            if (Common::getRequestVar('idGoal', false) == 'ecommerceOrder') {
                $icon = 'plugins/Zeitgeist/images/ecommerceOrder.gif';
            } else {
                $icon = 'plugins/Zeitgeist/images/goal.png';
            }
            
            $normalViewIcons['buttons'][] = array(
                'id' => 'tableGoals',
                'title' => Piwik_Translate('General_DisplayTableWithGoalMetrics'),
                'icon' => $icon
            );
        }

        if ($this->show_ecommerce) {
            $normalViewIcons['buttons'][] = array(
                'id' => 'ecommerceOrder',
                'title' => Piwik_Translate('General_EcommerceOrders'),
                'icon' => 'plugins/Zeitgeist/images/ecommerceOrder.gif',
                'text' => Piwik_Translate('General_EcommerceOrders')
            );

            $normalViewIcons['buttons'][] = array(
                'id' => 'ecommerceAbandonedCart',
                'title' => Piwik_Translate('General_AbandonedCarts'),
                'icon' => 'plugins/Zeitgeist/images/ecommerceAbandonedCart.gif',
                'text' => Piwik_Translate('General_AbandonedCarts')
            );
        }

        if (!empty($normalViewIcons['buttons'])) {
            $result[] = $normalViewIcons;
        }

        // add graph views
        $graphViewIcons = array(
            'class' => 'tableGraphViews tableGraphCollapsed',
            'buttons' => array(),
        );

        if ($this->show_all_views_icons) {
            if ($this->show_bar_chart) {
                $graphViewIcons['buttons'][] = array(
                    'id' => 'graphVerticalBar',
                    'title' => Piwik_Translate('General_VBarGraph'),
                    'icon' => 'plugins/Zeitgeist/images/chart_bar.png'
                );
            }

            if ($this->show_pie_chart) {
                $graphViewIcons['buttons'][] = array(
                    'id' => 'graphPie',
                    'title' => Piwik_Translate('General_Piechart'),
                    'icon' => 'plugins/Zeitgeist/images/chart_pie.png'
                );
            }

            if ($this->show_tag_cloud) {
                $graphViewIcons['buttons'][] = array(
                    'id' => 'cloud',
                    'title' => Piwik_Translate('General_TagCloud'),
                    'icon' => 'plugins/Zeitgeist/images/tagcloud.png'
                );
            }

            if ($this->show_non_core_visualizations) {
                $nonCoreVisualizations = DataTableVisualization::getNonCoreVisualizations();
                $nonCoreVisualizationInfo = DataTableVisualization::getVisualizationInfoFor($nonCoreVisualizations);

                foreach ($nonCoreVisualizationInfo as $format => $info) {
                    $graphViewIcons['buttons'][] = array(
                        'id' => $format,
                        'title' => Piwik_Translate($info['title']),
                        'icon' => $info['table_icon']
                    );
                }
            }
        }

        if (!empty($graphViewIcons['buttons'])) {
            $result[] = $graphViewIcons;
        }

        return $result;
    }

    public function getDefaultDataTableCssClass()
    {
        return 'dataTableViz' . Piwik::getUnnamespacedClassName($this->visualizationClass);
    }

    private function setViewProperties($values)
    {
        foreach ($values as $name => $value) {
            $this->setViewProperty($name, $value);
        }
    }

    private function setDefaultProperties()
    {
        // set core default properties
        $this->setViewProperties(Properties::getDefaultPropertyValues());

        // set visualization default properties
        if ($this->visualizationClass === null) {
            return;
        }

        $visualizationClass = $this->visualizationClass;
        $this->setViewProperties($visualizationClass::getDefaultPropertyValues());
    }

    private function convertForJson($value)
    {
        return is_bool($value) ? (int)$value : $value;
    }

    private function overrideViewPropertiesWithQueryParams()
    {
        $properties = $this->getOverridableProperties();
        foreach ($properties as $name) {
            if (Properties::isCoreViewProperty($name)) {
                $default = $this->viewProperties[$name];

                $this->viewProperties[$name] = $this->getPropertyFromQueryParam($name, $default);
            } else if (Properties::isValidVisualizationProperty($this->visualizationClass, $name)) {
                $default = $this->viewProperties['visualization_properties']->$name;

                $this->viewProperties['visualization_properties']->$name =
                    $this->getPropertyFromQueryParam($name, $default);
            }
        }
    }

    private function getPropertyFromQueryParam($name, $defaultValue)
    {
        $type = is_numeric($defaultValue) ? 'int' : null;
        return Common::getRequestVar($name, $defaultValue, $type);
    }

    /**
     * Helper function for getCliendSiteProperties/getClientSideParameters/etc.
     */
    private function getPropertyNameListWithMetaProperty($propertyNames, $getPropertiesFunctionName)
    {
        if ($this->visualizationClass) {
            $klass = $this->visualizationClass;
            $propertyNames = array_merge($propertyNames, $klass::$getPropertiesFunctionName());
        }
        return $propertyNames;
    }
}