summaryrefslogtreecommitdiff
path: root/framework/Util/TLogRouter.php
blob: 591bd2f6078cecd308fc67115fa586be15db8b21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
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
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
<?php
/**
 * TLogRouter, TLogRoute, TFileLogRoute, TEmailLogRoute class file
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Brad Anderson <javalizard@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2010 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Id$
 * @package System.Util
 */

Prado::using('System.Data.TDbConnection');

/**
 * TLogRouter class.
 *
 * TLogRouter manages routes that record log messages in different media different ways.
 * For example, a file log route {@link TFileLogRoute} records log messages
 * in log files. An email log route {@link TEmailLogRoute} sends log messages
 * to email addresses.
 *
 * Log routes may be configured in application or page folder configuration files
 * or an external configuration file specified by {@link setConfigFile ConfigFile}.
 * The format is as follows,
 * <code>
 *   <route class="TFileLogRoute" Categories="System.Web.UI" Levels="Warning" Roles="developer,administrator,other" Active="false" />
 *   <route class="TEmailLogRoute" Categories="Application" Levels="Fatal" Emails="admin@pradosoft.com" />
 * </code>
 * PHP configuration style:
 * <code>
 * 
 * </code>
 * You can specify multiple routes with different filtering conditions and different
 * targets, even if the routes are of the same type.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Carl G. Mathisen <carlgmathisen@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */
class TLogRouter extends TModule
{
	/**
	 * @var array list of routes available
	 */
	private $_routes=array();
	/**
	 * @var array list of routes needed to be logged before the page flush
	 */
	private $_preroutes=array();
	/**
	 * @var string external configuration file
	 */
	private $_configFile=null;
	/**
	 * @var boolean whether to do any routes
	 */
	private $_active=true;
	
	
	
	/**
	 * Initializes this module.
	 * This method is required by the IModule interface.
	 * @param mixed configuration for this module, can be null
	 * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid.
	 */
	public function init($config)
	{
		parent::init($config);
		
		if($this->_configFile!==null)
		{
 			if(is_file($this->_configFile))
 			{
				if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP)
				{
					$phpConfig = include $this->_configFile;
					$this->loadConfig($phpConfig);
				}
				else
				{
					$dom=new TXmlDocument;
					$dom->loadFromFile($this->_configFile);
					$this->loadConfig($dom);
				}
			}
			else
				throw new TConfigurationException('logrouter_configfile_invalid',$this->_configFile);
		}
		$this->loadConfig($config);

		// This is needed for FirePhp because it outputs headers
		$this->getApplication()->attachEventHandler('onPreFlushOutput',array($this,'collectLogsPreFlush'));
		$this->getApplication()->attachEventHandler('OnEndRequest',array($this,'collectLogs'));
	}

	/**
	 * Loads configuration from an XML element or PHP array
	 * @param mixed configuration node
	 * @throws TConfigurationException if log route class or type is not specified
	 */
	private function loadConfig($config)
	{
		if(is_array($config))
		{
			if(isset($config['routes']) && is_array($config['routes']))
			{
				foreach($config['routes'] as $route)
				{
					$properties = isset($route['properties'])?$route['properties']:array();
					if(!isset($route['class']))
						throw new TConfigurationException('logrouter_routeclass_required');
					if(isset($properties['disabled']) && $properties['disabled'])
						continue;
					$route=Prado::createComponent($route['class']);
					if(!($route instanceof TLogRoute))
						throw new TConfigurationException('logrouter_routetype_invalid');
					
					$this->_routes[]=$route;
					if($route instanceof IHeaderRoute)
						$this->_preroutes[]=$route;
					
					try {
						foreach($properties as $name=>$value)
							$route->setSubproperty($name,$value);
						$route->init($route);
					} catch(Exception $e) {
						$route->InitError = $e;
					}
				}
			}
		}
		else
		{
			foreach($config->getElementsByTagName('route') as $routeConfig)
			{
				$properties=$routeConfig->getAttributes();
				if(($disabled=$properties->remove('disabled'))!==null)
					continue;
				if(($class=$properties->remove('class'))===null)
					throw new TConfigurationException('logrouter_routeclass_required');
				$route=Prado::createComponent($class);
				if(!($route instanceof TLogRoute))
					throw new TConfigurationException('logrouter_routetype_invalid');
					
				$this->_routes[]=$route;
				if($route instanceof IHeaderRoute)
					$this->_preroutes[]=$route;
				
				try {
					foreach($properties as $name=>$value)
						$route->setSubproperty($name,$value);
					$route->init($routeConfig);
				} catch(Exception $e) {
					$route->InitError = $e;
				}
			}
		}
	}
	
	/**
	 * This returns the installed routes
	 * @return array of TLogRoute
	 */
	public function getRoutes() { return $this->_routes; }

	/**
	 * Adds a TLogRoute instance to the log router.  If a log route implements {@link IHeaderRoute}
	 * then it will get its log route data just before the page is written (b/c it needs that for the headers)
	 * 
	 * @param TLogRoute $route 
	 * @throws TInvalidDataTypeException if the route object is invalid
	 */
	public function addRoute($route)
	{
		if(!($route instanceof TLogRoute))
			throw new TInvalidDataTypeException('logrouter_routetype_invalid');
		$this->_routes[]=$route;
		if($route instanceof IHeaderRoute)
			$this->_preroutes[]=$route;
		$route->init($this);
	}

	/**
	 * @return string external configuration file. Defaults to null.
	 */
	public function getConfigFile()
	{
		return $this->_configFile;
	}

	/**
	 * @return boolean whether the TLogRouter is active or not.
	 */
	public function getActive()
	{
		return $this->_active;
	}

	/**
	 * @param boolean tells the object whether it's active or not.
	 */
	public function setActive($v)
	{
		$this->_active = TPropertyValue::ensureBoolean($v);
	}

	/**
	 * @param string external configuration file in namespace format. The file
	 * must be suffixed with '.xml'.
	 * @throws TConfigurationException if the file is invalid.
	 */
	public function setConfigFile($value)
	{
		if(($this->_configFile=Prado::getPathOfNamespace($value,$this->getApplication()->getConfigurationFileExt()))===null)
			throw new TConfigurationException('logrouter_configfile_invalid',$value);
	}

	/**
	 * Collects log messages from a logger.
	 * This method is an event handler to the application's onPreFlush event.
	 * Only pre flush routes get this treatment.
	 * @param mixed event parameter
	 */
	public function collectLogsPreFlush($param) {
		if(!$this->_active) return;
		
		$logger=Prado::getLogger();
		foreach($this->_preroutes as $route)
			$route->collectLogs($logger);
	}

	/**
	 * Collects log messages from a logger.
	 * This method is an event handler to the application's EndRequest event.
	 * Only post flush routes get this treatment.
	 * @param mixed event parameter
	 */
	public function collectLogs($param)
	{
		if(!$this->_active) return;
		
		$logger=Prado::getLogger();
		foreach($this->_routes as $route)
			if(!in_array($route, $this->_preroutes))
				$route->collectLogs($logger);
	}
}


/**
 * IHeaderRoute interface.
 *
 * This is used for registering log routers that output to the header so it can be routed before the page flush.
 *
 * @author Brad Anderson <javalizard@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */ 

interface IHeaderRoute {
}

/**
 * TLogRoute class.
 *
 * TLogRoute is the base class for all log route classes.
 * A log route object retrieves log messages from a logger and sends it
 * somewhere, such as files, emails.
 * The messages being retrieved may be filtered first before being sent
 * to the destination. The filters include log level filter and log category filter.
 *
 * To specify level filter, set {@link setLevels Levels} property,
 * which takes a string of comma-separated desired level names (e.g. 'Error, Debug').
 * To specify category filter, set {@link setCategories Categories} property,
 * which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO').
 *
 * Level filter and category filter are combinational, i.e., only messages
 * satisfying both filter conditions will they be returned.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */
abstract class TLogRoute extends TApplicationComponent
{
	/**
	 * @var array lookup table for level names
	 */
	protected static $_levelNames=array(
		TLogger::DEBUG=>'Debug',
		TLogger::INFO=>'Info',
		TLogger::NOTICE=>'Notice',
		TLogger::WARNING=>'Warning',
		TLogger::ERROR=>'Error',
		TLogger::ALERT=>'Alert',
		TLogger::FATAL=>'Fatal'
	);
	/**
	 * @var array lookup table for level values
	 */
	protected static $_levelValues=array(
		'debug'=>TLogger::DEBUG,
		'info'=>TLogger::INFO,
		'notice'=>TLogger::NOTICE,
		'warning'=>TLogger::WARNING,
		'error'=>TLogger::ERROR,
		'alert'=>TLogger::ALERT,
		'fatal'=>TLogger::FATAL
	);
	/**
	 * @var string the id of the route
	 */
	private $_id=null;
	/**
	 * @var string the name of the route
	 */
	private $_name=null;
	/**
	 * @var integer log level filter (bits)
	 */
	private $_levels=null;
	/**
	 * @var array log category filter
	 */
	private $_categories=null;
	/**
	 * @var array log controls filter
	 */
	private $_controls=null;
	/**
	 * @var array role filter
	 */
	private $_roles=null;

	/**
	 * @var int|string the reference to the hit metadata.  This is a transient property per page hit.
	 */
	private $_metaid=null;
	/**
	 * @var int the user id of the hit.  This is a transient property per page hit.
	 */
	private $_userid=null;
	
	/**
	 * @var boolean whether this is an active route or not
	 */
	private $_active=true;
	/**
	 * $var Exception any problems on the loading of the module
	 */
	private $_error=null;
	/**
	 * Initializes the route.
	 * @param TXmlElement configurations specified in {@link TLogRouter}.
	 */
	public function init($config)
	{
		if(is_array($config)) {
			if(isset($config['id']))
				$this->_id = $config['id'];
			if(isset($config['name']))
				$this->Name = $config['name'];
			if(isset($config['active']))
				$this->Active = $config['active'];
			if(isset($config['roles']))
				$this->Roles = $config['roles'];
			if(isset($config['categories']))
				$this->Categories = $config['categories'];
			if(isset($config['levels']))
				$this->Levels = $config['levels'];
			if(isset($config['controls']))
				$this->Controls = $config['controls'];
		}
	}
	

	/**
	 * @return string the id of the route
	 */
	public function getId()
	{
		return $this->_id;
	}

	/**
	 * @param The id of the route.
	 */
	public function setId($id)
	{
		$this->_id = $id;
	}

	/**
	 * @return string the name of the route
	 */
	public function getName()
	{
		return $this->_name;
	}

	/**
	 * @param The name of the route.
	 */
	public function setName($name)
	{
		$this->_name = $name;
	}

	/**
	 * @return boolean true if the route is active
	 */
	public function getActive()
	{
		return $this->_active;
	}

	/**
	 * @param boolean sets the object to active or not.
	 */
	public function setActive($v)
	{
		$this->_active = TPropertyValue::ensureBoolean($v);
	}

	/**
	 * @return Exception this returns any errors the log route has
	 */
	public function getInitError()
	{
		return $this->_error;
	}

	/**
	 * @param mixed this sets the errors that the log route may have
	 */
	public function setInitError($v)
	{
		$this->_error = $v;
	}

	/**
	 * @return string this returns the meta data id associated with the route
	 */
	public function getMetaId()
	{
		return $this->_metaid;
	}

	/**
	 * @param string this sets the meta data id associated with the route.
	 */
	public function setMetaId($v)
	{
		$this->_metaid = $v;
	}


	/**
	 * @return string this returns the user id associated with the route.
	 */
	public function getUserId()
	{
		return $this->_userid;
	}

	/**
	 * @return string this sets the user id associated with the route.
	 */
	public function setUserId($v)
	{
		$this->_userid = $v;
	}

	/**
	 * @return array log roles filter
	 */
	public function getRoles()
	{
		return $this->_roles;
	}

	/**
	 * @param array|string The roles that this log router is attached to.
	 */
	public function setRoles($roles)
	{
		if(is_array($roles))
			$this->_roles=$roles;
		else
		{
			$this->_roles=array();
			$roles=strtolower($roles);
			foreach(explode(',',$roles) as $role)
			{
				$role=trim($role);
				if(!in_array($role, $this->_roles))
					$this->_roles[] = $role;
			}
		}
	}

	/**
	 * @return integer log level filter
	 */
	public function getLevels()
	{
		return $this->_levels;
	}

	/**
	 * @param integer|string integer log level filter (in bits). If the value is
	 * a string, it is assumed to be comma-separated level names. Valid level names
	 * include 'Debug', 'Info', 'Notice', 'Warning', 'Error', 'Alert' and 'Fatal'.
	 */
	public function setLevels($levels)
	{
		if(is_integer($levels))
			$this->_levels=$levels;
		else
		{
			$this->_levels=null;
			if(is_string($levels))
				$levels = explode(',',strtolower($levels));
			
			foreach($levels as $level)
			{
				$level=trim($level);
				if(isset(self::$_levelValues[$level]))
					$this->_levels|=self::$_levelValues[$level];
			}
		}
	}

	/**
	 * @return array list of categories to be looked for
	 */
	public function getCategories()
	{
		return $this->_categories;
	}

	/**
	 * @param array|string list of categories to be looked for. If the value is a string,
	 * it is assumed to be comma-separated category names.
	 */
	public function setCategories($categories)
	{
		if(is_array($categories))
			$this->_categories=$categories;
		else
		{
			$this->_categories=array();
			foreach(explode(',',$categories) as $category)
			{
				if(($category=trim($category))!=='')
					$this->_categories[]=$category;
			}
		}
	}

	/**
	 * @return array list of controls to be looked for
	 */
	public function getControls()
	{
		return $this->_controls;
	}

	/**
	 * @param array|string list of controls to be looked for. If the value is a string,
	 * it is assumed to be comma-separated control client ids.
	 */
	public function setControls($controls)
	{
		if(is_array($controls))
			$this->_controls=$controls;
		else
		{
			$this->_controls=array();
			foreach(explode(',',$controls) as $control)
			{
				if(($control=trim($control))!=='')
					$this->_controls[]=$control;
			}
		}
	}

	/**
	 * @param integer level value
	 * @return string level name
	 */
	protected function getLevelName($level)
	{
		return isset(self::$_levelNames[$level])?self::$_levelNames[$level]:'Unknown';
	}

	/**
	 * @param string level name
	 * @return integer level value
	 */
	protected function getLevelValue($level)
	{
		return isset(self::$_levelValues[$level])?self::$_levelValues[$level]:0;
	}

	/**
	 * Formats a log message given different fields.
	 * @param string message content
	 * @param integer message level
	 * @param string message category
	 * @param integer timestamp
	 * @return string formatted message
	 */
	protected function formatLogMessage($message,$level,$category,$time, $memory)
	{
		if(!$this->MetaId)
			$this->MetaId = $this->Request->UserHostAddress;
		return '[metaid: ' .$this->MetaId.'] ' . @date('M d H:i:s',$time).' [Memory: '.$memory.'] ['.$this->getLevelName($level).'] ['.$category.'] '.$message."\n";
	}

	/**
	 * Retrieves log messages from logger to log route specific destination.
	 * @param TLogger logger instance
	 */
	public function collectLogs(TLogger $logger)
	{
		// if not active or roles don't match, end function
		if(!$this->_active || ($this->_roles && !array_intersect($this->_roles, $this->User->Roles))) return;
		
		Prado::trace('Routing Logs: '.get_class($this) . '->id='.$this->id,'System.Util.TLogRouter');
		
		$logs=$logger->getLogs($this->getLevels(),$this->getCategories(),$this->getControls());
		if(!empty($logs))
			$this->processLogs($logs);
	}
	
	/**
	 *	@return string this is the xml representation of the route
	 */
	public function toXml() {
		$xml = '<route ' . $this->encodeId() . $this->encodeName() . $this->encodeClass() . $this->encodeLevels() . 
			$this->encodeCategories() . $this->encodeRoles() . $this->encodeControls() . '/>';
		return $xml;
	}
	
	/**
	 *	@return string this encodes the id of the route as an xml attribute
	 */
	protected function encodeId() {
		return 'id="'. $this->_id .'" ';
	}
	
	/**
	 *	@return string this encodes the name of the route as an xml attribute
	 */
	protected function encodeName() {
		$active = '';
		if(!$this->_active) $active = 'active="'. ($this->_active?'true':'false') .'" ';
		return 'name="'. $this->_name .'" ' . $active;
	}
	
	/**
	 *	@return string this encodes the class of the route as an xml attribute
	 */
	protected function encodeClass() {
		return 'class="'. get_class($this) .'" ';
	}
	
	/**
	 *	@return string this encodes the levels of the route as an xml attribute
	 */
	protected function encodeLevels() {
		if(!$this->_levels) return '';
		$levels = array();
		foreach(self::$_levelNames as $level => $name)
			if($level & $this->_levels)
				$levels[] = strtolower($name);
		return 'levels="'. implode(',', $levels) .'" ';
	}
	
	/**
	 *	@return string this encodes the categories of the route as an xml attribute
	 */
	protected function encodeCategories() {
		if(!$this->_categories) return '';
		return 'categories="'. implode(',', $this->_categories) .'" ';
	}
	
	/**
	 *	@return string this encodes the roles of the route as an xml attribute
	 */
	protected function encodeRoles() {
		if(!$this->_roles) return '';
		return 'roles="'. implode(',', $this->_roles) .'" ';
	}
	
	/**
	 *	@return string this encodes the controls of the route as an xml attribute
	 */
	protected function encodeControls() {
		if(!$this->_roles) return '';
		return 'controls="'. implode(',', $this->_controls) .'" ';
	}

	/**
	 * Processes log messages and sends them to specific destination.
	 * Derived child classes must implement this method.
	 * @param array list of messages.  Each array elements represents one message
	 * with the following structure:
	 * array(
	 *   [0] => message
	 *   [1] => level
	 *   [2] => category
	 *   [3] => timestamp
	 *   [4] => memory in bytes
	 *   [5] => control);
	 */
	abstract protected function processLogs($logs);
}

/**
 * TFileLogRoute class.
 *
 * TFileLogRoute records log messages in files.
 * The log files are stored under {@link setLogPath LogPath} and the file name
 * is specified by {@link setLogFile LogFile}. If the size of the log file is
 * greater than {@link setMaxFileSize MaxFileSize} (in kilo-bytes), a rotation
 * is performed, which renames the current log file by suffixing the file name
 * with '.1'. All existing log files are moved backwards one place, i.e., '.2'
 * to '.3', '.1' to '.2'. The property {@link setMaxLogFiles MaxLogFiles}
 * specifies how many files to be kept.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */
class TFileLogRoute extends TLogRoute
{
	/**
	 * @var integer maximum log file size
	 */
	private $_maxFileSize=512; // in KB
	/**
	 * @var integer number of log files used for rotation
	 */
	private $_maxLogFiles=2;
	/**
	 * @var string directory storing log files
	 */
	private $_logPath=null;
	/**
	 * @var string original directory set for the log files so it can be recreated
	 */
	private $_logPradoPath=null;
	/**
	 * @var string log file name
	 */
	private $_logFile='prado.log';

	/**
	 * Initializes the route.
	 * @param TXmlElement configurations specified in {@link TLogRouter}.
	 * @throws TConfigurationException if {@link getSentFrom SentFrom} is empty and
	 * 'sendmail_from' in php.ini is also empty.
	 */
	public function init($config)
	{
		parent::init($config);
		
		if(is_array($config)) {
			if(isset($config['logfile']))
				$this->LogFile = $config['logfile'];
			if(isset($config['logpath']))
				$this->LogPath = $config['logpath'];
			if(isset($config['maxfilesize']))
				$this->MaxFileSize = $config['maxfilesize'];
			if(isset($config['maxfilesize']))
				$this->MaxLogFiles = $config['maxlogfiles'];
		}
	}
	
	/**
	 *	@return string this encodes the TFileLogRoute as a string
	 */
	public function toXml() {
		$xml = '<route ' .$this->encodeId(). $this->encodeName().$this->encodeClass() . $this->encodeLevels() . 
			$this->encodeCategories() . $this->encodeControls() . $this->encodeRoles() . $this->encodeMaxFileSize(). 
			$this->encodeMaxLogFiles(). $this->encodeLogPath().$this->encodeLogFile().'/>';
		return $xml;
	}
	
	/**
	 *	@return string this encodes the maxfilesize of the route as an xml attribute
	 */
	protected function encodeMaxFileSize() {
		if(!$this->MaxFileSize) return '';
		return 'maxfilesize="'. addslashes($this->MaxFileSize) .'" ';
	}
	
	/**
	 *	@return string this encodes the maxlogfiles of the route as an xml attribute
	 */
	protected function encodeMaxLogFiles() {
		if(!$this->MaxFileSize) return '';
		return 'maxlogfiles="'. addslashes($this->MaxLogFiles) .'" ';
	}
	
	/**
	 *	@return string this encodes the logpath of the route as an xml attribute
	 */
	protected function encodeLogPath() {
		if(!$this->LogPath) return '';
		return 'logpath="'. addslashes($this->_logPradoPath) .'" ';
	}
	
	/**
	 *	@return string this encodes the logfile of the route as an xml attribute
	 */
	protected function encodeLogFile() {
		if(!$this->LogFile) return '';
		return 'logfile="'. addslashes($this->LogFile) .'" ';
	}
	
	
	/**
	 * @return string directory storing log files. Defaults to application runtime path.
	 */
	public function getLogPath()
	{
		if($this->_logPath===null)
			$this->_logPath=$this->getApplication()->getRuntimePath();
		return $this->_logPath;
	}

	/**
	 * @param string directory (in namespace format) storing log files.
	 * @throws TConfigurationException if log path is invalid
	 */
	public function setLogPath($value)
	{
		$this->_logPradoPath = $value;
		if(($this->_logPath=Prado::getPathOfNamespace($value))===null || !is_dir($this->_logPath) || !is_writable($this->_logPath))
			throw new TConfigurationException('filelogroute_logpath_invalid',$value);
	}

	/**
	 * @return string log file name. Defaults to 'prado.log'.
	 */
	public function getLogFile()
	{
		return $this->_logFile;
	}

	/**
	 * @param string log file name
	 */
	public function setLogFile($value)
	{
		$this->_logFile=$value;
	}

	/**
	 * @return integer maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB).
	 */
	public function getMaxFileSize()
	{
		return $this->_maxFileSize;
	}

	/**
	 * @param integer maximum log file size in kilo-bytes (KB).
	 * @throws TInvalidDataValueException if the value is smaller than 1.
	 */
	public function setMaxFileSize($value)
	{
		$this->_maxFileSize=TPropertyValue::ensureInteger($value);
		if($this->_maxFileSize<=0)
			throw new TInvalidDataValueException('filelogroute_maxfilesize_invalid');
	}

	/**
	 * @return integer number of files used for rotation. Defaults to 2.
	 */
	public function getMaxLogFiles()
	{
		return $this->_maxLogFiles;
	}

	/**
	 * @param integer number of files used for rotation.
	 */
	public function setMaxLogFiles($value)
	{
		$this->_maxLogFiles=TPropertyValue::ensureInteger($value);
		if($this->_maxLogFiles<1)
			throw new TInvalidDataValueException('filelogroute_maxlogfiles_invalid');
	}

	/**
	 * Saves log messages in files.
	 * @param array list of log messages
	 */
	protected function processLogs($logs)
	{
		$logFile=$this->getLogPath().DIRECTORY_SEPARATOR.$this->getLogFile();
		if(@filesize($logFile)>$this->_maxFileSize*1024)
			$this->rotateFiles();
		foreach($logs as $log)
			error_log($this->formatLogMessage($log[0],$log[1],$log[2],$log[3],$log[4]),3,$logFile);
	}

	/**
	 * Rotates log files.
	 */
	protected function rotateFiles()
	{
		$file=$this->getLogPath().DIRECTORY_SEPARATOR.$this->getLogFile();
		for($i=$this->_maxLogFiles;$i>0;--$i)
		{
			$rotateFile=$file.'.'.$i;
			if(is_file($rotateFile))
			{
				if($i===$this->_maxLogFiles)
					unlink($rotateFile);
				else
					rename($rotateFile,$file.'.'.($i+1));
			}
		}
		if(is_file($file))
			rename($file,$file.'.1');
	}
}

/**
 * TEmailLogRoute class.
 *
 * TEmailLogRoute sends selected log messages to email addresses.
 * The target email addresses may be specified via {@link setEmails Emails} property.
 * Optionally, you may set the email {@link setSubject Subject} and the
 * {@link setSentFrom SentFrom} address.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */
class TEmailLogRoute extends TLogRoute
{
	/**
	 * Regex pattern for email address.
	 */
	const EMAIL_PATTERN='/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/';
	/**
	 * Default email subject.
	 */
	const DEFAULT_SUBJECT='Prado Application Log';
	/**
	 * @var array list of destination email addresses.
	 */
	private $_emails=array();
	/**
	 * @var string email subject
	 */
	private $_subject='';
	/**
	 * @var string email sent from address
	 */
	private $_from='';

	/**
	 * Initializes the route.
	 * @param TXmlElement configurations specified in {@link TLogRouter}.
	 * @throws TConfigurationException if {@link getSentFrom SentFrom} is empty and
	 * 'sendmail_from' in php.ini is also empty.
	 */
	public function init($config)
	{
		parent::init($config);
		
		if(is_array($config)) {
			if(isset($config['emails']))
				$this->Emails = $config['emails'];
			if(isset($config['subject']))
				$this->Subject = $config['subject'];
			if(isset($config['from']))
				$this->SentFrom = $config['from'];
		}
		
		if($this->_from==='')
			$this->_from=ini_get('sendmail_from');
		if($this->_from==='')
			throw new TConfigurationException('emaillogroute_sentfrom_required');
	}
	
	/**
	 *	@return string this encodes the TEmailLogRoute as an xml element
	 */
	public function toXml() {
		$xml = '<route ' .$this->encodeId(). $this->encodeName().$this->encodeClass() . $this->encodeLevels() . 
			$this->encodeCategories() . $this->encodeControls() . $this->encodeRoles() . $this->encodeEmails(). 
			$this->encodeSubject(). $this->encodeFrom().'/>';
		return $xml;
	}
	
	/**
	 *	@return string this encodes the emails of the route as an xml attribute
	 */
	protected function encodeEmails() {
		if(!$this->Emails) return '';
		return 'emails="'. addslashes(implode(',',$this->Emails)) .'" ';
	}
	
	/**
	 *	@return string this encodes the subject of the route as an xml attribute
	 */
	protected function encodeSubject() {
		if($this->Subject == self::DEFAULT_SUBJECT) return '';
		return 'subject="'. addslashes($this->Subject) .'" ';
	}
	
	/**
	 *	@return string this encodes the from email of the route as an xml attribute
	 */
	protected function encodeFrom() {
		return 'sentfrom="'. addslashes($this->SentFrom) .'" ';
	}
	
	
	/**
	 *	This sends a test email with a test log message
	 */
	public function sendTestEmail() {
		$this->processLogs(array(
				array('Test Message',TLogger::DEBUG,'System.Util.TEmailLogRoute',microtime(true),memory_get_usage())
			));
	}

	/**
	 * Sends log messages to specified email addresses.
	 * @param array list of log messages
	 */
	protected function processLogs($logs)
	{
		$message='';
		foreach($logs as $log)
			$message.=$this->formatLogMessage($log[0],$log[1],$log[2],$log[3],$log[4]);
		$message=wordwrap($message,70);
		$returnPath = ini_get('sendmail_path') ? "Return-Path:{$this->_from}\r\n" : '';
		foreach($this->_emails as $email)
			mail($email,$this->getSubject(),$message,"From:{$this->_from}\r\n{$returnPath}");

	}

	/**
	 * @return array list of destination email addresses
	 */
	public function getEmails()
	{
		return $this->_emails;
	}

	/**
	 * @return array|string list of destination email addresses. If the value is
	 * a string, it is assumed to be comma-separated email addresses.
	 */
	public function setEmails($emails)
	{
		if(is_array($emails))
			$this->_emails=$emails;
		else
		{
			$this->_emails=array();
			foreach(explode(',',$emails) as $email)
			{
				$email=trim($email);
				if(preg_match(self::EMAIL_PATTERN,$email))
					$this->_emails[]=$email;
			}
		}
	}

	/**
	 * @return string email subject. Defaults to TEmailLogRoute::DEFAULT_SUBJECT
	 */
	public function getSubject()
	{
		if($this->_subject===null)
			$this->_subject=self::DEFAULT_SUBJECT;
		return $this->_subject;
	}

	/**
	 * @param string email subject.
	 */
	public function setSubject($value)
	{
		$this->_subject=$value ? $value : null;
	}

	/**
	 * @return string send from address of the email
	 */
	public function getSentFrom()
	{
		return $this->_from;
	}

	/**
	 * @param string send from address of the email
	 */
	public function setSentFrom($value)
	{
		$this->_from=$value;
	}
}

/**
 * TBrowserLogRoute class.
 *
 * TBrowserLogRoute prints selected log messages in the response.
 *
 * @author Xiang Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id$
 * @package System.Util
 * @since 3.0
 */
class TBrowserLogRoute extends TLogRoute
{
	/**
	 * @var string css class for indentifying the table structure in the dom tree
	 */
	private $_cssClass='log-route-browser';
	

	/**
	 * Sends log messages to the browser.
	 * This does quartile analysis on the logs to highlight the memory and time offenders
	 * @param array list of log messages
	 */
	public function processLogs($logs)
	{
		if(empty($logs) || $this->getApplication()->getMode()==='Performance') return;
		$first = $logs[0][3];
		$mem_first = $logs[0][4];
		$even = true;
		$use_interquartile_top_bottom = false;
		$response = $this->getApplication()->getResponse();
		
		$c = count($logs);
		for($i=0,$n=count($logs); $i<$n; $i++) {
			$logs[$i]['i'] = $i;
			if($i > 1 && $i < $n-1) {
				$logs[$i]['time_delta'] = $logs[$i+1][3] - $logs[$i][3];
				$logs[$i]['time_total'] = $logs[$i+1][3] - $first;
				$logs[$i]['mem_delta'] = $logs[$i+1][4] - $logs[$i][4];
				$logs[$i]['mem_total'] = $logs[$i+1][4] - $mem_first;
			} else {
				$logs[$i]['time_delta'] = '?';
				$logs[$i]['time_total'] = $logs[$i][3] - $first;
				$logs[$i]['mem_delta'] = '?';
				$logs[$i]['mem_total'] = $logs[$i][4] - $mem_first;
			}
			$logs[$i]['even'] = !($even = !$even);
		}
		
		{
			vrsort($logs, 'mem_delta');
			$median = $logs[round($c/2)];
			$q1 = $logs[round($c/4)];
			$q3 = $logs[round($c*3/4)];
			
			$mem_delta_median = $median['mem_delta'];
			$mem_delta_q1 = $q1['mem_delta'];
			$mem_delta_q3 = $q3['mem_delta'];
			$irq = $mem_delta_q1 - $mem_delta_q3;
			
			if($use_interquartile_top_bottom) {
				$top = $mem_delta_q1 + $irq * 1.5;
				$bottom = $mem_delta_q3 - $irq * 1.5;
			} else {
				$top = $logs[round($c*2/100)]['mem_delta'];
				$bottom = $logs[round($c*98/100)]['mem_delta'];
			}
			
			$sum_top = 0;
			$sum_bottom = 0;
			$top_value = $mem_delta_q1;
			$bottom_value = $mem_delta_q3;
			
			$top_outliers = 0;
			$bottom_outliers = 0;
			for($i=0,$n=count($logs); $i<$n; $i++) {
				$logs[$i]['mem_delta_order'] = $i;
				$logs[$i]['top_outlier'] = false;
				$logs[$i]['bottom_outlier'] = false;
				if($logs[$i]['mem_delta'] > $top) {
					$logs[$i]['top_outlier'] = true;
					$top_outliers++;
					$sum_top += $logs[$i]['mem_delta'];
				}
				if($logs[$i]['mem_delta'] < $bottom) {
					$logs[$i]['bottom_outlier'] = true;
					$bottom_outliers++;
					$sum_bottom += $logs[$i]['mem_delta'];
				}
					
				if($logs[$i]['mem_delta'] > $mem_delta_q1) {
					$logs[$i]['mem_delta_quartile'] = 0;
					if($logs[$i]['mem_delta'] > $top_value)
						$top_value = $logs[$i]['mem_delta'];
				} else if($logs[$i]['mem_delta'] > $mem_delta_median) {
					$logs[$i]['mem_delta_quartile'] = 1;
				} else if($logs[$i]['mem_delta'] > $mem_delta_q3) {
					$logs[$i]['mem_delta_quartile'] = 2;
				} else {
					$logs[$i]['mem_delta_quartile'] = 3;
					if($logs[$i]['mem_delta'] < $bottom_value)
						$bottom_value = $logs[$i]['mem_delta'];
				}
			}
			if($top_outliers)
				$sum_top /= $top_outliers;
			if($bottom_outliers)
				$sum_bottom /= $bottom_outliers;
		}
		
		$metrics = array(
				'mem_outliers' => $top_outliers + $bottom_outliers, 
				'mem_top_outliers' => $top_outliers,
				'mem_bottom_outliers' => $bottom_outliers,
				'mem_avg_top_outliers' => round($sum_top),
				'mem_avg_bottom_outliers' => round($sum_bottom),
				'mem_median' => $mem_delta_median,
				'mem_q1' => $mem_delta_q1,
				'mem_q3' => $mem_delta_q3,
				'mem_top_irq' => $top,
				'mem_bottom_irq' => $bottom,
				'mem_top' => $top_value,
				'mem_bottom' => $bottom_value
			);
			
		{
			vrsort($logs, 'time_delta');
			$median = $logs[round($c/2)];
			$q1 = $logs[round($c/4)];
			$q3 = $logs[round($c*3/4)];
			
			$time_delta_median = $median['time_delta'];
			$time_delta_q1 = $q1['time_delta'];
			$time_delta_q3 = $q3['time_delta'];
			$irq = $time_delta_q1 - $time_delta_q3;
			
			if($use_interquartile_top_bottom) {
				$top = $time_delta_q1 + $irq * 1.5;
				$bottom = $time_delta_q3 - $irq * 1.5;
			} else {
				$top = $logs[round($c*2/100)]['time_delta'];
				$bottom = $logs[round($c*98/100)]['time_delta'];
			}
			
			$sum_top = 0;
			$sum_bottom = 0;
			$top_value = $time_delta_q1;
			$bottom_value = $time_delta_q3;
			
			$top_outliers = 0;
			$bottom_outliers = 0;
			for($i=0,$n=count($logs); $i<$n; $i++) {
				$logs[$i]['time_delta_order'] = $i;
				$logs[$i]['time_top_outlier'] = false;
				$logs[$i]['time_bottom_outlier'] = false;
				if($logs[$i]['time_delta'] > $top) {
					$logs[$i]['time_top_outlier'] = true;
					$top_outliers++;
					$sum_top += $logs[$i]['time_delta'];
				}
				if($logs[$i]['time_delta'] < $bottom) {
					$logs[$i]['time_bottom_outlier'] = true;
					$bottom_outliers++;
					$sum_bottom += $logs[$i]['time_delta'];
				}
					
				if($logs[$i]['time_delta'] > $time_delta_q1) {
					$logs[$i]['time_delta_quartile'] = 0;
					if($logs[$i]['time_delta'] > $top_value)
						$top_value = $logs[$i]['time_delta'];
				} else if($logs[$i]['time_delta'] > $time_delta_median) {
					$logs[$i]['time_delta_quartile'] = 1;
				} else if($logs[$i]['time_delta'] > $time_delta_q3) {
					$logs[$i]['time_delta_quartile'] = 2;
				} else {
					$logs[$i]['time_delta_quartile'] = 3;
					if($logs[$i]['time_delta'] < $bottom_value)
						$bottom_value = $logs[$i]['time_delta'];
				}
			}
			if($top_outliers)
				$sum_top /= $top_outliers;
			if($bottom_outliers)
				$sum_bottom /= $bottom_outliers;
		}
		$metrics += array(
				'time_outliers' => round(($top_outliers + $bottom_outliers) * 1000, 3), 
				'time_top_outliers' => $top_outliers,
				'time_bottom_outliers' => $bottom_outliers,
				'time_avg_top_outliers' => round($sum_top * 1000, 3),
				'time_avg_bottom_outliers' => round($sum_bottom * 1000, 3),
				'time_median' => round($time_delta_median * 1000, 3),
				'time_q1' => round($time_delta_q1 * 1000, 3),
				'time_q3' => round($time_delta_q3 * 1000, 3),
				'time_top_irq' => round($top * 1000, 3),
				'time_bottom_irq' => round($bottom * 1000, 3),
				'time_top' => round($top_value * 1000, 3),
				'time_bottom' => round($bottom_value * 1000, 3)
			);
		
		vsort($logs, 'i');
		//ksort($logs);
		
		$response->write($this->renderHeader($metrics));
		for($i=0,$n=count($logs);$i<$n;++$i)
		{
			$response->write($this->renderMessage($logs[$i]));
		}
		$response->write($this->renderFooter());
	}
	
	/**
	 * @param string the css class of the control
	 */
	public function setCssClass($value)
	{
		$this->_cssClass = TPropertyValue::ensureString($value);
	}

	/**
	 * @return string the css class of the control
	 */
	public function getCssClass()
	{
		return TPropertyValue::ensureString($this->_cssClass);
	}

	protected function renderHeader($metrics)
	{
		$string = '';
		if($className=$this->getCssClass())
		{
			$string = <<<EOD
<table class="$className">
	<tr class="header">
		<th colspan="7">
			Application Log
		</th>
	</tr><tr class="description">
	    <th>&nbsp;</th>
		<th>Category</th><th>Message</th>
		<th>Time Spent (s)</th>
		<th>Cumulated Time Spent (s)</th>
		<th>&Delta; Memory</th>
		<th>Memory</th>
	</tr>
EOD;
		}
		else
		{
			$top_outliers = 'unset';
			if($metrics['mem_top_outliers'])
				$top_outliers = 'Avg Upper Outlier: '. $metrics['mem_avg_top_outliers'] . ' &nbsp; ';
			if($metrics['time_top_outliers'])
				$time_top_outliers = 'Avg Upper Outlier: '. $metrics['time_avg_top_outliers'] . ' ms &nbsp; ';
			$string = <<<EOD
<table cellspacing="0" cellpadding="2" border="0" width="100%" style="table-layout:auto">
	<tr>
		<th style="background-color: black; color:white;" colspan="7">
			Application Log
		</th>
	</tr>
	<tr>
		<th style="background-color: black; color:white;" colspan="7">
			Memory Stats-   &nbsp;  &nbsp; 
				Top Value: {$metrics['mem_top']} &nbsp; 
				{$top_outliers} &nbsp;
				Q1: {$metrics['mem_q1']} &nbsp; 
				Median: {$metrics['mem_median']} &nbsp; 
				Q3: {$metrics['mem_q3']}  &nbsp; 
				Bottom Value: {$metrics['mem_bottom']} &nbsp; 
		</th>
	</tr>
	<tr>
		<th style="background-color: black; color:white;" colspan="7">
			Time Stats-   &nbsp;  &nbsp; 
				Top Value: {$metrics['time_top']} ms &nbsp; 
				{$time_top_outliers} &nbsp;
				Q1: {$metrics['time_q1']} ms &nbsp; 
				Median: {$metrics['time_median']} ms &nbsp; 
				Q3: {$metrics['time_q3']} ms  &nbsp; 
				Bottom Value: {$metrics['time_bottom']} ms &nbsp; 
		</th>
	</tr>
	<tr style="background-color: #ccc; color:black">
	    <th style="width: 15px">&nbsp;</th>
		<th style="width: auto">Category</th>
		<th style="width: auto">Message</th>
		<th style="width: 120px">Time Spent (s)</th>
		<th style="width: 150px">Cumulated Time Spent (s)</th>
		<th style="width: 100px">&Delta; Memory</th>
		<th style="width: 120px">Memory</th>
	</tr>
EOD;
		}
		return $string;
	}

	protected function renderMessage($log)
	{
		$string = '';
		$total = sprintf('%0.6f', $log['time_total']);
		$delta = sprintf('%0.6f', $log['time_delta']);
		$mem_total = $log['mem_total'];
		$mem_delta = $log['mem_delta'];
		$msg = preg_replace('/\(line[^\)]+\)$/','',$log[0]); //remove line number info
		$msg = THttpUtility::htmlEncode($msg);
		if($this->getCssClass())
		{
			//$log[1] = 0xF;
			
			$colorCssClass = $log[1];
			$memcolor = $log['top_outlier'] ? 'high-memory': ($mem_delta < 0 ? 'negative-memory': '');
			$timecolor = $log['time_top_outlier'] ? 'high-time': ($delta > 0.001 ? 'medium-time': '');
			$string = <<<EOD
	<tr class="message">
		<td class="code level-$colorCssClass">&nbsp;</td>
		<td class="category">{$log[2]}</td>
		<td class="message">{$msg}</td>
		<td class="time $timecolor">{$delta}</td>
		<td class="cumulatedtime">{$total}</td>
		<td class="mem_change $memcolor">{$mem_delta}</td>
		<td class="mem_total">{$mem_total}</td>
	</tr>
EOD;
		}
		else
		{
			$bgcolor = $log['even'] ? "#fff" : "#eee";
			$color = $this->getColorLevel($log[1]);
			$memcolor = $log['top_outlier'] ? '#e00': ($mem_delta < 0 ? '#080': '');
			$timecolor = $log['time_top_outlier'] ? '#e00': ($delta > 0.001 ? '#00c': '');
			$string = <<<EOD
	<tr style="background-color: {$bgcolor}; color:#000">
		<td style="border:1px solid silver;background-color: $color;">&nbsp;</td>
		<td>{$log[2]}</td>
		<td>{$msg}</td>
		<td style="text-align:center; color: $timecolor">{$delta}</td>
		<td style="text-align:center">{$total}</td>
		<td style="text-align:center; color: $memcolor">{$mem_delta}</td>
		<td style="text-align:center">{$mem_total}</td>
	</tr>
EOD;
		}
		return $string;
	}

	protected function getColorLevel($level)
	{
		switch($level)
		{
			case TLogger::DEBUG: return 'green';
			case TLogger::INFO: return 'black';
			case TLogger::NOTICE: return '#3333FF';
			case TLogger::WARNING: return '#33FFFF';
			case TLogger::ERROR: return '#ff9933';
			case TLogger::ALERT: return '#ff00ff';
			case TLogger::FATAL: return 'red';
		}
		return '';
	}

	protected function renderFooter()
	{
		$string = '';
		if($this->getCssClass())
		{
			$string .= '<tr class="footer"><td colspan="7" align="center">';
			foreach(self::$_levelValues as $name => $level)
			{
				$string .= '<span class="level-'.$level.'">'.strtoupper($name)."</span>";
			}
		}
		else
		{
			$string .= "<tr><td colspan=\"7\" style=\"text-align:center; background-color:black; border-top: 1px solid #ccc; padding:0.2em;\">";
			foreach(self::$_levelValues as $name => $level)
			{
				$string .= "<span style=\"color:white; border:1px solid white; background-color:".$this->getColorLevel($level);
				$string .= ";margin: 0.5em; padding:0.01em;\">".strtoupper($name)."</span>";
			}
		}
		$string .= '</td></tr></table>';
		return $string;
	}
}




/**
 * TArraySorter class.
 * TArraySorter allows one to easily sort an array based on the value of a specific key
 *
 * @author Brad Anderson <javalizard@gmail.com>
 * @version $Id$
 * @package System
 * @since 3.2a
 */
class TArraySorter {
	private $_v;
	public function __construct($v) {
		$this->_v = $v;
	}
	public function sort_func($a, $b) {
		return $a[$this->_v] > $b[$this->_v];
	}
	public function sort_func_rev($a, $b) {
		return $a[$this->_v] < $b[$this->_v];
	}
	public function avsort(&$array) {
		uasort($array, array($this, 'sort_func'));
	}
	public function vsort(&$array) {
		usort($array, array($this, 'sort_func'));
	}
	public function avrsort(&$array) {
		uasort($array, array($this, 'sort_func_rev'));
	}
	public function vrsort(&$array) {
		usort($array, array($this, 'sort_func_rev'));
	}
}


/**
 * This sorts an array of arrays based on a the value of a key in the child array 
 * This sort drops all associations and reindexes the keys numerically in order
 * @param array &$array of arrays to be sorted
 * @param string $key the $key in the child arrays to use to sort by
 */
function vsort(&$array, $key) {
	$vsort = new ArraySorter($key);
	$vsort->vsort($array);
	unset($vsort);
}
/**
 * This sorts an array of arrays based on a the value of a key in the child array
 * This sort keeps all associations but reorders the array
 * @param array &$array of arrays to be sorted
 * @param string $key the $key in the child arrays to use to sort by
 */
function avsort(&$array, $key) {
	$uvsort = new ArraySorter($key);
	$uvsort->avsort($array);
	unset($uvsort);
}
/**
 * This sorts an array of arrays based on a the value of a key in the child array in reverse order
 * This sort drops all associations and reindexes the keys numerically in order
 * @param array &$array of arrays to be sorted
 * @param string $key the $key in the child arrays to use to sort by
 */
function vrsort(&$array, $key) {
	$vsort = new ArraySorter($key);
	$vsort->vrsort($array);
	unset($vsort);
}
/**
 * This sorts an array of arrays based on a the value of a key in the child array in reverse order
 * This sort keeps all associations but reorders the array
 * @param array &$array of arrays to be sorted
 * @param string $key the $key in the child arrays to use to sort by
 */
function avrsort(&$array, $key) {
	$vsort = new ArraySorter($key);
	$vsort->avrsort($array);
	unset($vsort);
}


/**
 * TDbLogRoute class
 *
 * TDbLogRoute stores log messages in a database table.
 * To specify the database table, set {@link setConnectionID ConnectionID} to be
 * the ID of a {@link TDataSourceConfig} module and {@link setLogTableName LogTableName}.
 * If they are not setting, an SQLite3 database named 'sqlite3.log' will be created and used
 * under the runtime directory.
 *
 * By default, the database table name is 'pradolog'. It has the following structure:
 * <code>
 *	CREATE TABLE pradolog
 *  (
 *		log_id INTEGER NOT NULL PRIMARY KEY,
 *		level INTEGER,
 *		category VARCHAR(128),
 *		logtime VARCHAR(20),
 *		message VARCHAR(255)
 *   );
 * </code>
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.1.2
 */
class TDbLogRoute extends TLogRoute
{
	/**
	 * @var string the ID of TDataSourceConfig module
	 */
	private $_connID='';
	/**
	 * @var TDbConnection the DB connection instance
	 */
	private $_db;
	/**
	 * @var string name of the DB log table
	 */
	private $_logTable='pradolog';
	/**
	 * @var boolean whether the log DB table should be created automatically
	 */
	private $_autoCreate=true;

	/**
	 * Destructor.
	 * Disconnect the db connection.
	 */
	public function __destruct()
	{
		if($this->_db!==null)
			$this->_db->setActive(false);
	}

	/**
	 * Initializes this module.
	 * This method is required by the IModule interface.
	 * It initializes the database for logging purpose.
	 * @param TXmlElement configuration for this module, can be null
	 * @throws TConfigurationException if the DB table does not exist.
	 */
	public function init($config)
	{
		if(is_array($config)) {
			if(isset($config['connectionid']))
				$this->ConnectionID = $config['connectionid'];
			if(isset($config['logtablename']))
				$this->LogTableName = $config['logtablename'];
			if(isset($config['autocreatelogtable']))
				$this->AutoCreateLogTable = $config['autocreatelogtable'];
		}
		
		if(!$this->checkForTable()) {
			// DB table not exists
			if($this->_autoCreate)
				$this->createDbTable();
			else
				throw new TConfigurationException('db_logtable_inexistent',$this->_logTable);
		}

		parent::init($config);
	}
	
	/**
	 *	This checks for the existance of the log table
	 * @return boolean true if the table exists, false if not
	 */
	protected function checkForTable() {
		
		$db=$this->getDbConnection();
		$db->setActive(true);

		$sql='SELECT * FROM '.$this->_logTable.' WHERE 0';
		try
		{
			$db->createCommand($sql)->query()->close();
			return true;
		} catch( Exception $e ) {
			return false;
		}
	}
	
	
	/**
	 *	@return string this encodes the TDbLogRoute as xml
	 */
	public function toXml() {
		$xml = '<route ' .$this->encodeId(). $this->encodeName().$this->encodeClass() . $this->encodeLevels() . 
			$this->encodeCategories() . $this->encodeControls() . $this->encodeRoles() . $this->encodeConnectionID(). 
			$this->encodeLogTableName(). $this->encodeAutoCreateLogTable().'/>';
		return $xml;
	}
	
	/**
	 *	@return string this encodes the id of the database module of the route as an xml attribute
	 */
	protected function encodeConnectionID() {
		return 'connectionid="'. addslashes($this->ConnectionID) .'" ';
	}
	
	/**
	 *	@return string this encodes the table name of the route as an xml attribute
	 */
	protected function encodeLogTableName() {
		return 'logtablename="'. addslashes($this->LogTableName) .'" ';
	}
	
	/**
	 *	@return string this encodes the auto create log table of the route as an xml attribute
	 */
	protected function encodeAutoCreateLogTable() {
		return 'autocreatelogtable="'. $this->AutoCreateLogTable .'" ';
	}

	/**
	 * Stores log messages into database.
	 * @param array list of log messages
	 */
	protected function processLogs($logs)
	{
		try {
			$sql='INSERT INTO '.$this->_logTable.'(metakey, userid, level, category, memory, logtime, message) VALUES (:metakey, :userid, :level, :category, :memory, :logtime, :message)';
			$command=$this->getDbConnection()->createCommand($sql);
			foreach($logs as $log)
			{
				$command->bindValue(':metakey',$this->MetaId);
				$command->bindValue(':userid',$this->UserId);
				$command->bindValue(':level',$log[1]);
				$command->bindValue(':category',$log[2]);
				$command->bindValue(':memory',$log[4]);
				$command->bindValue(':logtime',$log[3]);
				$command->bindValue(':message',$log[0]);
				$command->execute();
			}
		} catch(Exception $e) {
			// table may be deleted from when this was instantiated
			//probable case: deleted table (aka. dumped database), and don't fail in this case
			
			//If the table is there, something else is up and rethrow error
			if($this->checkForTable())
				throw $e;
		}
	}

	/**
	 * Creates the DB table for storing log messages.
	 * @todo create sequence for PostgreSQL
	 */
	protected function createDbTable()
	{
		$db = $this->getDbConnection();
		$driver=$db->getDriverName();
		$autoidAttributes = '';
		if($driver==='mysql')
			$autoidAttributes = 'AUTO_INCREMENT';
		
		// metakey = varchar 39 because that's the size of an IPv6 address
		$sql='CREATE TABLE '.$this->_logTable.' (
			log_id INTEGER NOT NULL PRIMARY KEY ' . $autoidAttributes . ',
			metakey VARCHAR(39),
			userid BIGINT,
			level INTEGER NOT NULL,
			category VARCHAR(128),
			memory INTEGER NOT NULL,
			logtime DECIMAL(20,8) NOT NULL,
			message VARCHAR(255), INDEX(metakey), INDEX(userid), INDEX(level), INDEX(category), INDEX(logtime))';
		$db->createCommand($sql)->execute();
	}

	/**
	 * Creates the DB connection.
	 * @param string the module ID for TDataSourceConfig
	 * @return TDbConnection the created DB connection
	 * @throws TConfigurationException if module ID is invalid or empty
	 */
	protected function createDbConnection()
	{
		if($this->_connID!=='')
		{
			$config=$this->getApplication()->getModule($this->_connID);
			if($config instanceof TDataSourceConfig)
				return $config->getDbConnection();
			else
				throw new TConfigurationException('dblogroute_connectionid_invalid',$this->_connID);
		}
		else
		{
			$db=new TDbConnection;
			// default to SQLite3 database
			$dbFile=$this->getApplication()->getRuntimePath().'/sqlite3.log';
			$db->setConnectionString('sqlite:'.$dbFile);
			return $db;
		}
	}

	/**
	 * @return TDbConnection the DB connection instance
	 */
	public function getDbConnection()
	{
		if($this->_db===null)
			$this->_db=$this->createDbConnection();
		return $this->_db;
	}

	/**
	 * @return string the ID of a {@link TDataSourceConfig} module. Defaults to empty string, meaning not set.
	 */
	public function getConnectionID()
	{
		return $this->_connID;
	}

	/**
	 * Sets the ID of a TDataSourceConfig module.
	 * The datasource module will be used to establish the DB connection for this log route.
	 * @param string ID of the {@link TDataSourceConfig} module
	 */
	public function setConnectionID($value)
	{
		$this->_connID=$value;
	}

	/**
	 * @return string the name of the DB table to store log content. Defaults to 'pradolog'.
	 * @see setAutoCreateLogTable
	 */
	public function getLogTableName()
	{
		return $this->_logTable;
	}

	/**
	 * Sets the name of the DB table to store log content.
	 * Note, if {@link setAutoCreateLogTable AutoCreateLogTable} is false
	 * and you want to create the DB table manually by yourself,
	 * you need to make sure the DB table is of the following structure:
	 * (key CHAR(128) PRIMARY KEY, value BLOB, expire INT)
	 * @param string the name of the DB table to store log content
	 * @see setAutoCreateLogTable
	 */
	public function setLogTableName($value)
	{
		$this->_logTable=$value;
	}

	/**
	 * @return boolean whether the log DB table should be automatically created if not exists. Defaults to true.
	 * @see setAutoCreateLogTable
	 */
	public function getAutoCreateLogTable()
	{
		return $this->_autoCreate;
	}

	/**
	 * @param boolean whether the log DB table should be automatically created if not exists.
	 * @see setLogTableName
	 */
	public function setAutoCreateLogTable($value)
	{
		$this->_autoCreate=TPropertyValue::ensureBoolean($value);
	}

}

/**
 * TFirebugLogRoute class.
 *
 * TFirebugLogRoute prints selected log messages in the firebug log console.
 *
 * {@link http://www.getfirebug.com/ FireBug Website}
 *
 * @author Enrico Stahn <mail@enricostahn.com>, Christophe Boulain <Christophe.Boulain@gmail.com>
 * @version $Id$
 * @package System.Util
 * @since 3.1.2
 */
class TFirebugLogRoute extends TBrowserLogRoute
{
	
	protected function renderHeader ()
	{
		$string = <<<EOD

<script type="text/javascript">
/*<![CDATA[*/
if (typeof(console) == 'object')
{
	console.log ("[Cumulated Time] [Time] [Memory] [Level] [Category] [Message]");

EOD;

		return $string;
	}

	protected function renderMessage ($log)
	{
		$logfunc = $this->getFirebugLoggingFunction($log[1]);
		$total = sprintf('%0.6f', $log['time_total']);
		$delta = sprintf('%0.6f', $log['time_delta']);
		$msg = trim($this->formatLogMessage($log[0],$log[1],$log[2],'',$log[4]));
		$msg = preg_replace('/\(line[^\)]+\)$/','',$msg); //remove line number info
		$msg = "[{$total}] [{$delta}] ".$msg; // Add time spent and cumulated time spent
		$string = $logfunc . '(\'' . addslashes($msg) . '\');' . "\n";

		return $string;
	}


	protected function renderFooter ()
	{
		$string = <<<EOD

}
</script>

EOD;

		return $string;
	}

	protected function getFirebugLoggingFunction($level)
	{
		switch ($level)
		{
			case TLogger::DEBUG:
			case TLogger::INFO:
			case TLogger::NOTICE:
				return 'console.log';
			case TLogger::WARNING:
				return 'console.warn';
			case TLogger::ERROR:
			case TLogger::ALERT:
			case TLogger::FATAL:
				return 'console.error';
		}
		return 'console.log';
	}

}

/**
 * TFirePhpLogRoute class.
 *
 * TFirePhpLogRoute prints log messages in the firebug log console via firephp.
 *
 * {@link http://www.getfirebug.com/ FireBug Website}
 * {@link http://www.firephp.org/ FirePHP Website}
 *
 * @author Yves Berkholz <godzilla80[at]gmx[dot]net>
 * @version $Id$
 * @package System.Util
 * @since 3.1.5
 */
class TFirePhpLogRoute extends TLogRoute implements IHeaderRoute
{
	/**
	 * Default group label
	 */
	const DEFAULT_LABEL = 'System.Util.TLogRouter(TFirePhpLogRoute)';

	private $_groupLabel = null;

	static public function available() {
		require_once Prado::getPathOfNamespace('System.3rdParty.FirePHPCore') . '/FirePHP.class.php';
		$instance = FirePHP::getInstance(true);
		$available = $instance->detectClientExtension();
		return $available;
	}

	/**
	 * Initializes the route.
	 * @param TXmlElement configurations specified in {@link TLogRouter}.
	 */
	public function init($config)
	{
		parent::init($config);
		
		if(is_array($config)) {
			if(isset($config['grouplabel']))
				$this->GroupLabel = $config['grouplabel'];
		}
		if($this->Application->Service instanceof IPageEvents) {
			$this->Application->Service->OnPreRenderComplete[] = array($this, 'checkHeadFlush');
		}
	}
	
	/**
	 * Not having the head tag flush when it's done is a small price to pay to enable firephp
	 * @param TXmlElement configurations specified in {@link TLogRouter}.
	 */
	public function checkHeadFlush($sender, $page) {
		if(!$this->Active) return;
		$heads = $page->findControlsByType('THead');
		
		// there should only be one but it's an array, so why not?
		foreach($heads as $head) {
			if($head->RenderFlush) {
				Prado::log('Turning off head flush option for firephp', TLogger::INFO, 'System.Util.TFirePhpLogRoute');
				$head->RenderFlush = false;
			}
		}
	}
	
	
	
	
	/**
	 *	@return string this encodes the TFirePhpLogRoute of the route as an xml attribute
	 */
	public function toXml() {
		$xml = '<route ' .$this->encodeId(). $this->encodeName().$this->encodeClass() . $this->encodeLevels() . 
			$this->encodeCategories() . $this->encodeControls() . $this->encodeRoles() . $this->encodeGroupLabel(). '/>';
		return $xml;
	}
	
	/**
	 *	@return string this encodes the grouplabel of the route as an xml attribute
	 */
	protected function encodeGroupLabel() {
		if($this->GroupLabel == self::DEFAULT_LABEL) return '';
		return 'grouplabel="'. addslashes($this->GroupLabel) .'" ';
	}
	

	/**
	 * Stores log messages into database.
	 * @param array list of log messages
	 */
	public function processLogs($logs)
	{
		if(empty($logs) || $this->getApplication()->getMode()==='Performance') return;

		if( headers_sent() ) {
			echo '
				<div style="width:100%; background-color:darkred; color:#FFF; padding:2px">
					TFirePhpLogRoute.GroupLabel "<i>' . $this -> getGroupLabel() . '</i>" -
					Routing to FirePHP impossible, because headers already sent!
				</div>
			';
			$fallback = new TFirebugLogRoute();
			$fallback->processLogs($logs);
			return;
		}

		require_once Prado::getPathOfNamespace('System.3rdParty.FirePHPCore') . '/FirePHP.class.php';
		$firephp = FirePHP::getInstance(true);
		$firephp -> setOptions(array('useNativeJsonEncode' => false));

		$firephp -> group($this->getGroupLabel(), array('Collapsed' => true));

		$firephp ->log('Time,  Message');

		$first = $logs[0][3];
		$c = count($logs);
		for($i=0,$n=$c;$i<$n;++$i)
		{
			$message	= $logs[$i][0];
			$level		= $logs[$i][1];
			$category	= $logs[$i][2];

			if ($i<$n-1)
			{
				$delta = $logs[$i+1][3] - $logs[$i][3];
				$total = $logs[$i+1][3] - $first;
			}
			else
			{
				$delta = '?';
				$total = $logs[$i][3] - $first;
			}

			$message = sPrintF('+%0.6f: %s', $delta, preg_replace('/\(line[^\)]+\)$/','',$message));
			$firephp ->fb($message, $category, self::translateLogLevel($level));
		}
		$firephp ->log( sPrintF('%0.6f', $total), 'Cumulated Time');
		$firephp -> groupEnd();
	}

	protected static function translateLogLevel($level)
	{
		switch($level)
		{
			case TLogger::INFO:
				return FirePHP::INFO;
			case TLogger::DEBUG:
			case TLogger::NOTICE:
				return FirePHP::LOG;
			case TLogger::WARNING:
				return FirePHP::WARN;
			case TLogger::ERROR:
			case TLogger::ALERT:
			case TLogger::FATAL:
				return FirePHP::ERROR;
		}
		return FirePHP::LOG;
	}

	/**
	 * @return string group label. Defaults to TFirePhpLogRoute::DEFAULT_LABEL
	 */
	public function getGroupLabel()
	{
		if($this->_groupLabel===null)
			$this->_groupLabel=self::DEFAULT_LABEL;
		return $this->_groupLabel;
	}

	/**
	 * @param string group label.
	 */
	public function setGroupLabel($value)
	{
		$this->_groupLabel=$value ? $value : null;
	}
}