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
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
|
<?php
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
* @version $Id$
*
* @category Piwik
* @package Piwik
*/
/**
* @see destroy()
*/
require_once PIWIK_INCLUDE_PATH . '/core/Common.php';
/**
*
* ---- DataTable
* A DataTable is a data structure used to store complex tables of data.
*
* A DataTable is composed of multiple DataTable_Row.
* A DataTable can be applied one or several DataTable_Filter.
* A DataTable can be given to a DataTable_Renderer that would export the data under a given format (XML, HTML, etc.).
*
* A DataTable has the following features:
* - serializable to be stored in the DB
* - loadable from the serialized version
* - efficient way of loading data from an external source (from a PHP array structure)
* - very simple interface to get data from the table
*
* ---- DataTable_Row
* A DataTableRow in the table is defined by
* - multiple columns (a label, multiple values, ...)
* - optional metadata
* - optional - a sub DataTable associated to this row
*
* Simple row example:
* - columns = array( 'label' => 'Firefox',
* 'visitors' => 155,
* 'pages' => 214,
* 'bounce_rate' => 67)
* - metadata = array('logo' => '/img/browsers/FF.png')
* - no sub DataTable
*
* A more complex example would be a DataTable_Row that is associated to a sub DataTable.
* For example, for the row of the search engine Google,
* we want to get the list of keywords associated, with their statistics.
* - columns = array( 'label' => 'Google',
* 'visits' => 1550,
* 'visits_length' => 514214,
* 'returning_visits' => 77)
* - metadata = array( 'logo' => '/img/search/google.png',
* 'url' => 'http://google.com')
* - DataTable = DataTable containing several DataTable_Row containing the keywords information for this search engine
* Example of one DataTable_Row
* - the keyword columns specific to this search engine =
* array( 'label' => 'Piwik', // the keyword
* 'visitors' => 155, // Piwik has been searched on Google by 155 visitors
* 'pages' => 214 // Visitors coming from Google with the kwd Piwik have seen 214 pages
* )
* - the keyword metadata = array() // nothing here, but we could imagining storing the URL of the search in Google for example
* - no subTable
*
*
* ---- DataTable_Filter
* A DataTable_Filter is a applied to a DataTable and so
* can filter information in the multiple DataTable_Row.
*
* For example a DataTable_Filter can:
* - remove rows from the table,
* for example the rows' labels that do not match a given searched pattern
* for example the rows' values that are less than a given percentage (low population)
* - return a subset of the DataTable
* for example a function that apply a limit: $offset, $limit
* - add / remove columns
* for example adding a column that gives the percentage of a given value
* - add some metadata
* for example the 'logo' path if the filter detects the logo
* - edit the value, the label
* - change the rows order
* for example if we want to sort by Label alphabetical order, or by any column value
*
* When several DataTable_Filter are to be applied to a DataTable they are applied sequentially.
* A DataTable_Filter is assigned a priority.
* For example, filters that
* - sort rows should be applied with the highest priority
* - remove rows should be applied with a high priority as they prune the data and improve performance.
*
* ---- Code example
*
* $table = new DataTable();
* $table->addRowsFromArray( array(...) );
*
* # sort the table by visits asc
* $filter = new DataTable_Filter_Sort( $table, 'visits', 'asc');
* $tableFiltered = $filter->getTableFiltered();
*
* # add a filter to select only the website with a label matching '*.com' (regular expression)
* $filter = new DataTable_Filter_Pattern( $table, 'label', '*(.com)');
* $tableFiltered = $filter->getTableFiltered();
*
* # keep the 20 elements from offset 15
* $filter = new DataTable_Filter_Limit( $tableFiltered, 15, 20);
* $tableFiltered = $filter->getTableFiltered();
*
* # add a column computing the percentage of visits
* # params = table, column containing the value, new column name to add, number of total visits to use to compute the %
* $filter = new DataTable_Filter_AddColumnPercentage( $tableFiltered, 'visits', 'visits_percentage', 2042);
* $tableFiltered = $filter->getTableFiltered();
*
* # we get the table as XML
* $xmlOutput = new DataTable_Exporter_Xml( $table );
* $xmlOutput->setHeader( ... );
* $xmlOutput->setColumnsToExport( array('visits', 'visits_percent', 'label') );
* $XMLstring = $xmlOutput->getOutput();
*
*
* ---- Other (ideas)
* We can also imagine building a DataTable_Compare which would take N DataTable that have the same
* structure and would compare them, by computing the percentages of differences, etc.
*
* For example
* DataTable1 = [ keyword1, 1550 visits]
* [ keyword2, 154 visits ]
* DataTable2 = [ keyword1, 1004 visits ]
* [ keyword3, 659 visits ]
* DataTable_Compare = result of comparison of table1 with table2
* [ keyword1, +154% ]
* [ keyword2, +1000% ]
* [ keyword3, -430% ]
*
* @see Piwik_DataTable_Row A Piwik_DataTable is composed of Piwik_DataTable_Row
*
* @package Piwik
* @subpackage Piwik_DataTable
*/
class Piwik_DataTable
{
/** Name for metadata that describes when a report was archived. */
const ARCHIVED_DATE_METADATA_NAME = 'archived_date';
const MAX_DEPTH_DEFAULT = 15;
/**
* Maximum nesting level.
*/
static private $maximumDepthLevelAllowed = self::MAX_DEPTH_DEFAULT;
/**
* Array of Piwik_DataTable_Row
*
* @var Piwik_DataTable_Row[]
*/
protected $rows = array();
/**
* Array of parent IDs
*
* @var array
*/
protected $parents = null;
/**
* 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 Piwik_DataTable_Filter queued to this table
*
* @var array
*/
protected $queuedFilters = 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;
/**
* Table metadata.
*
* @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;
const ID_SUMMARY_ROW = -1;
const LABEL_SUMMARY_ROW = -1;
const ID_PARENTS = -2;
/**
* Builds the DataTable, registers itself to the manager
*
*/
public function __construct()
{
$this->currentId = Piwik_DataTable_Manager::getInstance()->addTable($this);
}
/**
* At destruction we free all memory
*/
public function __destruct()
{
static $depth = 0;
// destruct can be called several times
if($depth < self::$maximumDepthLevelAllowed
&& isset($this->rows))
{
$depth++;
foreach($this->getRows() as $row) {
destroy($row);
}
unset($this->rows);
Piwik_DataTable_Manager::getInstance()->setTableDeleted($this->getId());
$depth--;
}
}
/**
* Sort the dataTable rows using the php callback function
*
* @param string $functionCallback
* @param string $columnSortedBy The column name. Used to then ask the datatable what column are you sorted by
*/
public function sort( $functionCallback, $columnSortedBy )
{
$this->indexNotUpToDate = true;
$this->tableSortedBy = $columnSortedBy;
usort( $this->rows, $functionCallback );
if($this->enableRecursiveSort === true)
{
foreach($this->getRows() as $row)
{
if(($idSubtable = $row->getIdSubDataTable()) !== null)
{
$table = Piwik_DataTable_Manager::getInstance()->getTable($idSubtable);
$table->enableRecursiveSort();
$table->sort($functionCallback, $columnSortedBy);
}
}
}
}
/**
* Returns the name of the column the tables is sorted by
*
* @return bool|string
*/
public function getSortedByColumnName()
{
return $this->tableSortedBy;
}
/**
* Enables the recursive sort. Means that when using $table->sort()
* it will also sort all subtables using the same callback
*/
public function enableRecursiveSort()
{
$this->enableRecursiveSort = true;
}
/**
* Enables the recursive filter. Means that when using $table->filter()
* it will also filter all subtables using the same callback
*/
public function enableRecursiveFilters()
{
$this->enableRecursiveFilters = true;
}
/**
* Returns the number of rows before we applied the limit filter
*
* @return int
*/
public function getRowsCountBeforeLimitFilter()
{
$toReturn = $this->rowsCountBeforeLimitFilter;
if($toReturn == 0)
{
return $this->getRowsCount();
}
return $toReturn;
}
/**
* Saves the current number of rows
*/
function setRowsCountBeforeLimitFilter()
{
$this->rowsCountBeforeLimitFilter = $this->getRowsCount();
}
/**
* Apply a filter to this datatable
*
* @param string $className Class name, eg. "Sort" or "Piwik_DataTable_Filter_Sort"
* @param array $parameters Array of parameters to the filter, eg. array('nb_visits', 'asc')
*/
public function filter( $className, $parameters = array() )
{
if(!class_exists($className, false))
{
$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);
}
/**
* Queue a DataTable_Filter that will be applied when applyQueuedFilters() is called.
* (just before sending the datatable back to the browser (or API, etc.)
*
* @param string $className The class name of the filter, eg. Piwik_DataTable_Filter_Limit
* @param array $parameters The parameters to give to the filter, eg. array( $offset, $limit) for the filter Piwik_DataTable_Filter_Limit
*/
public function queueFilter( $className, $parameters = array() )
{
if(!is_array($parameters))
{
$parameters = array($parameters);
}
$this->queuedFilters[] = array('className' => $className, 'parameters' => $parameters);
}
/**
* Apply all filters that were previously queued to this table
* @see queueFilter()
*/
public function applyQueuedFilters()
{
foreach($this->queuedFilters as $filter)
{
$this->filter($filter['className'], $filter['parameters']);
}
$this->queuedFilters = array();
}
/**
* Adds a new DataTable to this DataTable
* Go through all the rows of the new DataTable and applies the algorithm:
* - if a row in $table doesnt exist in $this we add the new row to $this
* - if a row exists in both $table and $this we sum the columns values into $this
* - if a row in $this doesnt exist in $table we add in $this the row of $table without modification
*
* A common row to 2 DataTable is defined by the same label
*
* @example tests/core/DataTable.test.php
*
* @param Piwik_DataTable $tableToSum
*/
public function addDataTable( Piwik_DataTable $tableToSum )
{
foreach($tableToSum->getRows() as $row)
{
$labelToLookFor = $row->getColumn('label');
$rowFound = $this->getRowFromLabel( $labelToLookFor );
if($rowFound === false)
{
if( $labelToLookFor === self::LABEL_SUMMARY_ROW )
{
$this->addSummaryRow( $row );
}
else
{
$this->addRow( $row );
}
}
else
{
$rowFound->sumRow( $row );
// if the row to add has a subtable whereas the current row doesn't
// we simply add it (cloning the subtable)
// if the row has the subtable already
// then we have to recursively sum the subtables
if(($idSubTable = $row->getIdSubDataTable()) !== null)
{
$rowFound->sumSubtable( Piwik_DataTable_Manager::getInstance()->getTable($idSubTable) );
}
}
}
}
/**
* Returns the Piwik_DataTable_Row that has a column 'label' with the value $label
*
* @param string $label Value of the column 'label' of the row to return
* @return Piwik_DataTable_Row|false The row if found, false otherwise
*/
public function getRowFromLabel( $label )
{
$rowId = $this->getRowIdFromLabel($label);
if($rowId instanceof Piwik_DataTable_Row)
{
return $rowId;
}
if(is_int($rowId) && isset($this->rows[$rowId]))
{
return $this->rows[$rowId];
}
return false;
}
/**
* Returns the row id for the givel label
*
* @param string $label Value of the column 'label' of the row to return
* @return int|Row
*/
public function getRowIdFromLabel($label)
{
$this->rebuildIndexContinuously = true;
if($this->indexNotUpToDate)
{
$this->rebuildIndex();
}
if($label === self::LABEL_SUMMARY_ROW
&& !is_null($this->summaryRow))
{
return $this->summaryRow;
}
$label = (string)$label;
if(!isset($this->rowsIndexByLabel[$label]))
{
return false;
}
return $this->rowsIndexByLabel[$label];
}
/**
* Returns a Piwik_DataTable that has only the one column that matches $label.
* If no matches are found, an empty data table is returned.
*
* @param string $label Value of the column 'label' to search for
* @return Piwik_DataTable
*/
public function getFilteredTableFromLabel($label)
{
$newTable = $this->getEmptyClone();
$row = $this->getRowFromLabel($label);
if ($row !== false)
{
$newTable->addRow($row);
}
return $newTable;
}
/**
* Get an empty table with the same properties as this one
*
* @return Piwik_DataTable
*/
public function getEmptyClone()
{
$clone = new Piwik_DataTable;
$clone->queuedFilters = $this->queuedFilters;
return $clone;
}
/**
* Rebuilds the index used to lookup a row by label
*/
private function rebuildIndex()
{
foreach($this->rows as $id => $row)
{
$label = $row->getColumn('label');
if($label !== false)
{
$this->rowsIndexByLabel[$label] = $id;
}
}
$this->indexNotUpToDate = false;
}
/**
* Returns the ith row in the array
*
* @param int $id
* @return Piwik_DataTable_Row or false if not found
*/
public function getRowFromId($id)
{
if(!isset($this->rows[$id]))
{
if($id == self::ID_SUMMARY_ROW
&& !is_null($this->summaryRow))
{
return $this->summaryRow;
}
return false;
}
return $this->rows[$id];
}
/**
* Returns a row that has the subtable ID matching the parameter
*
* @param int $idSubTable
* @return Piwik_DataTable_Row|false if not found
*/
public function getRowFromIdSubDataTable($idSubTable)
{
$idSubTable = (int)$idSubTable;
foreach($this->rows as $row)
{
if($row->getIdSubDataTable() === $idSubTable)
{
return $row;
}
}
return false;
}
/**
* Add a row to the table and rebuild the index if necessary
*
* @param Piwik_DataTable_Row $row to add at the end of the array
*/
public function addRow( Piwik_DataTable_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
{
$this->addSummaryRow(new Piwik_DataTable_Row(array(
Piwik_DataTable_Row::COLUMNS => $row->getColumns()
)));
$this->summaryRow->setColumn('label', self::LABEL_SUMMARY_ROW);
}
else
{
$this->summaryRow->sumRow($row, $enableCopyMetadata = false);
}
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;
}
$this->indexNotUpToDate = false;
}
return $row;
}
/**
* Sets the summary row (a dataTable can have only one summary row)
*
* @param Piwik_DataTable_Row $row
* @return Piwik_DataTable_Row Returns $row.
*/
public function addSummaryRow( Piwik_DataTable_Row $row )
{
$this->summaryRow = $row;
return $row;
}
/**
* Returns the dataTable ID
*
* @return int
*/
public function getId()
{
return $this->currentId;
}
/**
* Adds a new row from a PHP array data structure
*
* @param array $row eg. array(Piwik_DataTable_Row::COLUMNS => array( 'visits' => 13, 'test' => 'toto'),)
*/
public function addRowFromArray( $row )
{
$this->addRowsFromArray(array($row));
}
/**
* Adds a new row a PHP array data structure
*
* @param array $row eg. array('name' => 'google analytics', 'license' => 'commercial')
*/
public function addRowFromSimpleArray( $row )
{
$this->addRowsFromSimpleArray(array($row));
}
/**
* Returns the array of Piwik_DataTable_Row
*
* @return Piwik_DataTable_Row[]
*/
public function getRows()
{
if(is_null($this->summaryRow))
{
return $this->rows;
}
else
{
return $this->rows + array(self::ID_SUMMARY_ROW => $this->summaryRow);
}
}
/**
* Returns the array containing all rows values for the requested column
*
* @param string $name
* @return array
*/
public function getColumn( $name )
{
$columnValues = array();
foreach($this->getRows() as $row)
{
$columnValues[] = $row->getColumn($name);
}
return $columnValues;
}
/**
* Returns an array containing the rows Metadata values
*
* @param string $name Metadata column to return
* @return array
*/
public function getRowsMetadata( $name )
{
$metadataValues = array();
foreach($this->getRows() as $row)
{
$metadataValues[] = $row->getMetadata($name);
}
return $metadataValues;
}
/**
* Returns the number of rows in the table
*
* @return int
*/
public function getRowsCount()
{
if(is_null($this->summaryRow))
{
return count($this->rows);
}
else
{
return count($this->rows) + 1;
}
}
/**
* Returns the first row of the DataTable
*
* @return Piwik_DataTable_Row
*/
public function getFirstRow()
{
if(count($this->rows) == 0)
{
if(!is_null($this->summaryRow))
{
return $this->summaryRow;
}
return false;
}
$row = array_slice($this->rows, 0, 1);
return $row[0];
}
/**
* Returns the last row of the DataTable
*
* @return Piwik_DataTable_Row
*/
public function getLastRow()
{
if(!is_null($this->summaryRow))
{
return $this->summaryRow;
}
if(count($this->rows) == 0)
{
return false;
}
$row = array_slice($this->rows, -1);
return $row[0];
}
/**
* Returns the sum of the number of rows of all the subtables
* + the number of rows in the parent table
*
* @return int
*/
public function getRowsCountRecursive()
{
$totalCount = 0;
foreach($this->rows as $row)
{
if(($idSubTable = $row->getIdSubDataTable()) !== null)
{
$subTable = Piwik_DataTable_Manager::getInstance()->getTable($idSubTable);
$count = $subTable->getRowsCountRecursive();
$totalCount += $count;
}
}
$totalCount += $this->getRowsCount();
return $totalCount;
}
/**
* Delete a given column $name in all the rows
*
* @param string $name
*/
public function deleteColumn( $name )
{
$this->deleteColumns(array($name));
}
public function __sleep()
{
return array('rows', 'parents', 'summaryRow');
}
/**
* Rename a column in all rows
*
* @param string $oldName Old column name
* @param string $newName New column name
*/
public function renameColumn( $oldName, $newName )
{
foreach($this->getRows() as $row)
{
$row->renameColumn($oldName, $newName);
if(($idSubDataTable = $row->getIdSubDataTable()) !== null)
{
Piwik_DataTable_Manager::getInstance()->getTable($idSubDataTable)->renameColumn($oldName, $newName);
}
}
if(!is_null($this->summaryRow))
{
$this->summaryRow->renameColumn($oldName, $newName);
}
}
/**
* Delete columns by name in all rows
*
* @param array $names
* @param bool $deleteRecursiveInSubtables
*/
public function deleteColumns($names, $deleteRecursiveInSubtables = false)
{
foreach($this->getRows() as $row)
{
foreach($names as $name)
{
$row->deleteColumn($name);
}
if(($idSubDataTable = $row->getIdSubDataTable()) !== null)
{
Piwik_DataTable_Manager::getInstance()->getTable($idSubDataTable)->deleteColumns($names, $deleteRecursiveInSubtables);
}
}
if(!is_null($this->summaryRow))
{
foreach($names as $name)
{
$this->summaryRow->deleteColumn($name);
}
}
}
/**
* Deletes the ith row
*
* @param int $id
* @throws Exception if the row $id cannot be found
* @return
*/
public function deleteRow( $id )
{
if($id === self::ID_SUMMARY_ROW)
{
$this->summaryRow = null;
return;
}
if(!isset($this->rows[$id]))
{
throw new Exception("Trying to delete unknown row with idkey = $id");
}
unset($this->rows[$id]);
}
/**
* Deletes all row from offset, offset + limit.
* If limit is null then limit = $table->getRowsCount()
*
* @param int $offset
* @param int $limit
* @return int
*/
public function deleteRowsOffset( $offset, $limit = null )
{
if($limit === 0)
{
return 0;
}
$count = $this->getRowsCount();
if($offset >= $count)
{
return 0;
}
// if we delete until the end, we delete the summary row as well
if( is_null($limit)
|| $limit >= $count )
{
$this->summaryRow = null;
}
if(is_null($limit))
{
$spliced = array_splice($this->rows, $offset);
}
else
{
$spliced = array_splice($this->rows, $offset, $limit);
}
$countDeleted = count($spliced);
return $countDeleted;
}
/**
* Deletes the rows from the list of rows ID
*
* @param array $aKeys ID of the rows to delete
* @throws Exception if any of the row to delete couldn't be found
*/
public function deleteRows( array $aKeys )
{
foreach($aKeys as $key)
{
$this->deleteRow($key);
}
}
/**
* Returns a simple output of the DataTable for easy visualization
* Example: echo $datatable;
*
* @return string
*/
public function __toString()
{
$renderer = new Piwik_DataTable_Renderer_Html();
$renderer->setTable($this);
return (string)$renderer;
}
/**
* Returns true if both DataTable are exactly the same.
* Used in unit tests.
*
* @param Piwik_DataTable $table1
* @param Piwik_DataTable $table2
* @return bool
*/
static public function isEqual(Piwik_DataTable $table1, Piwik_DataTable $table2)
{
$rows1 = $table1->getRows();
$rows2 = $table2->getRows();
$table1->rebuildIndex();
$table2->rebuildIndex();
if($table1->getRowsCount() != $table2->getRowsCount())
{
return false;
}
foreach($rows1 as $row1)
{
$row2 = $table2->getRowFromLabel($row1->getColumn('label'));
if($row2 === false
|| !Piwik_DataTable_Row::isEqual($row1,$row2))
{
return false;
}
}
return true;
}
/**
* The serialization returns a one dimension array containing all the
* serialized DataTable contained in this DataTable.
* We save DataTable in serialized format in the Database.
* Each row of this returned PHP array will be a row in the DB table.
* At the end of the method execution, the dataTable may be truncated (if $maximum* parameters are set).
*
* The keys of the array are very important as they are used to define the DataTable
*
* IMPORTANT: The main table (level 0, parent of all tables) will always be indexed by 0
* even it was created after some other tables.
* It also means that all the parent tables (level 0) will be indexed with 0 in their respective
* serialized arrays. You should never lookup a parent table using the getTable( $id = 0) as it
* won't work.
*
* @throws Exception if an infinite recursion is found (a table row's has a subtable that is one of its parent table)
* @param int $maximumRowsInDataTable If not null, defines the number of rows maximum of the serialized dataTable
* @param int $maximumRowsInSubDataTable If not null, defines the number of rows maximum of the serialized subDataTable
* @param string $columnToSortByBeforeTruncation Column to sort by before truncation
* @return array Serialized arrays
* array( // Datatable level0
* 0 => 'eghuighahgaueytae78yaet7yaetae',
*
* // first Datatable level1
* 1 => 'gaegae gh gwrh guiwh uigwhuige',
*
* //second Datatable level1
* 2 => 'gqegJHUIGHEQjkgneqjgnqeugUGEQHGUHQE',
*
* //first Datatable level3 (child of second Datatable level1 for example)
* 3 => 'eghuighahgaueytae78yaet7yaetaeGRQWUBGUIQGH&QE',
* );
*/
public function getSerialized( $maximumRowsInDataTable = null,
$maximumRowsInSubDataTable = null,
$columnToSortByBeforeTruncation = null )
{
static $depth = 0;
if($depth > self::$maximumDepthLevelAllowed)
{
$depth = 0;
throw new Exception("Maximum recursion level of ".self::$maximumDepthLevelAllowed. " reached. Maybe you have set a DataTable_Row with an associated DataTable belonging already to one of its parent tables?");
}
if( !is_null($maximumRowsInDataTable) )
{
$this->filter('AddSummaryRow',
array( $maximumRowsInDataTable - 1,
Piwik_DataTable::LABEL_SUMMARY_ROW,
$columnToSortByBeforeTruncation)
);
}
// For each row, get the serialized row
// If it is associated to a sub table, get the serialized table recursively ;
// but returns all serialized tables and subtable in an array of 1 dimension
$aSerializedDataTable = array();
foreach($this->rows as $row)
{
if(($idSubTable = $row->getIdSubDataTable()) !== null)
{
$subTable = Piwik_DataTable_Manager::getInstance()->getTable($idSubTable);
$depth++;
$aSerializedDataTable = $aSerializedDataTable + $subTable->getSerialized( $maximumRowsInSubDataTable, $maximumRowsInSubDataTable, $columnToSortByBeforeTruncation );
$depth--;
}
}
// we load the current Id of the DataTable
$forcedId = $this->getId();
// if the datatable is the parent we force the Id at 0 (this is part of the specification)
if($depth == 0)
{
$forcedId = 0;
}
// we then serialize the rows and store them in the serialized dataTable
$addToRows = array( self::ID_SUMMARY_ROW => $this->summaryRow );
if ($this->parents && Piwik_Config::getInstance()->General['enable_archive_parents_of_datatable'])
{
$addToRows[self::ID_PARENTS] = $this->parents;
}
$aSerializedDataTable[$forcedId] = serialize($this->rows + $addToRows);
foreach($this->rows as &$row)
{
$row->cleanPostSerialize();
}
return $aSerializedDataTable;
}
/**
* Load a serialized string of a datatable.
*
* Does not load recursively all the sub DataTable.
* They will be loaded only when requesting them specifically.
*
* The function creates all the necessary DataTable_Row
*
* @param string $stringSerialized string of serialized datatable
* @throws Exception
*/
public function addRowsFromSerializedArray( $stringSerialized )
{
$serialized = unserialize($stringSerialized);
if($serialized === false)
{
throw new Exception("The unserialization has failed!");
}
$this->addRowsFromArray($serialized);
}
/**
* Loads the DataTable from a PHP array data structure
*
* @param array $array Array with the following structure
* array(
* // row1
* array(
* Piwik_DataTable_Row::COLUMNS => array( col1_name => value1, col2_name => value2, ...),
* Piwik_DataTable_Row::METADATA => array( metadata1_name => value1, ...), // see Piwik_DataTable_Row
* ),
* // row2
* array( ... ),
* )
*/
public function addRowsFromArray( $array )
{
foreach($array as $id => $row)
{
if($id == self::ID_PARENTS)
{
$this->parents = $row;
continue;
}
if(is_array($row))
{
$row = new Piwik_DataTable_Row($row);
}
if($id == self::ID_SUMMARY_ROW)
{
$this->summaryRow = $row;
}
else
{
$this->addRow($row);
}
}
}
/**
* Loads the data from a simple php array.
* Basically maps a simple multidimensional php array to a DataTable.
* Not recursive (if a row contains a php array itself, it won't be loaded)
*
* @param array $array Array with the simple structure:
* array(
* array( col1_name => valueA, col2_name => valueC, ...),
* array( col1_name => valueB, col2_name => valueD, ...),
* )
* @throws Exception
* @return
*/
public function addRowsFromSimpleArray( $array )
{
if(count($array) === 0)
{
return;
}
// we define an exception we may throw if at one point we notice that we cannot handle the data structure
$e = new Exception(" Data structure returned is not convertible in the requested format.".
" Try to call this method with the parameters '&format=original&serialize=1'".
"; you will get the original php data structure serialized.".
" The data structure looks like this: \n \$data = " . var_export($array, true) . "; ");
// first pass to see if the array has the structure
// array(col1_name => val1, col2_name => val2, etc.)
// with val* that are never arrays (only strings/numbers/bool/etc.)
// if we detect such a "simple" data structure we convert it to a row with the correct columns' names
$thisIsNotThatSimple = false;
foreach($array as $columnName => $columnValue )
{
if(is_array($columnValue) || is_object($columnValue))
{
$thisIsNotThatSimple = true;
break;
}
}
if($thisIsNotThatSimple === false)
{
// case when the array is indexed by the default numeric index
if( array_keys($array) == array_keys(array_fill(0, count($array), true)) )
{
foreach($array as $row)
{
$this->addRow( new Piwik_DataTable_Row( array( Piwik_DataTable_Row::COLUMNS => array($row) ) ) );
}
}
else
{
$this->addRow( new Piwik_DataTable_Row( array( Piwik_DataTable_Row::COLUMNS => $array ) ) );
}
// we have converted our simple array to one single row
// => we exit the method as the job is now finished
return;
}
foreach($array as $key => $row)
{
// stuff that looks like a line
if(is_array($row))
{
/**
* We make sure we can convert this PHP array without losing information.
* We are able to convert only simple php array (no strings keys, no sub arrays, etc.)
*
*/
// if the key is a string it means that some information was contained in this key.
// it cannot be lost during the conversion. Because we are not able to handle properly
// this key, we throw an explicit exception.
if(is_string($key))
{
throw $e;
}
// if any of the sub elements of row is an array we cannot handle this data structure...
foreach($row as $subRow)
{
if(is_array($subRow))
{
throw $e;
}
}
$row = new Piwik_DataTable_Row( array( Piwik_DataTable_Row::COLUMNS => $row ) );
}
// other (string, numbers...) => we build a line from this value
else
{
$row = new Piwik_DataTable_Row( array( Piwik_DataTable_Row::COLUMNS => array($key => $row)) );
}
$this->addRow($row);
}
}
/**
* Rewrites the input $array
* array (
* LABEL => array(col1 => X, col2 => Y),
* LABEL2 => array(col1 => X, col2 => Y),
* )
* to the structure
* array (
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL, col1 => X, col2 => Y)),
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL2, col1 => X, col2 => Y)),
* )
*
* It also works with array having only one value per row, eg.
* array (
* LABEL => X,
* LABEL2 => Y,
* )
* would be converted to the structure
* array (
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL, 'value' => X)),
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL2, 'value' => Y)),
* )
*
* The optional parameter $subtablePerLabel is an array of subTable associated to the rows of the $array
* For example if $subtablePerLabel is given
* array(
* LABEL => #Piwik_DataTable_ForLABEL,
* LABEL2 => #Piwik_DataTable_ForLABEL2,
* )
*
* the $array would become
* array (
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL, col1 => X, col2 => Y),
* Piwik_DataTable_Row::DATATABLE_ASSOCIATED => #ID DataTable For LABEL
* ),
* array( Piwik_DataTable_Row::COLUMNS => array('label' => LABEL2, col1 => X, col2 => Y)
* Piwik_DataTable_Row::DATATABLE_ASSOCIATED => #ID2 DataTable For LABEL2
* ),
* )
*
* @param array $array See method description
* @param array|null $subtablePerLabel See method description
*/
public function addRowsFromArrayWithIndexLabel( $array, $subtablePerLabel = null)
{
$cleanRow = array();
foreach($array as $label => $row)
{
if(!is_array($row))
{
$row = array('value' => $row);
}
$cleanRow[Piwik_DataTable_Row::DATATABLE_ASSOCIATED] = null;
// we put the 'label' column first as it looks prettier in API results
$cleanRow[Piwik_DataTable_Row::COLUMNS] = array('label' => $label) + $row;
if(!is_null($subtablePerLabel)
// some rows of this table don't have subtables
// (for example case of campaigns without keywords)
&& isset($subtablePerLabel[$label])
)
{
$cleanRow[Piwik_DataTable_Row::DATATABLE_ASSOCIATED] = $subtablePerLabel[$label];
}
$this->addRow( new Piwik_DataTable_Row($cleanRow) );
}
}
/**
* Set the array of parent ids
*
* @param array $parents
*/
public function setParents($parents)
{
$this->parents = $parents;
}
/**
* Get parents
*
* @return array of all parents, root level first
*/
public function getParents() {
if ($this->parents == null)
{
return array();
}
return $this->parents;
}
/**
* Sets the maximum nesting level to at least a certain value. If the current value is
* greater than the supplied level, the maximum nesting level is not changed.
*
* @param int $atLeastLevel
*/
static public function setMaximumDepthLevelAllowedAtLeast( $atLeastLevel )
{
self::$maximumDepthLevelAllowed = max($atLeastLevel, self::$maximumDepthLevelAllowed);
if(self::$maximumDepthLevelAllowed < 1) {
self::$maximumDepthLevelAllowed = 1;
}
}
/**
* Returns all table metadata.
*
* @return array
*/
public function getAllTableMetadata()
{
return $this->metadata;
}
/**
* Returns metadata by name.
*
* @param string $name The metadata name.
* @return mixed
*/
public function getMetadata( $name )
{
if (!isset($this->metadata[$name]))
{
return false;
}
return $this->metadata[$name];
}
/**
* Sets a metadata value by name.
*
* @param string $name The metadata name.
* @param mixed $value
*/
public function setMetadata( $name, $value )
{
$this->metadata[$name] = $value;
}
/**
* Sets the maximum number of rows allowed in this datatable (including the summary
* row). If adding more then the allowed number of rows is attempted, the extra
* rows are added to the summary row.
*
* @param int|null $maximumAllowedRows
*/
public function setMaximumAllowedRows( $maximumAllowedRows )
{
$this->maximumAllowedRows = $maximumAllowedRows;
}
/**
* Traverses a DataTable tree using an array of labels and returns the row
* it finds or false if it cannot find one, and the number of segments of
* the path successfully walked.
*
* If $missingRowColumns is supplied, the specified path is created. When
* a subtable is encountered w/o the queried label, a new row is created
* with the label, and a subtable is added to the row.
*
* @param array $path The path to walk. An array of label values.
* @param array|false $missingRowColumns
* The default columns to use when creating new arrays.
* If this parameter is supplied, new rows will be
* created if labels cannot be found.
* @param int $maxSubtableRows The maximum number of allowed rows in new
* subtables.
* @return array First element is the found row or false. Second element is
* the number of path segments walked. If a row is found, this
* will be == to count($path). Otherwise, it will be the index
* of the path segment that we could not find.
*/
public function walkPath( $path, $missingRowColumns = false, $maxSubtableRows = 0 )
{
$pathLength = count($path);
$table = $this;
$next = false;
for ($i = 0; $i < $pathLength; ++$i)
{
$segment = $path[$i];
$next = $table->getRowFromLabel($segment);
if ($next === false)
{
// if there is no table to advance to, and we're not adding missing rows, return false
if ($missingRowColumns === false)
{
return array(false, $i);
}
else // if we're adding missing rows, add a new row
{
$row = new Piwik_DataTable_Row_DataTableSummary();
$row->setColumns(array('label' => $segment) + $missingRowColumns);
$next = $table->addRow($row);
if ($next !== $row) // if the row wasn't added, the table is full
{
// Summary row, has no metadata
$next->deleteMetadata();
return array($next, $i);
}
}
}
$table = $next->getSubtable();
if ($table === false)
{
// if the row has no table (and thus no child rows), and we're not adding
// missing rows, return false
if ($missingRowColumns === false)
{
return array(false, $i);
}
else if ($i != $pathLength - 1) // create subtable if missing, but only if not on the last segment
{
$table = new Piwik_DataTable();
$table->setMaximumAllowedRows($maxSubtableRows);
$next->setSubtable($table);
// Summary row, has no metadata
$next->deleteMetadata();
}
}
}
return array($next, $i);
}
/**
* Returns a new DataTable that contains the rows of each of this table's
* subtables.
*
* @return Piwik_DataTable
*/
public function mergeSubtables()
{
$result = new Piwik_DataTable();
foreach ($this->getRows() as $row)
{
$subtable = $row->getSubtable();
if ($subtable !== false)
{
$result->addRowsFromArray($subtable->getRows());
}
}
return $result;
}
/**
* Returns a new DataTable created with data from a 'simple' array.
*
* @param array $array
* @return Piwik_DataTable
*/
public static function makeFromSimpleArray( $array )
{
$dataTable = new Piwik_DataTable();
$dataTable->addRowsFromSimpleArray($array);
return $dataTable;
}
}
|