Repository navigation
Expand file tree
/
Copy pathAPI.php
More file actions
1090 lines (952 loc) · 44.8 KB
/
Copy pathAPI.php
File metadata and controls
1090 lines (952 loc) · 44.8 KB
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
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
declare(strict_types=1);
namespace Piwik\Plugins\DataExplorer;
use Piwik\Access;
use Piwik\Archive\DataTableFactory;
use Piwik\Cache;
use Piwik\Category\CategoryList;
use Piwik\Category\Subcategory;
use Piwik\Common;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\DataTable;
use Piwik\Db;
use Piwik\NoAccessException;
use Piwik\Period;
use Piwik\Period\Factory as PeriodFactory;
use Piwik\Period\Range;
use Piwik\Piwik;
use Piwik\Plugin\Manager as PluginManager;
use Piwik\Plugins\DataExplorer\Access\ReportPermissions;
use Piwik\Plugins\DataExplorer\Catalog\DimensionCatalog;
use Piwik\Plugins\DataExplorer\Catalog\MetricCatalog;
use Piwik\Plugins\DataExplorer\Categories\ExploreSubcategory;
use Piwik\Plugins\DataExplorer\Categories\ManageSubcategory;
use Piwik\Plugins\DataExplorer\Dao\ReportsDao;
use Piwik\Plugins\DataExplorer\Model\Placement;
use Piwik\Plugins\DataExplorer\Model\ReportDefinition;
use Piwik\Plugins\DataExplorer\Query\FunnelQueryRunner;
use Piwik\Plugins\DataExplorer\Query\FunnelResult;
use Piwik\Plugins\DataExplorer\Query\PreviewTree;
use Piwik\Plugins\DataExplorer\Query\ProcessedMetrics;
use Piwik\Plugins\DataExplorer\Query\SavedReportReader;
use Piwik\Plugins\DataExplorer\Query\VisualQueryBuilder;
use Piwik\Plugins\DataExplorer\Query\CustomReportExport;
use Piwik\Plugins\DataExplorer\Query\CustomReportImport;
use Piwik\Plugins\DataExplorer\Query\VisualQueryRunner;
use Piwik\Plugins\DataExplorer\Reports\GetSavedReport;
use Piwik\Plugins\DataExplorer\Sql\ParsedQuery;
use Piwik\Plugins\DataExplorer\Sql\RawSqlRunner;
use Piwik\Plugins\DataExplorer\Sql\ReadOnlySetup;
use Piwik\Plugins\DataExplorer\Sql\RejectedQueryException;
use Piwik\Plugins\DataExplorer\Sql\SiteScopeProof;
use Piwik\Plugins\DataExplorer\Sql\SqlGuard;
use Piwik\Plugins\SegmentEditor\API as SegmentEditorAPI;
use Piwik\Plugins\SitesManager\API as SitesManagerAPI;
use Piwik\Segment;
use Piwik\Site;
/**
* API of the DataExplorer plugin.
*
* @method static API getInstance()
*/
class API extends \Piwik\Plugin\API
{
// pages of the plugin itself, never a place for a saved report
private const RESERVED_SUBCATEGORIES = [ExploreSubcategory::ID, ManageSubcategory::ID];
/**
* Dashboards and the Marketplace teaser use the reporting menu but are not report pages.
*/
private const NON_REPORTING_CATEGORIES = ['Dashboard_Dashboard', 'Marketplace_Marketplace'];
private const MAX_SUBCATEGORY_LENGTH = 255;
private const MAX_ORDER = 1000;
/** seconds a live exploration result serves the requests of the canvas data table */
private const PREVIEW_CACHE_TTL = 300;
/**
* Dimensions and metrics grouped by category (for the "+" pickers), the stored segments of the site and the
* limits of an exploration (row dimensions, metrics, column dimensions).
*
* @param int $idSite
* @return array{dimensions: array, metrics: array, segments: array, limits: array}
*/
public function getCatalog(int $idSite): array
{
(new ReportPermissions())->checkCanExplore($idSite);
$dimensions = [];
foreach ((new DimensionCatalog())->all($idSite) as $entry) {
$dimensions[] = $entry->toArray();
}
$metrics = [];
foreach ((new MetricCatalog())->all($idSite) as $entry) {
$metrics[] = $entry->toArray();
}
$segments = [];
foreach (SegmentEditorAPI::getInstance()->getAll($idSite) as $segment) {
$segments[] = ['definition' => (string) $segment['definition'], 'name' => (string) $segment['name']];
}
return [
'dimensions' => $this->groupByCategory($dimensions),
'metrics' => $this->groupByCategory($metrics),
'segments' => $segments,
'limits' => [
'maxDimensions' => Configuration::getMaxDimensions(),
'maxMetrics' => ReportDefinition::MAX_METRICS,
'maxColumns' => 1,
],
];
}
/**
* Runs an unsaved funnel live: one row per step, with a subtable per step of the breakdown values when the
* funnel has a breakdown.
*
* @unsanitized
* @param int $idSite
* @param string $period
* @param string $date
* @param string $definition JSON of the funnel, same shape as a saved funnel definition
* @param string $segment combined (AND) with the segment stored in the definition
* @return DataTable|DataTable\Map
*/
public function runFunnel(int $idSite, string $period, string $date, string $definition, string $segment = ''): DataTable\DataTableInterface
{
(new ReportPermissions())->checkCanExplore($idSite);
$raw = json_decode($definition, true);
if (!is_array($raw)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorDefinitionInvalid'));
}
$raw['type'] = ReportDefinition::TYPE_FUNNEL;
if (!isset($raw['name']) || !is_string($raw['name']) || trim($raw['name']) === '') {
$raw['name'] = 'preview';
}
$validated = ReportDefinition::fromArray($raw);
if (Period::isMultiplePeriod($date, $period)) {
$site = new Site($idSite);
$map = new DataTable\Map();
$map->setKeyName('date');
foreach (array_slice((new Range($period, $date, $site->getTimezone()))->getSubperiods(), -Configuration::getRawSqlMaxPoints()) as $subPeriod) {
$map->addTable($this->runFunnel($idSite, $subPeriod->getLabel(), $subPeriod->getDateStart()->toString(), $definition, $segment), $subPeriod->getPrettyString());
}
return $map;
}
$cache = Cache::getLazyCache();
$cacheId = 'DataExplorer_funnel_' . md5(implode('|', [$idSite, $period, $date, $segment, json_encode($validated->toArray())]));
$rows = $cache->fetch($cacheId);
if (!is_array($rows)) {
$rows = (new FunnelQueryRunner())->run($validated, $idSite, $period, $date, $segment)->getRows();
$rows = array_map(fn (DataTable\Row $row) => [
'columns' => $row->getColumns(),
'subtable' => $row->getSubtable() instanceof DataTable ? array_map(fn (DataTable\Row $sub) => $sub->getColumns(), $row->getSubtable()->getRows()) : null,
], $rows);
$cache->save($cacheId, $rows, self::PREVIEW_CACHE_TTL);
}
$table = new DataTable();
foreach ($rows as $row) {
$stepRow = new DataTable\Row([DataTable\Row::COLUMNS => $row['columns']]);
if ($row['subtable'] !== null) {
$subtable = new DataTable();
foreach ($row['subtable'] as $columns) {
$subtable->addRow(new DataTable\Row([DataTable\Row::COLUMNS => $columns]));
}
$stepRow->setSubtable($subtable);
}
$table->addRow($stepRow);
}
$breakdown = $validated->getBreakdown() === null ? null : (new VisualQueryBuilder())->resolveDimension($validated->getBreakdown(), $idSite);
FunnelResult::present($table, $validated, $breakdown, $idSite);
$site = new Site($idSite);
$table->setMetadata(DataTableFactory::TABLE_METADATA_SITE_INDEX, $site);
$table->setMetadata(DataTableFactory::TABLE_METADATA_PERIOD_INDEX, PeriodFactory::build($period, $date, $site->getTimezone()));
return $table;
}
/**
* Runs a visual exploration live (the explorer canvas). Nothing is saved. An evolution definition returns one
* table per period: the days of a range, the requested periods, or the last periods ending at the selected one.
*
* @unsanitized
* @param int $idSite
* @param string $period
* @param string $date
* @param string $definition JSON of the exploration, same shape as a saved visual definition
* @param string $segment combined (AND) with the segment stored in the definition
* @param int $idSubtable a row of the hierarchical view to open, numbered by PreviewTree
* @param bool $flat the whole tree, its subtables in memory (flat view, export)
* @return DataTable|DataTable\Map
*/
public function runVisual(int $idSite, string $period, string $date, string $definition, string $segment = '', int $idSubtable = 0, bool $flat = false): DataTable\DataTableInterface
{
(new ReportPermissions())->checkCanExplore($idSite);
$raw = json_decode($definition, true);
if (!is_array($raw)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorDefinitionInvalid'));
}
$raw['type'] = ReportDefinition::TYPE_VISUAL;
if (!isset($raw['name']) || !is_string($raw['name']) || trim($raw['name']) === '') {
$raw['name'] = 'preview';
}
$validated = ReportDefinition::fromArray($raw);
// a KPI card over several periods is its sparkline: one total per period, like an evolution
if ($validated->getReportType() === ReportDefinition::REPORT_TYPE_EVOLUTION
|| ($validated->getReportType() === ReportDefinition::REPORT_TYPE_KPICARD && Period::isMultiplePeriod($date, $period))
) {
return (new VisualQueryRunner())->runEvolution($validated, $idSite, $period, $date, $segment);
}
// a table over several periods, such as the previous and current period of a treemap's evolution colors
if (Period::isMultiplePeriod($date, $period)) {
$site = new Site($idSite);
$subPeriods = (new Range($period, $date, $site->getTimezone()))->getSubperiods();
$map = new DataTable\Map();
$map->setKeyName('date');
foreach (array_slice($subPeriods, -Configuration::getRawSqlMaxPoints()) as $subPeriod) {
$table = $this->runVisual($idSite, $subPeriod->getLabel(), $subPeriod->getDateStart()->toString(), $definition, $segment, $idSubtable, $flat);
$map->addTable($table, $subPeriod->getPrettyString());
}
return $map;
}
// the native data table of the canvas asks again on every sort, page or opened row: one run serves them
$cache = Cache::getLazyCache();
$cacheId = 'DataExplorer_preview_' . md5(implode('|', [$idSite, $period, $date, $segment, json_encode($validated->toArray())]));
$tree = $cache->fetch($cacheId);
if (!is_array($tree)) {
$tree = PreviewTree::export((new VisualQueryRunner())->run($validated, $idSite, $period, $date, $segment));
$cache->save($cacheId, $tree, self::PREVIEW_CACHE_TTL);
}
if ($flat || Common::getRequestVar('expanded', 0, 'int')) {
$table = PreviewTree::toTable($tree);
} else {
$table = PreviewTree::level($tree, $idSubtable);
if ($table === null) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorDefinitionInvalid'));
}
}
// the cached tree keeps values only: formats and the metrics to drop are set on every table served
ProcessedMetrics::forResolved((new VisualQueryBuilder())->resolve($validated, $idSite), $idSite)->decorate($table);
// like an archived report, so core can load and label the subtables of the period
$site = new Site($idSite);
$table->setMetadata(DataTableFactory::TABLE_METADATA_SITE_INDEX, $site);
$table->setMetadata(DataTableFactory::TABLE_METADATA_PERIOD_INDEX, PeriodFactory::build($period, $date, $site->getTimezone()));
return $table;
}
/**
* The parameters of CustomReports.addCustomReport for an exploration: report type, dimension and metric ids,
* and the stored segment plus the filters as one segment definition. Label filters of coded dimensions
* become the stored values they match on the site and period. "unsupported" names what a custom report
* cannot hold.
*
* @unsanitized
* @param int $idSite
* @param string $period
* @param string $date
* @param string $definition JSON of the visual definition
* @return array
*/
public function getCustomReportParameters(int $idSite, string $period, string $date, string $definition): array
{
(new ReportPermissions())->checkCanExplore($idSite);
$raw = json_decode($definition, true);
if (!is_array($raw)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorDefinitionInvalid'));
}
$raw['type'] = ReportDefinition::TYPE_VISUAL;
if (!isset($raw['name']) || !is_string($raw['name']) || trim($raw['name']) === '') {
$raw['name'] = 'preview';
}
$validated = ReportDefinition::fromArray($raw);
$filters = (new VisualQueryRunner())->storedFilters($validated, $idSite, $period, $date);
$export = new CustomReportExport();
$parameters = $export->convert($validated, $filters, $idSite);
if (!Configuration::isCustomReportsAvailable()) {
return $parameters;
}
$resolved = (new VisualQueryBuilder())->resolve($validated, $idSite);
$metricNames = [];
foreach (array_merge($resolved['metrics'], $resolved['processed']) as $metric) {
$metricNames[$metric->id] = $metric->name;
}
$dimensionNames = [];
foreach ($resolved['rows'] as $dimension) {
$dimensionNames[$dimension->id] = $dimension->name;
}
return $export->mapToCatalogue(
$parameters,
$metricNames,
$dimensionNames,
$this->customReportsCatalogue('CustomReports.getAvailableMetrics', 'metrics', $idSite),
$this->customReportsCatalogue('CustomReports.getAvailableDimensions', 'dimensions', $idSite)
);
}
/**
* The custom reports of a site the explorer can open, id and name only. Empty when that plugin is not active.
*
* @param int $idSite
* @return array{idcustomreport: int, name: string, place: string}[]
*/
public function getCustomReports(int $idSite): array
{
(new ReportPermissions())->checkCanExplore($idSite);
if (!Configuration::isCustomReportsAvailable()) {
return [];
}
$reports = (array) \Piwik\API\Request::processRequest('CustomReports.getConfiguredReports', [
'idSite' => $idSite,
'filter_limit' => -1,
'format' => 'original',
], []);
$result = [];
foreach ($reports as $report) {
if (isset($report['idcustomreport'], $report['name']) && ($report['status'] ?? 'active') === 'active') {
$place = array_filter([(string) ($report['category']['name'] ?? ''), (string) ($report['subcategory']['name'] ?? '')], 'strlen');
$result[] = [
'idcustomreport' => (int) $report['idcustomreport'],
'name' => (string) $report['name'],
'place' => implode(' > ', $place),
];
}
}
return $result;
}
/**
* A custom report as a visual definition the explorer opens: the same dimensions and metrics, its segment as
* filter groups where it can be, the rest kept as the segment. "unsupported" names what the explorer has not.
*
* @param int $idSite
* @param int $idCustomReport
* @return array{definition: array, unsupported: string[], customReport: array}
*/
public function getCustomReportDefinition(int $idSite, int $idCustomReport): array
{
(new ReportPermissions())->checkCanExplore($idSite);
if (!Configuration::isCustomReportsAvailable()) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorCustomReportsUnavailable'));
}
$report = (array) \Piwik\API\Request::processRequest('CustomReports.getConfiguredReport', [
'idSite' => $idSite,
'idCustomReport' => $idCustomReport,
'format' => 'original',
], []);
$metrics = [];
foreach ((new MetricCatalog())->all($idSite) as $entry) {
$metrics[$entry->id] = $entry->name;
}
$result = (new CustomReportImport())->convert(
$report,
(new DimensionCatalog())->all($idSite),
$metrics,
$this->customReportsCatalogue('CustomReports.getAvailableDimensions', 'dimensions', $idSite),
$this->customReportsCatalogue('CustomReports.getAvailableMetrics', 'metrics', $idSite)
);
// what saving it again keeps: its place in the menu, its sites, and what an update must send back
$result['customReport'] = [
'idCustomReport' => (int) ($report['idcustomreport'] ?? $idCustomReport),
'idSite' => (int) ($report['idsite'] ?? $idSite),
'name' => (string) ($report['name'] ?? ''),
'description' => (string) ($report['description'] ?? ''),
'category' => (string) ($report['category']['id'] ?? ''),
'subcategory' => (string) ($report['subcategory']['id'] ?? ''),
'multipleIdSites' => array_values(array_filter(array_map('intval', explode(',', (string) ($report['multiple_idsites'] ?? ''))))),
'childReportIds' => array_values(array_map(fn ($child) => (int) ($child['idcustomreport'] ?? 0), (array) ($report['child_reports'] ?? []))),
'editable' => !empty($report['allowedToEdit']),
];
return $result;
}
/**
* @return array<string, string> id => name of a Custom Reports catalogue
*/
private function customReportsCatalogue(string $method, string $key, int $idSite): array
{
$catalogue = [];
foreach ((array) \Piwik\API\Request::processRequest($method, ['idSite' => $idSite, 'filter_limit' => -1, 'format' => 'original'], []) as $category) {
foreach ((array) ($category[$key] ?? []) as $entry) {
if (isset($entry['uniqueId'])) {
$catalogue[(string) $entry['uniqueId']] = (string) ($entry['name'] ?? $entry['uniqueId']);
}
}
}
return $catalogue;
}
/**
* Runs a raw SQL query live on the read-only connection (super user only). {idsite}, {date_start} and
* {date_end} are bound from the site and period.
*
* @unsanitized
* @param int $idSite
* @param string $period
* @param string $date
* @param string $sql
* @return DataTable
*/
public function runSql(int $idSite, string $period, string $date, string $sql): DataTable
{
(new ReportPermissions())->checkCanRunRawSql();
return (new RawSqlRunner())->run($sql, $idSite, $period, $date);
}
/**
* Columns of the tables raw SQL can read, keyed by their prefixed name as written in a query, for the
* autocompletion of the SQL editor (super user only).
*
* @return array<string, string[]>
*/
public function getSqlSchema(): array
{
(new ReportPermissions())->checkCanRunRawSql();
$schema = [];
foreach ((new ReadOnlySetup())->tables() as $table) {
$schema[$table] = array_map(fn (array $column) => (string) $column['Field'], Db::fetchAll('SHOW COLUMNS FROM `' . str_replace('`', '``', $table) . '`'));
}
return $schema;
}
/**
* State of the read-only connection raw SQL runs with (super user only), read when the SQL tab opens.
*
* @return array{state: string, message: string} state is ready when raw SQL can run
*/
public function getSqlStatus(): array
{
(new ReportPermissions())->checkCanRunRawSql();
return (new ReadOnlySetup())->status();
}
/**
* Data of a saved report on a site where it is placed, for any user with view access on that site.
* Visual reports are read from their archives (segment applied), raw SQL reports run live with a short cache
* (segment ignored). Evolution and KPI card raw SQL reports run once per sub-period of a multiple period,
* at most raw_sql_max_points times (the most recent ones).
*
* idExploration 0 with a definition is the unsaved exploration of the explorer canvas, run live like runVisual,
* so the canvas and the saved report share the report class core renders them with.
*
* @param int $idSite
* @param string $period
* @param string $date
* @param int $idExploration
* @param string $segment
* @param bool $expanded
* @param int $idSubtable
* @param string $definition JSON of an unsaved visual exploration, with idExploration 0
* @return DataTable\DataTableInterface
*/
public function getReport(int $idSite, string $period, string $date, int $idExploration, string $segment = '', bool $expanded = false, int $idSubtable = 0, string $definition = '')
{
if ($idExploration === 0 && $definition !== '') {
$raw = json_decode(Common::unsanitizeInputValue($definition), true);
if (is_array($raw) && ($raw['type'] ?? '') === ReportDefinition::TYPE_FUNNEL) {
return $this->runFunnel($idSite, $period, $date, Common::unsanitizeInputValue($definition), Common::unsanitizeInputValue($segment));
}
if (is_array($raw) && ($raw['type'] ?? '') === ReportDefinition::TYPE_SQL) {
$validated = GetSavedReport::previewDefinition(Common::unsanitizeInputValue($definition));
return (new SavedReportReader())->readSqlPreview($validated['sql'], $validated['report_type'], $idSite, $period, $date);
}
// runVisual takes its parameters unsanitized; core flattens the flat view from the whole tree
$flat = $expanded || Common::getRequestVar('flat', 0, 'int') === 1;
return $this->runVisual($idSite, $period, $date, Common::unsanitizeInputValue($definition), Common::unsanitizeInputValue($segment), $idSubtable, $flat);
}
$report = (new ReportsDao())->get($idExploration);
if ($report === null) {
throw new NoAccessException(Piwik::translate('DataExplorer_ErrorReportNotAvailable'));
}
return (new SavedReportReader())->read($report, $idSite, $period, $date, $segment, $expanded, $idSubtable);
}
/**
* Checks a raw SQL query with the guard used before each run, for the live validation of the editor
* (super user only). Offsets count Unicode code points, the *Utf16 variants count UTF-16 code units like
* JavaScript strings do. A null offset means the whole query.
*
* @unsanitized
* @param string $sql
* @return array{valid: bool, errors: array, warnings: array}
*/
public function validateSql(string $sql): array
{
(new ReportPermissions())->checkCanRunRawSql();
try {
$parsed = $this->guardSql($sql);
} catch (RejectedQueryException $e) {
return [
'valid' => false,
'errors' => [$this->problem($sql, $e->getOffset(), $this->tokenLength($e->getOffendingToken()), $e->getMessage())],
'warnings' => [],
];
}
$warnings = [];
$unproven = SiteScopeProof::check($parsed);
if ($unproven !== null) {
$offset = null;
$length = 0;
foreach ($parsed->getTableInstances() as $instance) {
if ($instance['alias'] === $unproven || ($instance['alias'] === null && $instance['table'] === $unproven)) {
$offset = $instance['position'];
$length = mb_strlen($instance['name']);
break;
}
}
$warnings[] = $this->problem($sql, $offset, $length, Piwik::translate('DataExplorer_SqlWarningNotSiteScoped', [$unproven]));
}
return ['valid' => true, 'errors' => [], 'warnings' => $warnings];
}
/**
* Saves a new report. Visual reports need write access on every listed site, raw SQL reports and "all
* websites" need super user access, and a raw SQL query must prove that every per-site table it reads is
* filtered by idsite = {idsite}.
*
* @unsanitized
* @param string $name
* @param string $type visual or sql
* @param string $reportType table, evolution or kpicard
* @param string $definition JSON of the definition, {"sql": "..."} for a raw SQL report
* @param string $placement JSON, {"all": true} or {"sites": [1, 2]}
* @param string $category an id of getCategories(), empty for the Data Explorer category
* @param string $subcategory an existing subcategory id of the category, the name of a new one, or empty for a page of its own
* @param int $order 0 to 1000
* @return int id of the report
*/
public function addReport(string $name, string $type, string $reportType, string $definition, string $placement, string $category, string $subcategory = '', int $order = 100): int
{
$permissions = new ReportPermissions();
$newPlacement = $this->parsePlacement($placement);
$permissions->checkCanSave($newPlacement, $type);
$this->checkSitesExist($newPlacement);
$row = $this->buildRow($name, $type, $reportType, $definition, $newPlacement, $category, $subcategory, $order);
$row['created_by'] = Piwik::getCurrentUserLogin();
$dao = new ReportsDao();
$idReport = $dao->insert($row, $newPlacement);
$report = $dao->get($idReport);
$this->afterWrite($report);
/**
* Triggered after a DataExplorer report is created or updated.
*
* @param int $idReport
* @param array $report the stored report
* @param array|null $previous the report before the update, null on creation
*/
Piwik::postEvent('DataExplorer.reportSaved', [$idReport, $report, null]);
return $idReport;
}
/**
* Updates a report, with the access rules of addReport() for its new placement plus the right to edit it:
* its author with write access on every site it is placed on, or an admin of all those sites. Raw SQL
* reports, and turning a report into or out of raw SQL, need super user access. Only a change of what the
* report computes rebuilds its history; a new placement only builds it on the sites added.
*
* @unsanitized
* @param int $idReport
* @param string $name
* @param string $type
* @param string $reportType
* @param string $definition
* @param string $placement
* @param string $category
* @param string $subcategory
* @param int $order
*/
public function updateReport(int $idReport, string $name, string $type, string $reportType, string $definition, string $placement, string $category, string $subcategory = '', int $order = 100): void
{
$dao = new ReportsDao();
$previous = $this->getWritableReport($dao, $idReport);
$permissions = new ReportPermissions();
$newPlacement = $this->parsePlacement($placement);
$permissions->checkCanSave($newPlacement, $type);
$this->checkSitesExist($newPlacement);
$row = $this->buildRow($name, $type, $reportType, $definition, $newPlacement, $category, $subcategory, $order);
$computedChanged = $this->computesSomethingElse($previous, $row);
$dao->update($idReport, $row, $newPlacement, $computedChanged);
$report = $dao->get($idReport);
if ($computedChanged) {
$this->afterWrite($report);
} else {
$this->afterWrite($report, $this->addedSites($previous['placement'], $newPlacement));
}
Piwik::postEvent('DataExplorer.reportSaved', [$idReport, $report, $previous]);
}
/**
* Soft deletes a report, with the rights of updateReport().
*
* @param int $idReport
*/
public function deleteReport(int $idReport): void
{
$dao = new ReportsDao();
$report = $this->getWritableReport($dao, $idReport);
$dao->softDelete($idReport);
$this->afterWrite(null);
/**
* Triggered after a DataExplorer report is deleted.
*
* @param int $idReport
* @param array $report the report as it was before the deletion
*/
Piwik::postEvent('DataExplorer.reportDeleted', [$idReport, $report]);
}
/**
* Reports placed on the site, with an editable flag. The query of raw SQL reports is only returned to super
* users, and the placement lists only the sites the user can view.
*
* @param int $idSite
* @return array[]
*/
public function getReports(int $idSite): array
{
Piwik::checkUserHasViewAccess($idSite);
$permissions = new ReportPermissions();
$isSuperUser = Piwik::hasUserSuperUserAccess();
$result = [];
foreach ((new ReportsDao())->getForSite($idSite) as $report) {
try {
$permissions->checkCanView($report, $idSite);
} catch (NoAccessException $e) {
continue;
}
$definition = $report['definition'];
if (!$isSuperUser || !isset($definition['sql']) || !is_string($definition['sql'])) {
$definition['sql'] = '';
}
/** @var Placement $placement */
$placement = $report['placement'];
$sites = $placement->getSiteIds();
if (!$isSuperUser) {
$sites = array_values(array_filter($sites, fn (int $id) => Piwik::isUserHasViewAccess($id)));
}
$result[] = [
'idreport' => $report['idreport'],
'name' => $report['name'],
'type' => $report['type'],
'report_type' => $report['report_type'],
'definition' => $definition,
'placement' => ['all' => $placement->isAllWebsites(), 'sites' => $sites],
'category' => $report['category'],
'subcategory' => $report['subcategory'],
'place' => $this->placeName((string) $report['category'], (string) $report['subcategory']),
'order' => $report['order'],
'revision' => $report['revision'],
'created_by' => $report['created_by'],
'created_date' => $report['created_date'],
'updated_date' => $report['updated_date'],
'editable' => $this->canWrite($report),
];
}
return $result;
}
/**
* The reporting categories and their subcategories, where the save dialog can place a report. A new
* subcategory may be created under any of these categories.
*
* @param int $idSite
* @return array[] [{id, name, subcategories: [{id, name}]}]
*/
public function getCategories(int $idSite): array
{
(new ReportPermissions())->checkCanExplore($idSite);
return $this->reportingCategories();
}
/**
* "Category > Page" of a saved report in the reporting menu, the category alone for a report on its own page.
*/
private function placeName(string $categoryId, string $subcategoryId): string
{
$category = CategoryList::get()->getCategory($categoryId !== '' ? $categoryId : ExploreSubcategory::CATEGORY);
if (!$category) {
return '';
}
$subcategory = $subcategoryId !== '' ? $category->getSubcategory($subcategoryId) : null;
$page = $subcategory ? Piwik::translate($subcategory->getName()) : '';
return implode(' > ', array_filter([$category->getDisplayName(), $page], 'strlen'));
}
/**
* Categories of the reporting menu, with their subcategories for the site of the request.
*/
private function reportingCategories(): array
{
$allowed = $this->reportingCategoryIds();
$categories = [];
foreach (CategoryList::get()->getCategories() as $category) {
if (!isset($allowed[$category->getId()])) {
continue;
}
// the page of its own of a report is not a page others are saved on, nor are the explorer and the
// manage page: a report there would render under the explorer
$subcategories = array_values(array_filter(
$category->getSubcategories(),
fn ($subcategory) => !GetSavedReport::isOwnPage((string) $category->getId(), (string) $subcategory->getId())
&& !in_array((string) $subcategory->getId(), self::RESERVED_SUBCATEGORIES, true)
));
usort($subcategories, fn ($a, $b) => $a->getOrder() <=> $b->getOrder());
$categories[] = [
'id' => (string) $category->getId(),
'name' => $category->getDisplayName(),
'order' => (int) $category->getOrder(),
'subcategories' => array_map(fn ($subcategory) => [
'id' => (string) $subcategory->getId(),
'name' => Piwik::translate((string) $subcategory->getName()),
], $subcategories),
];
}
usort($categories, fn (array $a, array $b) => $a['order'] <=> $b['order']);
return array_map(function (array $category) {
unset($category['order']);
return $category;
}, $categories);
}
/**
* Categories that hold report pages declared as Subcategory classes. Read from the classes only, not from
* Category.addSubcategories: its listeners load per-site data of the request's idSite, which the saving user
* may not be able to view.
*
* @return array<string, true>
*/
private function reportingCategoryIds(): array
{
$ids = [];
foreach (PluginManager::getInstance()->findMultipleComponents('Categories', Subcategory::class) as $class) {
$subcategory = StaticContainer::getContainer()->make($class);
$ids[(string) $subcategory->getCategoryId()] = true;
}
foreach (self::NON_REPORTING_CATEGORIES as $id) {
unset($ids[$id]);
}
return $ids;
}
private function getWritableReport(ReportsDao $dao, int $idReport): array
{
$report = $dao->get($idReport);
if ($report === null || !empty($report['deleted'])) {
throw new \Exception(Piwik::translate('DataExplorer_ErrorReportNotFound'));
}
$this->checkCanWrite($report);
return $report;
}
/**
* checkCanEdit() plus the raw SQL rule: runSaved executes the stored query for every viewer, so only a super
* user may change or remove it, whatever the placement.
*/
private function checkCanWrite(array $report): void
{
(new ReportPermissions())->checkCanEdit($report);
if ($report['type'] === ReportDefinition::TYPE_SQL) {
Piwik::checkUserHasSuperUserAccess();
}
}
private function canWrite(array $report): bool
{
try {
$this->checkCanWrite($report);
} catch (NoAccessException $e) {
return false;
}
return true;
}
private function parsePlacement(string $placement): Placement
{
$raw = json_decode($placement, true);
if (!is_array($raw)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorPlacementInvalid'));
}
return Placement::fromArray($raw);
}
private function checkSitesExist(Placement $placement): void
{
if ($placement->isAllWebsites()) {
return;
}
$existing = Access::doAsSuperUser(fn () => array_map('intval', SitesManagerAPI::getInstance()->getAllSitesId()));
foreach ($placement->getSiteIds() as $idSite) {
if (!in_array($idSite, $existing, true)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorSiteUnknown', [$idSite]));
}
}
}
/**
* Resolves the dimensions, metrics, filters and segment of a visual report on every listed site, so an id the
* catalogue of a site lacks is refused at save rather than failing at archiving. An "all websites" report is
* checked on the site of the request only: site-specific dimensions are missing elsewhere by design and the
* read path skips them there.
*/
private function checkVisualOnSites(ReportDefinition $definition, Placement $placement): void
{
if ($placement->isAllWebsites()) {
$idSite = Common::getRequestVar('idSite', 0, 'int');
if ($idSite < 1) {
$ids = Access::doAsSuperUser(fn () => SitesManagerAPI::getInstance()->getAllSitesId());
$idSite = $ids ? (int) reset($ids) : 0;
}
$siteIds = $idSite > 0 ? [$idSite] : [];
} else {
$siteIds = $placement->getSiteIds();
}
$builder = new VisualQueryBuilder();
foreach ($siteIds as $idSite) {
if ($definition->isFunnel()) {
foreach ($definition->getSteps() as $step) {
$builder->funnelStepTable($builder->resolveConditions($step['conditions'], $idSite), $step['name']);
}
if ($definition->getBreakdown() !== null) {
$breakdown = $builder->resolveDimension($definition->getBreakdown(), $idSite);
if (!in_array($breakdown->table, ['log_visit', 'log_link_visit_action'], true)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorFunnelBreakdown', [$breakdown->name]));
}
}
} else {
$builder->resolve($definition, $idSite);
}
if ($definition->getSegment() !== '') {
try {
new Segment($definition->getSegment(), [$idSite]);
} catch (\Exception $e) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorSegmentInvalid', [$e->getMessage()]));
}
}
}
}
/**
* @return array the columns of a ReportsDao row, validated
*/
private function buildRow(string $name, string $type, string $reportType, string $definition, Placement $placement, string $category, string $subcategory, int $order): array
{
$raw = json_decode($definition, true);
if (!is_array($raw)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorDefinitionInvalid'));
}
$validated = ReportDefinition::fromArray(array_merge($raw, ['name' => $name, 'type' => $type, 'report_type' => $reportType]));
if ($validated->getType() === ReportDefinition::TYPE_SQL) {
$unproven = SiteScopeProof::check($this->guardSql($validated->getSql()));
if ($unproven !== null) {
throw new RejectedQueryException(Piwik::translate('DataExplorer_SqlWarningNotSiteScoped', [$unproven]), $unproven);
}
} else {
$this->checkVisualOnSites($validated, $placement);
}
$category = trim($category);
if ($category === '') {
$category = ExploreSubcategory::CATEGORY;
}
if (!isset($this->reportingCategoryIds()[$category])) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorCategoryInvalid'));
}
// empty: the report gets a page of its own, named after it (GetSavedReport::pageId)
$subcategory = trim($subcategory);
if (mb_strlen($subcategory) > self::MAX_SUBCATEGORY_LENGTH) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorSubcategoryInvalid', [self::MAX_SUBCATEGORY_LENGTH]));
}
if (in_array($subcategory, self::RESERVED_SUBCATEGORIES, true)) {
throw new \InvalidArgumentException(Piwik::translate('DataExplorer_ErrorSubcategoryReserved'));
}
$stored = $validated->toArray();
unset($stored['name'], $stored['type'], $stored['report_type']);
return [
'name' => $validated->getName(),
'type' => $validated->getType(),
'report_type' => $validated->getReportType(),
'definition' => $stored,
'category' => $category,
'subcategory' => $subcategory,
'order' => max(0, min(self::MAX_ORDER, $order)),
];
}
/**
* True when the update changes what the report computes, so its archived records no longer match it. A rename,
* a new place in the menu or a new placement keeps the archived history.
*/
private function computesSomethingElse(array $previous, array $row): bool
{
try {
$before = ReportDefinition::fromReport($previous)->toArray();
$after = ReportDefinition::fromReport($row)->toArray();
} catch (\InvalidArgumentException $e) {
return true;
}
// the description, the chart and the table view are read when the report renders, never archived
foreach (['name', 'description', 'chart', 'table_view'] as $key) {
unset($before[$key], $after[$key]);
}
// segments switched off keep the archives of the whole traffic; switched back on, the segment archives
// already built without the report must be rebuilt
$segmentsBefore = $before['process_segments'] ?? true;
$segmentsAfter = $after['process_segments'] ?? true;
unset($before['process_segments'], $after['process_segments']);
return $before !== $after || (!$segmentsBefore && $segmentsAfter);
}
/**
* @return int[] sites of $new that $old did not include
*/
private function addedSites(Placement $old, Placement $new): array
{
if ($old->isAllWebsites()) {
return [];
}