forked from matomo-org/matomo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataTable.php
2055 lines (1863 loc) · 69.6 KB
/
DataTable.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
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik;
use Closure;
use Exception;
use Piwik\DataTable\DataTableInterface;
use Piwik\DataTable\Manager;
use Piwik\DataTable\Renderer\Html;
use Piwik\DataTable\Row;
use Piwik\DataTable\Row\DataTableSummaryRow;
use Piwik\DataTable\Simple;
use ReflectionClass;
/**
* @see Common::destroy()
*/
require_once PIWIK_INCLUDE_PATH . '/core/Common.php';
require_once PIWIK_INCLUDE_PATH . "/core/DataTable/Bridges.php";
/**
* The primary data structure used to store analytics data in Piwik.
*
* <a name="class-desc-the-basics"></a>
* ### The Basics
*
* DataTables consist of rows and each row consists of columns. A column value can be
* a numeric, a string or an array.
*
* Every row has an ID. The ID is either the index of the row or {@link ID_SUMMARY_ROW}.
*
* DataTables are hierarchical data structures. Each row can also contain an additional
* nested sub-DataTable (commonly referred to as a 'subtable').
*
* Both DataTables and DataTable rows can hold **metadata**. _DataTable metadata_ is information
* regarding all the data, such as the site or period that the data is for. _Row metadata_
* is information regarding that row, such as a browser logo or website URL.
*
* Finally, all DataTables contain a special _summary_ row. This row, if it exists, is
* always at the end of the DataTable.
*
* ### Populating DataTables
*
* Data can be added to DataTables in three different ways. You can either:
*
* 1. create rows one by one and add them through {@link addRow()} then truncate if desired,
* 2. create an array of DataTable\Row instances or an array of arrays and add them using
* {@link addRowsFromArray()} or {@link addRowsFromSimpleArray()}
* then truncate if desired,
* 3. or set the maximum number of allowed rows (with {@link setMaximumAllowedRows()})
* and add rows one by one.
*
* If you want to eventually truncate your data (standard practice for all Piwik plugins),
* the third method is the most memory efficient. It is, unfortunately, not always possible
* to use since it requires that the data be sorted before adding.
*
* ### Manipulating DataTables
*
* There are two ways to manipulate a DataTable. You can either:
*
* 1. manually iterate through each row and manipulate the data,
* 2. or you can use predefined filters.
*
* A filter is a class that has a 'filter' method which will manipulate a DataTable in
* some way. There are several predefined Filters that allow you to do common things,
* such as,
*
* - add a new column to each row,
* - add new metadata to each row,
* - modify an existing column value for each row,
* - sort an entire DataTable,
* - and more.
*
* Using these filters instead of writing your own code will increase code clarity and
* reduce code redundancy. Additionally, filters have the advantage that they can be
* applied to DataTable\Map instances. So you can visit every DataTable in a {@link DataTable\Map}
* without having to write a recursive visiting function.
*
* All predefined filters exist in the **Piwik\DataTable\BaseFilter** namespace.
*
* _Note: For convenience, [anonymous functions](http://www.php.net/manual/en/functions.anonymous.php)
* can be used as DataTable filters._
*
* ### Applying Filters
*
* Filters can be applied now (via {@link filter()}), or they can be applied later (via
* {@link queueFilter()}).
*
* Filters that sort rows or manipulate the number of rows should be applied right away.
* Non-essential, presentation filters should be queued.
*
* ### Learn more
*
* - See **{@link ArchiveProcessor}** to learn how DataTables are persisted.
*
* ### Examples
*
* **Populating a DataTable**
*
* // adding one row at a time
* $dataTable = new DataTable();
* $dataTable->addRow(new Row(array(
* Row::COLUMNS => array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
* Row::METADATA => array('url' => 'http://thing1.com')
* )));
* $dataTable->addRow(new Row(array(
* Row::COLUMNS => array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2),
* Row::METADATA => array('url' => 'http://thing2.com')
* )));
*
* // using an array of rows
* $dataTable = new DataTable();
* $dataTable->addRowsFromArray(array(
* array(
* Row::COLUMNS => array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
* Row::METADATA => array('url' => 'http://thing1.com')
* ),
* array(
* Row::COLUMNS => array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2),
* Row::METADATA => array('url' => 'http://thing2.com')
* )
* ));
*
* // using a "simple" array
* $dataTable->addRowsFromSimpleArray(array(
* array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
* array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2)
* ));
*
* **Getting & setting metadata**
*
* $dataTable = \Piwik\Plugins\Referrers\API::getInstance()->getSearchEngines($idSite = 1, $period = 'day', $date = '2007-07-24');
* $oldPeriod = $dataTable->metadata['period'];
* $dataTable->metadata['period'] = Period\Factory::build('week', Date::factory('2013-10-18'));
*
* **Serializing & unserializing**
*
* $maxRowsInTable = Config::getInstance()->General['datatable_archiving_maximum_rows_standard'];j
*
* $dataTable = // ... build by aggregating visits ...
* $serializedData = $dataTable->getSerialized($maxRowsInTable, $maxRowsInSubtable = $maxRowsInTable,
* $columnToSortBy = Metrics::INDEX_NB_VISITS);
*
* $serializedDataTable = $serializedData[0];
* $serailizedSubTable = $serializedData[$idSubtable];
*
* **Filtering for an API method**
*
* public function getMyReport($idSite, $period, $date, $segment = false, $expanded = false)
* {
* $dataTable = Archive::createDataTableFromArchive('MyPlugin_MyReport', $idSite, $period, $date, $segment, $expanded);
* $dataTable->filter('Sort', array(Metrics::INDEX_NB_VISITS, 'desc', $naturalSort = false, $expanded));
* $dataTable->queueFilter('ColumnCallbackAddMetadata', array('label', 'url', __NAMESPACE__ . '\getUrlFromLabelForMyReport'));
* return $dataTable;
* }
*
*
* @api
*/
class DataTable implements DataTableInterface, \IteratorAggregate, \ArrayAccess
{
const MAX_DEPTH_DEFAULT = 15;
/** Name for metadata that describes when a report was archived. */
const ARCHIVED_DATE_METADATA_NAME = 'ts_archived';
/** Name for metadata that describes which columns are empty and should not be shown. */
const EMPTY_COLUMNS_METADATA_NAME = 'empty_column';
/** Name for metadata that describes the number of rows that existed before the Limit filter was applied. */
const TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME = 'total_rows_before_limit';
/**
* Name for metadata that describes how individual columns should be aggregated when {@link addDataTable()}
* or {@link Piwik\DataTable\Row::sumRow()} is called.
*
* This metadata value must be an array that maps column names with valid operations. Valid aggregation operations are:
*
* - `'skip'`: do nothing
* - `'max'`: does `max($column1, $column2)`
* - `'min'`: does `min($column1, $column2)`
* - `'sum'`: does `$column1 + $column2`
*
* See {@link addDataTable()} and {@link DataTable\Row::sumRow()} for more information.
*/
const COLUMN_AGGREGATION_OPS_METADATA_NAME = 'column_aggregation_ops';
/**
* Name for metadata that stores array of generic filters that should not be run on the table.
*/
const GENERIC_FILTERS_TO_DISABLE_METADATA_NAME = 'generic_filters_to_disable';
/** The ID of the Summary Row. */
const ID_SUMMARY_ROW = -1;
/**
* The ID of the special metadata row. This row only exists in the serialized row data and stores the datatable metadata.
*
* This allows us to save datatable metadata in archive data.
*/
const ID_ARCHIVED_METADATA_ROW = -3;
/** The original label of the Summary Row. */
const LABEL_SUMMARY_ROW = -1;
const LABEL_TOTALS_ROW = -2;
const LABEL_ARCHIVED_METADATA_ROW = '__datatable_metadata__';
/**
* Name for metadata that contains extra {@link Piwik\Plugin\ProcessedMetric}s for a DataTable.
* These metrics will be added in addition to the ones specified in the table's associated
* {@link Piwik\Plugin\Report} class.
*/
const EXTRA_PROCESSED_METRICS_METADATA_NAME = 'extra_processed_metrics';
/**
* Maximum nesting level.
*/
private static $maximumDepthLevelAllowed = self::MAX_DEPTH_DEFAULT;
/**
* Array of Row
*
* @var Row[]
*/
protected $rows = array();
/**
* Id assigned to the DataTable, used to lookup the table using the DataTable_Manager
*
* @var int
*/
protected $currentId;
/**
* Current depth level of this data table
* 0 is the parent data table
*
* @var int
*/
protected $depthLevel = 0;
/**
* This flag is set to false once we modify the table in a way that outdates the index
*
* @var bool
*/
protected $indexNotUpToDate = true;
/**
* This flag sets the index to be rebuild whenever a new row is added,
* as opposed to re-building the full index when getRowFromLabel is called.
* This is to optimize and not rebuild the full Index in the case where we
* add row, getRowFromLabel, addRow, getRowFromLabel thousands of times.
*
* @var bool
*/
protected $rebuildIndexContinuously = false;
/**
* Column name of last time the table was sorted
*
* @var string
*/
protected $tableSortedBy = false;
/**
* List of BaseFilter queued to this table
*
* @var array
*/
protected $queuedFilters = array();
/**
* List of disabled filter names eg 'Limit' or 'Sort'
*
* @var array
*/
protected $disabledFilters = array();
/**
* We keep track of the number of rows before applying the LIMIT filter that deletes some rows
*
* @var int
*/
protected $rowsCountBeforeLimitFilter = 0;
/**
* Defaults to false for performance reasons (most of the time we don't need recursive sorting so we save a looping over the dataTable)
*
* @var bool
*/
protected $enableRecursiveSort = false;
/**
* When the table and all subtables are loaded, this flag will be set to true to ensure filters are applied to all subtables
*
* @var bool
*/
protected $enableRecursiveFilters = false;
/**
* @var array
*/
protected $rowsIndexByLabel = array();
/**
* @var \Piwik\DataTable\Row
*/
protected $summaryRow = null;
/**
* @var \Piwik\DataTable\Row
*/
protected $totalsRow = null;
/**
* Table metadata. Read [this](#class-desc-the-basics) to learn more.
*
* Any data that describes the data held in the table's rows should go here.
*
* Note: this field is protected so derived classes will serialize it.
*
* @var array
*/
protected $metadata = array();
/**
* Maximum number of rows allowed in this datatable (including the summary row).
* If adding more rows is attempted, the extra rows get summed to the summary row.
*
* @var int
*/
protected $maximumAllowedRows = 0;
/**
* Constructor. Creates an empty DataTable.
*/
public function __construct()
{
// registers this instance to the manager
$this->currentId = Manager::getInstance()->addTable($this);
}
/**
* Destructor. Makes sure DataTable memory will be cleaned up.
*/
public function __destruct()
{
static $depth = 0;
// destruct can be called several times
if ($depth < self::$maximumDepthLevelAllowed
&& isset($this->rows)
) {
$depth++;
foreach ($this->rows as $row) {
Common::destroy($row);
}
if (isset($this->summaryRow)) {
Common::destroy($this->summaryRow);
}
unset($this->rows);
Manager::getInstance()->setTableDeleted($this->currentId);
$depth--;
}
}
/**
* Clone. Called when cloning the datatable. We need to make sure to create a new datatableId.
* If we do not increase tableId it can result in segmentation faults when destructing a datatable.
*/
public function __clone()
{
// registers this instance to the manager
$this->currentId = Manager::getInstance()->addTable($this);
}
public function setLabelsHaveChanged()
{
$this->indexNotUpToDate = true;
}
/**
* @ignore
* does not update the summary row!
*/
public function setRows($rows)
{
unset($this->rows);
$this->rows = $rows;
$this->indexNotUpToDate = true;
}
/**
* Sorts the DataTable rows using the supplied callback function.
*
* @param string $functionCallback A comparison callback compatible with {@link usort}.
* @param string $columnSortedBy The column name `$functionCallback` sorts by. This is stored
* so we can determine how the DataTable was sorted in the future.
*/
public function sort($functionCallback, $columnSortedBy)
{
$this->setTableSortedBy($columnSortedBy);
usort($this->rows, $functionCallback);
if ($this->isSortRecursiveEnabled()) {
foreach ($this->getRowsWithoutSummaryRow() as $row) {
$subTable = $row->getSubtable();
if ($subTable) {
$subTable->enableRecursiveSort();
$subTable->sort($functionCallback, $columnSortedBy);
}
}
}
}
public function setTotalsRow(Row $totalsRow)
{
$this->totalsRow = $totalsRow;
}
public function getTotalsRow()
{
return $this->totalsRow;
}
public function getSummaryRow()
{
return $this->summaryRow;
}
/**
* Returns the name of the column this table was sorted by (if any).
*
* See {@link sort()}.
*
* @return false|string The sorted column name or false if none.
*/
public function getSortedByColumnName()
{
return $this->tableSortedBy;
}
/**
* Enables recursive sorting. If this method is called {@link sort()} will also sort all
* subtables.
*/
public function enableRecursiveSort()
{
$this->enableRecursiveSort = true;
}
/**
* @ignore
*/
public function isSortRecursiveEnabled()
{
return $this->enableRecursiveSort === true;
}
/**
* @ignore
*/
public function setTableSortedBy($column)
{
$this->indexNotUpToDate = true;
$this->tableSortedBy = $column;
}
/**
* Enables recursive filtering. If this method is called then the {@link filter()} method
* will apply filters to every subtable in addition to this instance.
*/
public function enableRecursiveFilters()
{
$this->enableRecursiveFilters = true;
}
/**
* @ignore
*/
public function disableRecursiveFilters()
{
$this->enableRecursiveFilters = false;
}
/**
* Applies a filter to this datatable.
*
* If {@link enableRecursiveFilters()} was called, the filter will be applied
* to all subtables as well.
*
* @param string|Closure $className Class name, eg. `"Sort"` or "Piwik\DataTable\Filters\Sort"`. If no
* namespace is supplied, `Piwik\DataTable\BaseFilter` is assumed. This parameter
* can also be a closure that takes a DataTable as its first parameter.
* @param array $parameters Array of extra parameters to pass to the filter.
*/
public function filter($className, $parameters = array())
{
if ($className instanceof \Closure
|| is_array($className)
) {
array_unshift($parameters, $this);
call_user_func_array($className, $parameters);
return;
}
if (in_array($className, $this->disabledFilters)) {
return;
}
if (!class_exists($className, true)) {
$className = 'Piwik\DataTable\Filter\\' . $className;
}
$reflectionObj = new ReflectionClass($className);
// the first parameter of a filter is the DataTable
// we add the current datatable as the parameter
$parameters = array_merge(array($this), $parameters);
$filter = $reflectionObj->newInstanceArgs($parameters);
$filter->enableRecursive($this->enableRecursiveFilters);
$filter->filter($this);
}
/**
* Applies a filter to all subtables but not to this datatable.
*
* @param string|Closure $className Class name, eg. `"Sort"` or "Piwik\DataTable\Filters\Sort"`. If no
* namespace is supplied, `Piwik\DataTable\BaseFilter` is assumed. This parameter
* can also be a closure that takes a DataTable as its first parameter.
* @param array $parameters Array of extra parameters to pass to the filter.
*/
public function filterSubtables($className, $parameters = array())
{
foreach ($this->getRowsWithoutSummaryRow() as $row) {
$subtable = $row->getSubtable();
if ($subtable) {
$subtable->filter($className, $parameters);
$subtable->filterSubtables($className, $parameters);
}
}
}
/**
* Adds a filter and a list of parameters to the list of queued filters of all subtables. These filters will be
* executed when {@link applyQueuedFilters()} is called.
*
* Filters that prettify the column values or don't need the full set of rows should be queued. This
* way they will be run after the table is truncated which will result in better performance.
*
* @param string|Closure $className The class name of the filter, eg. `'Limit'`.
* @param array $parameters The parameters to give to the filter, eg. `array($offset, $limit)` for the Limit filter.
*/
public function queueFilterSubtables($className, $parameters = array())
{
foreach ($this->getRowsWithoutSummaryRow() as $row) {
$subtable = $row->getSubtable();
if ($subtable) {
$subtable->queueFilter($className, $parameters);
$subtable->queueFilterSubtables($className, $parameters);
}
}
}
/**
* Adds a filter and a list of parameters to the list of queued filters. These filters will be
* executed when {@link applyQueuedFilters()} is called.
*
* Filters that prettify the column values or don't need the full set of rows should be queued. This
* way they will be run after the table is truncated which will result in better performance.
*
* @param string|Closure $className The class name of the filter, eg. `'Limit'`.
* @param array $parameters The parameters to give to the filter, eg. `array($offset, $limit)` for the Limit filter.
*/
public function queueFilter($className, $parameters = array())
{
if (!is_array($parameters)) {
$parameters = array($parameters);
}
$this->queuedFilters[] = array('className' => $className, 'parameters' => $parameters);
}
/**
* Disable a specific filter to run on this DataTable in case you have already applied this filter or if you will
* handle this filter manually by using a custom filter. Be aware if you disable a given filter, that filter won't
* be ever executed. Even if another filter calls this filter on the DataTable.
*
* @param string $className eg 'Limit' or 'Sort'. Passing a `Closure` or an `array($class, $methodName)` is not
* supported yet. We check for exact match. So if you disable 'Limit' and
* call `->filter('Limit')` this filter won't be executed. If you call
* `->filter('Piwik\DataTable\Filter\Limit')` that filter will be executed. See it as a
* feature.
* @ignore
*/
public function disableFilter($className)
{
$this->disabledFilters[] = $className;
}
/**
* Applies all filters that were previously queued to the table. See {@link queueFilter()}
* for more information.
*/
public function applyQueuedFilters()
{
foreach ($this->queuedFilters as $filter) {
$this->filter($filter['className'], $filter['parameters']);
}
$this->clearQueuedFilters();
}
/**
* Sums a DataTable to this one.
*
* This method will sum rows that have the same label. If a row is found in `$tableToSum` whose
* label is not found in `$this`, the row will be added to `$this`.
*
* If the subtables for this table are loaded, they will be summed as well.
*
* Rows are summed together by summing individual columns. By default columns are summed by
* adding one column value to another. Some columns cannot be aggregated this way. In these
* cases, the {@link COLUMN_AGGREGATION_OPS_METADATA_NAME}
* metadata can be used to specify a different type of operation.
*
* @param \Piwik\DataTable $tableToSum
* @throws Exception
*/
public function addDataTable(DataTable $tableToSum)
{
if ($tableToSum instanceof Simple) {
if ($tableToSum->getRowsCount() > 1) {
throw new Exception("Did not expect a Simple table with more than one row in addDataTable()");
}
$row = $tableToSum->getFirstRow();
$this->aggregateRowFromSimpleTable($row);
} else {
$columnAggregationOps = $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME);
foreach ($tableToSum->getRowsWithoutSummaryRow() as $row) {
$this->aggregateRowWithLabel($row, $columnAggregationOps);
}
// we do not use getRows() as this method might get called 100k times when aggregating many datatables and
// this takes a lot of time.
$row = $tableToSum->getRowFromId(DataTable::ID_SUMMARY_ROW);
if ($row) {
$this->aggregateRow($this->summaryRow, $row, $columnAggregationOps, true);
}
}
}
/**
* Returns the Row whose `'label'` column is equal to `$label`.
*
* This method executes in constant time except for the first call which caches row
* label => row ID mappings.
*
* @param string $label `'label'` column value to look for.
* @return Row|false The row if found, `false` if otherwise.
*/
public function getRowFromLabel($label)
{
$rowId = $this->getRowIdFromLabel($label);
if (is_int($rowId) && isset($this->rows[$rowId])) {
return $this->rows[$rowId];
}
if ($rowId == self::ID_SUMMARY_ROW
&& !empty($this->summaryRow)
) {
return $this->summaryRow;
}
if (empty($rowId)
&& !empty($this->totalsRow)
&& $label == $this->totalsRow->getColumn('label')
) {
return $this->totalsRow;
}
if ($rowId instanceof Row) {
return $rowId;
}
return false;
}
/**
* Returns the row id for the row whose `'label'` column is equal to `$label`.
*
* This method executes in constant time except for the first call which caches row
* label => row ID mappings.
*
* @param string $label `'label'` column value to look for.
* @return int The row ID.
*/
public function getRowIdFromLabel($label)
{
if ($this->indexNotUpToDate) {
$this->rebuildIndex();
}
$label = (string) $label;
if (!isset($this->rowsIndexByLabel[$label])) {
// in case label is '-1' and there is no normal row w/ that label. Note: this is for BC since
// in the past, it was possible to get the summary row by searching for the label '-1'
if ($label == self::LABEL_SUMMARY_ROW
&& !is_null($this->summaryRow)
) {
return self::ID_SUMMARY_ROW;
}
return false;
}
return $this->rowsIndexByLabel[$label];
}
/**
* Returns an empty DataTable with the same metadata and queued filters as `$this` one.
*
* @param bool $keepFilters Whether to pass the queued filter list to the new DataTable or not.
* @return DataTable
*/
public function getEmptyClone($keepFilters = true)
{
$clone = new DataTable;
if ($keepFilters) {
$clone->queuedFilters = $this->queuedFilters;
}
$clone->metadata = $this->metadata;
return $clone;
}
/**
* Rebuilds the index used to lookup a row by label
* @internal
*/
public function rebuildIndex()
{
$this->rowsIndexByLabel = array();
$this->rebuildIndexContinuously = true;
foreach ($this->rows as $id => $row) {
$label = $row->getColumn('label');
if ($label !== false) {
$this->rowsIndexByLabel[$label] = $id;
}
}
$this->indexNotUpToDate = false;
}
/**
* Returns a row by ID. The ID is either the index of the row or {@link ID_SUMMARY_ROW}.
*
* @param int $id The row ID.
* @return Row|false The Row or false if not found.
*/
public function getRowFromId($id)
{
if ($id == self::ID_SUMMARY_ROW
&& !is_null($this->summaryRow)
) {
return $this->summaryRow;
}
if (!isset($this->rows[$id])) {
return false;
}
return $this->rows[$id];
}
/**
* Returns the row that has a subtable with ID matching `$idSubtable`.
*
* @param int $idSubTable The subtable ID.
* @return Row|false The row or false if not found
*/
public function getRowFromIdSubDataTable($idSubTable)
{
$idSubTable = (int)$idSubTable;
foreach ($this->rows as $row) {
if ($row->getIdSubDataTable() === $idSubTable) {
return $row;
}
}
return false;
}
/**
* Adds a row to this table.
*
* If {@link setMaximumAllowedRows()} was called and the current row count is
* at the maximum, the new row will be summed to the summary row. If there is no summary row,
* this row is set as the summary row.
*
* @param Row $row
* @return Row `$row` or the summary row if we're at the maximum number of rows.
*/
public function addRow(Row $row)
{
// if there is a upper limit on the number of allowed rows and the table is full,
// add the new row to the summary row
if ($this->maximumAllowedRows > 0
&& $this->getRowsCount() >= $this->maximumAllowedRows - 1
) {
if ($this->summaryRow === null) {
// create the summary row if necessary
$columns = array('label' => self::LABEL_SUMMARY_ROW) + $row->getColumns();
$this->addSummaryRow(new Row(array(Row::COLUMNS => $columns)));
} else {
$this->summaryRow->sumRow(
$row, $enableCopyMetadata = false, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME));
}
return $this->summaryRow;
}
$this->rows[] = $row;
if (!$this->indexNotUpToDate
&& $this->rebuildIndexContinuously
) {
$label = $row->getColumn('label');
if ($label !== false) {
$this->rowsIndexByLabel[$label] = count($this->rows) - 1;
}
}
return $row;
}
/**
* Sets the summary row.
*
* _Note: A DataTable can have only one summary row._
*
* @param Row $row
* @return Row Returns `$row`.
*/
public function addSummaryRow(Row $row)
{
$this->summaryRow = $row;
$row->setIsSummaryRow();
// NOTE: the summary row does not go in the index, since it will overwrite rows w/ label == -1
return $row;
}
/**
* Returns the DataTable ID.
*
* @return int
*/
public function getId()
{
return $this->currentId;
}
/**
* Adds a new row from an array.
*
* You can add row metadata with this method.
*
* @param array $row eg. `array(Row::COLUMNS => array('visits' => 13, 'test' => 'toto'),
* Row::METADATA => array('mymetadata' => 'myvalue'))`
*/
public function addRowFromArray($row)
{
$this->addRowsFromArray(array($row));
}
/**
* Adds a new row a from an array of column values.
*
* Row metadata cannot be added with this method.
*
* @param array $row eg. `array('name' => 'google analytics', 'license' => 'commercial')`
*/
public function addRowFromSimpleArray($row)
{
$this->addRowsFromSimpleArray(array($row));
}
/**
* Returns the array of Rows.
* Internal logic in Matomo core should avoid using this method as it is time and memory consuming when being
* executed thousands of times. The alternative is to use {@link getRowsWithoutSummaryRow()} + get the summary
* row manually.
*
* @return Row[]
*/
public function getRows()
{
if (is_null($this->summaryRow)) {
return $this->rows;
} else {
return $this->rows + array(self::ID_SUMMARY_ROW => $this->summaryRow);
}
}
/**
* @ignore
*/
public function getRowsWithoutSummaryRow()
{
return $this->rows;
}
/**
* @ignore
*/
public function getRowsCountWithoutSummaryRow()
{
return count($this->rows);
}
/**
* Returns an array containing all column values for the requested column.
*
* @param string $name The column name.
* @return array The array of column values.
*/
public function getColumn($name)
{
$columnValues = array();
foreach ($this->getRows() as $row) {
$columnValues[] = $row->getColumn($name);
}
return $columnValues;
}
/**
* Returns an array containing all column values of columns whose name starts with `$name`.
*
* @param string $namePrefix The column name prefix.
* @return array The array of column values.
*/
public function getColumnsStartingWith($namePrefix)
{
$columnValues = array();
foreach ($this->getRows() as $row) {
$columns = $row->getColumns();
foreach ($columns as $column => $value) {
if (strpos($column, $namePrefix) === 0) {
$columnValues[] = $row->getColumn($column);
}
}
}
return $columnValues;
}
/**
* Returns the names of every column this DataTable contains. This method will return the
* columns of the first row with data and will assume they occur in every other row as well.
*
*_ Note: If column names still use their in-database INDEX values (@see Metrics), they
* will be converted to their string name in the array result._
*
* @return array Array of string column names.
*/
public function getColumns()
{
$result = array();
foreach ($this->getRows() as $row) {
$columns = $row->getColumns();
if (!empty($columns)) {
$result = array_keys($columns);
break;
}
}
// make sure column names are not DB index values
foreach ($result as &$column) {
if (isset(Metrics::$mappingFromIdToName[$column])) {
$column = Metrics::$mappingFromIdToName[$column];
}
}
return $result;
}
/**
* Returns an array containing the requested metadata value of each row.
*
* @param string $name The metadata column to return.
* @return array
*/
public function getRowsMetadata($name)
{
$metadataValues = array();
foreach ($this->getRows() as $row) {
$metadataValues[] = $row->getMetadata($name);
}
return $metadataValues;