/adei/trunk

To get this branch, use:
bzr branch http://darksoft.org/webbzr/adei/trunk
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
<?php
class CACHEDB extends ADEIDB {
 var $req;

 var $default_db_server, $default_db_name, $default_db_group;
 var $default_postfix;

 var $md5_postfix;
 var $use_subseconds = NULL;

 var $base_mask;	// Limits available channels, used in conjuction with VIRTUALReader

 var $transaction_operations;
 var $transaction_active;

 var $db_list_cache = array();
 
 const TYPE_AUTO = 0;
 const TYPE_MINMAX = 1;
 const TYPE_MEAN = 2;
 const TYPE_ALL = 3;

 const TABLE_INFO = 0x00010000;		// Information about cache tables
 const LEVEL_INFO = 0x00020000;         // Return information about the cache levels
 const NEED_REQUESTS = 0x00040000;	// Create appropriate requests on listing
 const FIND_BROKEN = 0x00080000;	// Find incomplete caches
 const SKIP_OK = 0x00100000;            // Don't report info on fully cached groups
 const SKIP_MISSING = 0x00200000;       // Don't report info on fully cached groups

 const INSERT_CALL = 1; 
 const DESTRUCTOR_CALL = 2;
 const START_CALL = 4;
 const INTERNAL_CALL = 7;

 function __construct(SOURCERequest $props = NULL) {
    parent::__construct();
    
    if ($props) $this->req = $props;
    else $this->req = new REQUEST();

    if (isset($this->req->props['db_server']))
	$this->default_db_server = $this->req->props['db_server'];
    else 
	$this->default_db_server = false;
    if (isset($this->req->props['db_name']))
	$this->default_db_name =  $this->req->props['db_name'];
    else 
	$this->default_db_name = false;
    if (isset($this->req->props['db_group']))
	$this->default_db_group = $this->req->props['db_group'];
    else 
	$this->default_db_group = false;

    if (($this->default_db_server !== false)&&($this->default_db_name !== false)&&($this->default_db_group !== false)) {
	$this->default_postfix = $this->GetCachePostfix();	
    } else {
	$this->default_postfix = false;
    }

    if (isset($this->req->props['base_mask'])) {
	$this->base_mask = new MASK($this->req->props['base_mask']);
	if ($this->base_mask->IsFull()) $this->base_mask = NULL;
    } else {
	$this->base_mask = NULL;
    }

    $this->transaction_active = false;
 }
 


 function __destruct() {
    if ($this->transaction_active) {
        $this->Commit(CACHEDB::DESTRUCTOR_CALL);
    }

/*
    This could cause problems in the following scenario:
	$cache = new CACHE();
	$cache = new CACHE(); 
    It looks like destructor is called after constructor of new class. To 
    correct problem use:
	$cache = new CACHE();
	unset($cache);
	$cache = new CACHE(); 

    if ($this->dbh) {
	@mysql_close($this->dbh);
	unset($this->dbh);
    }
*/
 }

 static function FindAggregator($aggregator) {
    if ($aggregator) {
	$name = "CACHEDB::TYPE_" . strtoupper($aggregator);
	if (defined($name)) return constant($name);
	else if ((!$aggregator)||(($aggregator>0)&&($aggregator<=CACHEDB::TYPE_ALL))) return $aggregator;
    
	throw new ADEIException(translate("Unknown aggregation mode (%s) is specified", $aggregator));
    }

    return CACHE::TYPE_AUTO;
 }

 function GetSize() {
    $res = mysql_query("SELECT SUM(data_length), SUM(index_length) FROM information_schema.tables WHERE table_schema=DATABASE()");
    if ($res) $row = mysql_fetch_row($res);
    else $row = false;
    if ($row) {
	return array(
	    'size' => $row[0] + $row[1],
	    'data' => $row[0],
	    'index' => $row[1]
	);
    }
    return array();
 }

 function ParseSimplePostfix($postfix, &$m, $prefix="") {
    $pos = strlen($prefix);

    $m[1] = substr($postfix, $pos);

    $pos += 2;
    if (strncmp($postfix, "{$prefix}__",  $pos)) return false;

    $next = strpos($postfix, "__", $pos);
    if ($next === false) return false;
    
    $m[2] = substr($postfix, $pos, $next - $pos);

    $pos =  $next + 2;
    $next = strpos($postfix, "__", $pos);
    if ($next === false) return false;

    $m[3] = substr($postfix, $pos, $next - $pos);
    $m[4] = substr($postfix, $next + 2);
    $m[0] = $postfix;
    return true;
 }
 
 function ParsePostfix($postfix, $prefix="", $allow_incomplete = false) {
    if (preg_match("/^$prefix(__md5_(.*))$/", $postfix, $m)) {
	$supported = true;
	    
	$postfix = $m[1];
	$md5 = $m[2];
	    
	$mres = @mysql_query("SELECT `postfix` FROM md5 WHERE hash = '" . $postfix . '\'', $this->dbh);
	if ($mres) $mrow = mysql_fetch_row($mres);
	else $mrow = false;
	
	if (($mrow)&&($this->ParseSimplePostfix($mrow[0], $m))) {
	    $srv = $m[2];
	    $db = $m[3];
	    $group = $m[4];
	} else if ($allow_incomplete) {
	    $srv = false;
	    $db = false;
	    $group = false;
	} else {
	    throw new ADEIException(translate("Supplied MD5 postfix (%s) is not listed in md5 table", $postfix));
	}

	unset($mres);
    } else if ($this->ParseSimplePostfix($postfix, $m, $prefix)) {
	$supported = true;
	$md5 = false;

	$postfix = $m[1];
	$srv = $m[2];
	$db = $m[3];
	$group = $m[4];
    } else if (preg_match("/^$prefix(__.*)$/", $postfix, $m)) {
	if ($allow_incomplete) {
	    $supported = false;
	    $postfix = $m[1];
	    $md5 = false;
	    $srv = false;
	    $db = false;
	    $group = false;
	} else {
	    throw new ADEIException(translate("Unsupported postfix (%s) is supplied", $postfix));
	}
    } else {
	if ($postfix) {
	    throw new ADEIException(translate("Unsupported postfix (%s) is supplied", $postfix));
	} else {
	    throw new ADEIException(translate("Postfix should be specified"));
	}
    }
    
    return array(
	'postfix' => $postfix,
	'md5' => $md5,
	'db_server' => $srv,
	'db_name' => $db,
	'db_group' => $group,
	'supported' => $supported
    );
 }
 
 function CreateServerRequest(&$postfix_or_info) {
    if (is_array($postfix_or_info))
	$info = &$postfix_or_info;
    else if ($postfix_or_info)
	$info = $this->ParsePostfix($postfix_or_info);
    else
	$info = $this->ParsePostfix($this->default_postfix);
	
    return new SERVERRequest($req = array(
	    'db_server' => $info['db_server']
    ));
	
 }
 
 function CreateGroupRequest(&$postfix_or_info) {
    if (is_array($postfix_or_info))
	$info = &$postfix_or_info;
    else if ($postfix_or_info)
	$info = $this->ParsePostfix($postfix_or_info);
    else
	$info = $this->ParsePostfix($this->default_postfix);

    return new GROUPRequest($req = array(
	'db_server' => $info['db_server'],
	'db_name' => $info['db_name'],
	'db_group' => $info['db_group']
    ));
 }
 
 function GetExtendedCacheInfo(&$postfix_or_row, $flags = 0) {
    global $READER_DB;
    global $ADEI_CACHE_LATENCY_THRESHOLD;
    
    if (is_array($postfix_or_row)) {
	$prefix = "cache0";
	$string = $postfix_or_row[0];
    } else if ($postfix_or_row) {
	$prefix = "";
	$string = $postfix_or_row;
    } else {
	$prefix = "";
	$string = $this->default_postfix;
    }

    $info = $this->ParsePostfix($string, $prefix, true);
    $postfix = $info['postfix'];
    $srv = $info['db_server'];
    $db = $info['db_name'];
    $source = "${srv}__${db}";
    $group = $info['db_group'];
    $supported = $info['supported'];

    $cache_info = array();
    if (($flags&CACHEDB::TABLE_INFO)&&($supported)) {
        $cache_info = $this->GetCacheInfo($postfix);

        if ($flags&CACHEDB::SKIP_OK) {
            $now = time();
            if ((isset($cache_info['last']))&&(abs($now - $cache_info['last']) < $ADEI_CACHE_LATENCY_THRESHOLD))
                return array();
        }
    }

    if ($flags&CACHE::NEED_REQUESTS) {
	    if ($supported) {
		try {
		    $req = $this->CreateGroupRequest($info);

		    $info['server'] = $READER_DB[$srv]['title'];
		    
		    try {
			$reader = $req->CreateReader();
		    } catch (ADEIException $ae) {
			$sreq = $this->CreateServerRequest($info);
			$reader = $sreq->CreateReader();
		    }
		    
		    $info['reader'] = get_class($reader);
		    
		    if ($reader->server['disconnected'])
			$info['disconnected'] = true;

		    if (!in_array($srv, $this->db_list_cache))
			$this->db_list_cache[$srv] = $reader->GetDatabaseList($flags&REQUEST::LIST_WILDCARDED);
		    $db_list = $this->db_list_cache[$srv];
		    
	            if (isset($db_list[$db])) {
			$info['database'] = $db_list[$db]['name'];
			if ((is_array($req->srv['database']))&&(!in_array($db, $req->srv['database'])))
			    $info['wildcarded'] = true;
			
		        if ($req) {
		    	    $grp = $reader->CreateGroup($req->props);
		                    // Slows down considerably on big installations
		            if ($flags&REQUEST::NEED_READERINFO)
			        $group_list = $reader->GetGroupInfo($grp, REQUEST::NEED_INFO|REQUEST::NEED_COUNT|REQUEST::PREFER_EXACTINFO);
                            else
			        $group_list = $reader->GetGroupInfo($grp);
			    
			    if (isset($group_list[$group])) {
				$ginfo = $group_list[$group];
			    } elseif (is_array($group_list)) {
				$ginfo = $group_list;
			    } else {
				$ginfo = false;
				$req = false;
			    }

			    if ($ginfo) {
				$info['group'] = $ginfo['name'];
				foreach ($ginfo as $gkey => $gval) {
				    $info[$gkey] = $gval;
				}

/*
				if (isset($ginfo['first'])) $info['first'] = $ginfo['first'];
				if (isset($ginfo['last'])) $info['last'] = $ginfo['last'];
				if (isset($ginfo['records'])) $info['last'] = $ginfo['records'];
				if (isset($ginfo['query_time'])) $info['last'] = $ginfo['query_time'];
*/
			    }
			}
		    } else {
		        if ($flags&CACHEDB::SKIP_MISSING)
                            return array();
		        $req = false;
		    }
		} catch (ADEIException $ae) {
		    if ($info['server']) {
			$info['disconnected'] = true;
			$info['error'] = $ae->getMessage();
		    }
		    $req = false;
		}
	    } else $req = false;
    
	    $info['req'] = $req;
    }
    

        // Fast variant of REQUEST:::NEED_COUNT is as precise as TABLE INFO (i.e. not)
    if (($flags&CACHEDB::TABLE_INFO)&&($supported)&&($cache_info)) {
	    $info['info'] = $cache_info;

	    if (is_array($postfix_or_row)) {
	        $info['info']['records'] = $postfix_or_row[4];
		$info['info']['dbsize'] = $postfix_or_row[6] + $postfix_or_row[8];
	    }
	    
	    $tables = array();

            if ($flags&CACHEDB::LEVEL_INFO) $mres = @mysql_query("SHOW TABLE STATUS LIKE 'cache%$postfix'", $this->dbh);
            else if ((!is_array($postfix_or_row))||(sizeof($postfix_or_row)<9)) $mres = @mysql_query("SHOW TABLE STATUS LIKE 'cache%$postfix'", $this->dbh);
            else $mres = array($postfix_or_row);

	    if ($mres) {
		$size = 0;
		while ($mrow = (is_array($mres)?array_pop($mres):mysql_fetch_row($mres))) {
		    $size += $mrow[6] + $mrow[8];
		    if (preg_match("/^cache(\d+)$postfix$/", $mrow[0], $m)) {
			$id = $m[1];
			
			if (!$id) $info['info']['records'] = $mrow[4];

			$tables[$id] = ($id > 0)?$this->GetTableInfo($id, $postfix):$cache_info;
			if (!is_array($tables[$id])) $tables[$id] = array();

			$tables[$id]['resolution'] = $id;
			$tables[$id]['records'] = $mrow[4];
			$tables[$id]['dbsize'] = $mrow[6] + $mrow[8];
		    }
		}
		unset($mres);
		
		if ($size) {
		    $info['info']['dbsize'] = $size;
		}
		
		if ($tables) {
		    ksort($tables);
		    $info['info']['tables'] = $tables;
		} else {
		    $info['info']['tables'] = array(
			0 => $info['info']
		    );
		}
	    }
    }

    if (($flags&REQUEST::NEED_ITEMINFO)&&($supported)) {
	    $mres = mysql_query("SHOW COLUMNS FROM `cache0$postfix`", $this->dbh);
	    if ($mres) {
		$mrow = mysql_fetch_row($mres);
		if ($mrow[0] == 'id') {
		    $mrow = mysql_fetch_row($mres);
		} else {
		    $info['info']['outdated'] = true;
		}

		if ($mrow[0] == 'time') {
		    $mrow = mysql_fetch_row($mres);
		    if ($mrow[0] == 'ns') {
			$info['info']['ns'] = true;
			$lastrow = "";
//			$item_number = 0;
		    } else {
			$info['info']['ns'] = false;
			$lastrow = $mrow[0];
//			$item_number = 1;
		    }

		    while ($mrow = mysql_fetch_array($mres)) $lastrow = $mrow[0];
		    if (preg_match("/(\d+)/", $lastrow, $m)) {
			$info['info']['width'] = $m[1] + 1;
		    } else {
			$info['info']['width'] = 0;
		    }
		    
/*			
		    $mrow = mysql_fetch_row($mres);
		    if ($mrow[0] != 'subcache') $item_number++;
		    
		    while ($mrow = mysql_fetch_row($mres)) {
			if ($mrow[0]) $item_number++;
		    }
		    $info['info']['width'] = $item_number;
*/
		}
	    }	   
#	    echo $postfix . " - " . $info['info']['width'] . "<br/>";


	    if ($req) {
		$info['info']['items'] = $reader->GetItemList();
	    }
    }
    return $info;
 }

 function GetCacheList($filter = false, $flags = 0) {
    $query="\\_\\_";
    if ($filter) $query .= preg_replace("/_/", "\\_", $filter) . "\\_\\_";
    $query .= "%";

    $list = $this->GetCacheListSimple($query, $flags);
    
    if ($filter) {
        $res = @mysql_query("SELECT hash FROM md5 WHERE postfix LIKE '${query}'", $this->dbh);
        if ($res) {
            while ($row = mysql_fetch_row($res)) {
                $md5_list = $this->GetCacheListSimple($row[0], $flags);
                $list = array_merge($list, $md5_list);
            }
        }
    }
    
    return $list;
 }
   
 function GetCacheListSimple($query = false, $flags = 0) {
    $list = array();

        // This is inaccurate with InnoDB.
    if ($flags&CACHEDB::TABLE_INFO)
	$res = @mysql_query("SHOW TABLE STATUS LIKE 'cache0${query}'", $this->dbh);
    else
    	$res = @mysql_query("SHOW TABLES LIKE 'cache0${query}'", $this->dbh);

    $postfixes = array();
    while ($row = mysql_fetch_row($res)) {
        try {
	    $t_start =  microtime(true);
	    $info = $this->GetExtendedCacheInfo($row, $flags);
            $t_end = microtime(true);
	    $t = $t_end - $t_start;
            //echo ">  " . date('h:i:s', floor($t_start))  . substr($t_start - floor($t_start), 1) . "  ($t)   " . "${row[0]}  util " .  date('h:i:s', floor($t_end))  . substr($t_end - floor($t_end), 1) ."\n";

	    if ($info) {
	        $info['get_extended_cache_info_time'] = $t;
	        $list[$info['postfix']] = $info;
	        array_push($postfixes, $info['postfix']);
            }
        } catch (ADEIException $ae) {
            // DS: what to do? Do we need to pass the error or we relly or FIND_BROKEN?
        }
    }

    if ($flags&CACHE::FIND_BROKEN) {
	$res = @mysql_query("SHOW TABLES LIKE 'cache%${query}%'", $this->dbh);
	if ($res) {
	    $all_postfixes = array();
    	    while ($row = mysql_fetch_row($res)) {
		if (preg_match("/^cache\d+(__.*)$/", $row[0], $m)) {
		    array_push($all_postfixes, $m[1]);
		}
	    }

	    $incomplete = array_diff(array_unique($all_postfixes), $postfixes);
	    foreach ($incomplete as $postfix) {
	        try {
		    $info = $this->GetExtendedCacheInfo($postfix, $flags);
                }  catch (ADEIException $ae) {
                    // DS: do we need another message about the problems?
                    $info = $this->ParsePostfix($postfix, "", true);
                }
		$info['incomplete'] = true;
//		array_push($list, $info);
		$list[$postfix] = $info;
	    }
	}
    }
        
    return $list;
 }

 function CreateReader($postfix = false) {
    if (!$postfix) $postfix = $this->default_postfix;
    
    $req = $this->CreateGroupRequest($postfix);
    return $req->CreateReader();
 }
 
 function Drop($postfix, $timestamp = false) {
    $lock = new LOCK("cache" . $postfix);
    $lock->Lock(LOCK::BLOCK|LOCK::ALL);

    try {	
	$resolutions = $this->ListResolutions($postfix);
	sort($resolutions);
	
	if ($timestamp !== false) {
	    $max_res = $resolutions[sizeof($resolutions) - 1];
	    $timestamp = floor($timestamp);
	    if ($max_res > 0) {
		$timestamp -= $timestamp % $max_res;
	    }
	    $sqltime = $this->SQLTime(floor($timestamp));
	    foreach ($resolutions as $res) {
		$table = $this->GetTableName($res, $postfix);
		
	        $query = "DELETE FROM `$table` WHERE time >= $sqltime;";
		if (!mysql_query($query, $this->dbh)) {
    		    throw new ADEIException(translate("Failed to drop CACHE (%s). Request '%s' is failed with error: %s", "cache*_$postfix", $query,  mysql_error($this->dbh)));
		}
	    }
	} else {    
	    foreach ($resolutions as $res) {
		$table = $this->GetTableName($res, $postfix);
	        $query = "DROP TABLE `$table`;";
		if (!mysql_query($query, $this->dbh)) {
    		    throw new ADEIException(translate("Failed to drop CACHE (%s). Request '%s' is failed with error: %s", "cache*_$postfix", $query,  mysql_error($this->dbh)));
		}
	    }
	}
    } catch (ADEIException $ae) {
	$lock->UnLock();    
	throw $ae;
    }
    
    $lock->UnLock();    
 }
 
 function Rewidth($postfix, $report = false) {
    $lock = new LOCK("cache" . $postfix);
    $lock->Lock(LOCK::BLOCK|LOCK::ALL);

    try {
	$current = $this->GetCacheWidth($postfix);

	$reader = $this->CreateReader($postfix);
	$actual = $reader->GetGroupSize();
    
	if ($current == $actual) {
	    $lock->UnLock();    
	    return;
	}

	if ($report) {
	    echo translate("Resizing %s from %d to %d", "cache*_$postfix", $current, $actual);
	    if ($report === "html") echo "<br/>";
	    echo "\n";
	}
	
	if ($current < $actual) {
	    $spec0 = "";
	    $spec = "";
	    
	    for ($i = $current; $i < $actual; $i++) {
		if ($i > $current) {
		    $spec0 .= ", ";
		    $spec .= ", ";
		}
		$spec0 .= "ADD `v$i` DOUBLE";
		$spec .= "ADD `min" . $i . "` DOUBLE, ADD `max" . $i . "` DOUBLE, ADD `mean" . $i . "` DOUBLE";
	    }
	} else {
	    $spec0 = "";
	    $spec = "";

	    for ($i = $actual; $i < $current; $i++) {
		if ($i > $actual) {
		    $spec0 .= ", ";
		    $spec .= ", ";
		}
		$spec0 .= "DROP `v$i`";
		$spec .= "DROP `min" . $i . "`, DROP `max" . $i . "`, DROP `mean" . $i . "`";
	    }
	}

	$resolutions = $this->ListResolutions($postfix);
	rsort($resolutions);
    
	foreach ($resolutions as $res) {
	    if ($res) {
		$width = $this->GetTableWidth($postfix, $res);
		if ($width != $current) {
		    if ($width == $actual) {
			if ($report) {
    			    echo translate("Resolution %lu is already converted", $res);
			    if ($report === "html") echo "<br/>";
			    echo "\n";
			}
			continue;
		    }
		    throw new ADEIException(translate("CACHE table (%s) have unexpected size: %d (converting from %d to %d)", "cache${res}${postfix}", $width, $current, $actual));
		}

		$query = "ALTER TABLE `cache${res}${postfix}` $spec";
	    } else {
		$query = "ALTER TABLE `cache0$postfix` $spec0";
	    }
	
	    if ($report) {
		echo translate("Converting resolution %lu", $res);
		if ($report === "html") echo "<br/>";
		echo "\n";
	    }

#	    echo $query . "<br/>\n";
	    if (!mysql_query($query, $this->dbh)) {
		throw new ADEIException(translate("The CACHE (%s) resizing request is not complete. Request '%s' is failed with error: %s", "cache*_$postfix", $query,  mysql_error($this->dbh)));
	    }
	
	}
    } catch (ADEIException $ae) {
	$lock->UnLock();    
	throw $ae;
    }
    
    $lock->UnLock();    
 }

 function ListCachedServers() {
    $groups = array();
    $md5 = array();
    
    $res = @mysql_query("SHOW TABLES LIKE 'cache0__%'", $this->dbh);
    if (!$res)
	throw new ADEIException(translate("SHOW TABLES request is failed on CACHE database, error: %s", mysql_error($this->dbh)));
	
    while ($row = mysql_fetch_row($res)) {
	if (strncmp($row[0], "cache0__md5_", 12)) {
	    $parts = explode("__", $row[0], 3);
	    array_push($groups, $parts[1]);
	} else {
	    array_push($md5, substr($row[0], 6));
	}
    }
    
    if (sizeof($md5) > 0) {
	$res = mysql_query("SELECT `hash`, `postfix` FROM md5", $this->dbh);
	if (!$res) 
	    throw new ADEIException(translate("SELECT request on MD5 table is failed, error: %s", mysql_error($this->dbh)));

	while ($row = mysql_fetch_row($res)) {
	    if (in_array($row[0], $md5)) {
		$parts = explode("__", $row[1], 3);
		array_push($groups, $parts[1]);
	    }
	}
    }

    return array_unique($groups);    
 }


 function ListCachedDatabases($db_server = false) {
    if (!$db_server) {
	if (!$db_server) $db_server = $this->default_db_server;

	if (!$db_server)
	    throw new ADEIException(translate("Server name and database should be specified to list available groups"));
    }

    $groups = array();
    
    $res = @mysql_query("SHOW TABLES LIKE 'cache0__${db_server}__%'", $this->dbh);
    if (!$res)
	throw new ADEIException(translate("SHOW TABLES request is failed on CACHE database, error: %s", mysql_error($this->dbh)));
	
    while ($row = mysql_fetch_row($res)) {
	$parts = explode("__", $row[0], 4);
	array_push($groups, $parts[2]);
    }
    
    $md5 = array();
    $res = mysql_query("SHOW TABLES LIKE 'cache0__md5_%'", $this->dbh);
    while ($row = mysql_fetch_row($res))
	array_push($md5, substr($row[0], 6));
    
    if (sizeof($md5) > 0) {
	$res = mysql_query("SELECT `hash`, `postfix` FROM md5 WHERE postfix LIKE '__${db_server}__%'", $this->dbh);
	if (!$res) 
	    throw new ADEIException(translate("SELECT request on MD5 table is failed, error: %s", mysql_error($this->dbh)));

	while ($row = mysql_fetch_row($res)) {
	    if (in_array($row[0], $md5)) {
		$parts = explode("__", $row[1], 4);
		array_push($groups, $parts[2]);
	    }
	}
    }

    return array_unique($groups);    
 }
 
 function ListCachedGroups($db_name = false, $db_server = false) {
	// DS, only listing databases having level0 CACHE
    if ((!$db_server)||(!$db_name)) {
	if (!$db_server) $db_server = $this->default_db_server;
	if (!$db_name) $db_name = $this->default_db_name;

	if ((!$db_server)||(!$db_name))
	    throw new ADEIException(translate("Server name and database should be specified to list available groups"));
    }

    $groups = array();
    
    $prefix = "cache0__" . $db_server . "__" . $db_name . "__";
    $prefix_length = strlen($prefix);
    
    $res = @mysql_query("SHOW TABLES LIKE 'cache0__${db_server}__${db_name}%'", $this->dbh);
    if (!$res)
	throw new ADEIException(translate("SHOW TABLES request is failed on CACHE database, error: %s", mysql_error($this->dbh)));
	
    while ($row = mysql_fetch_row($res)) {
	array_push($groups, substr($row[0], $prefix_length));
    }
    
    $md5 = array();
    $res = mysql_query("SHOW TABLES LIKE 'cache0__md5_%'", $this->dbh);
    while ($row = mysql_fetch_row($res))
	array_push($md5, substr($row[0], 6));
    
    if (sizeof($md5) > 0) {
	$prefix = "__" . $db_server . "__" . $db_name . "__";
	$prefix_length = strlen($prefix);

	$res = mysql_query("SELECT `hash`, `postfix` FROM md5 WHERE postfix LIKE '__${db_server}__${db_name}__%'", $this->dbh);
	if (!$res) 
	    throw new ADEIException(translate("SELECT request on MD5 table is failed, error: %s", mysql_error($this->dbh)));

	while ($row = mysql_fetch_row($res)) {
	    if (in_array($row[0], $md5))
		array_push($groups, substr($row[1], $prefix_length));
	}

	return array_unique($groups);
    }
    
    return $groups;    
 }

 function ListResolutions($postfix) {
    if (!$postfix) $postfix = $this->default_postfix;
    
    $tables = array();
    
    $mres = @mysql_query("SHOW TABLES LIKE 'cache%$postfix'", $this->dbh);
    if ($mres) {
	while ($mrow = mysql_fetch_row($mres)) {
	    if (preg_match("/^cache(\d+)$postfix$/", $mrow[0], $m)) {
		array_push($tables, $m[1]);
	    }
	}
    }
    
    return $tables;
 }

 function GetGroupPostfix($db_group = false, $db_name = false, $db_server = false) {
    if ((!$db_server)||(!$db_name)||(!$db_group)) {
	if ($db_server === false) $db_server = $this->default_db_server;
	if ($db_name === false) $db_name = $this->default_db_name;
	if ($db_group === false) $db_group = $this->default_db_group;
	if (($db_server === false)||($db_name === false)||($db_group === false))
	    throw new ADEIException(translate("Server name, database and group is required to construct CACHE postfix"));
    }

    if (!$this->GetPostfixType($db_group, $db_name, $db_server)) {
	$db_group = preg_replace("/[^\w\d_]/","",$db_group);
    }

    return "__${db_server}__${db_name}__${db_group}";
 }    

 function MD5CreateTable() {
    if (!@mysql_query("CREATE TABLE IF NOT EXISTS `md5` (`hash` CHAR(64) PRIMARY KEY,  `postfix` VARCHAR(4096) NOT NULL, UNIQUE INDEX(postfix(192)))", $this->dbh)) {
	throw new ADEIException(translate("Creation of system tables (md5) within CACHE database is failed") . " (" . mysql_error($this->dbh) . ")");
    }
 }

 function MD5CreateEntry($postfix) {
    $query = "INSERT INTO `md5` VALUES('" . $this->default_postfix . "' , '" . mysql_real_escape_string($postfix) . "')";
    if (!@mysql_query($query, $this->dbh)) 
	throw new ADEIException(translate("Can not insert entry (%s) into the MD5 caching table, error",  $postfix) . ": " . mysql_error($this->dbh));
 }

 function MD5Check() {
    $res = @mysql_query("SELECT `postfix` from `md5` WHERE `hash` = '" . $this->default_postfix . '\'', $this->dbh);
    if (!$res) {
	switch (mysql_errno($this->dbh)) {
	    case CACHE::MYSQL_ER_NO_SUCH_TABLE:
		$this->MD5CreateTable();
		$row = false;
	    break;
	    default:
		throw new ADEIException(translate("Can not query CACHE md5 table, error") . ": " . mysql_error($this->dbh));
	}
	
    } else {
	$row = mysql_fetch_row($res);
    }
    
    $postfix = $this->GetGroupPostfix();

    if ($row === false) 
	$this->MD5CreateEntry($postfix);
    elseif (strcmp($row[0], $postfix))
	throw new ADEIException(translate("Unlucky, the MD5 checksums of two groups (\"%s\" and \"%s\") are coinciding. This is not handled automaticaly yet. Please, add/alter md5 suffix to the newly added group.", $row[0], $postfix));
 }

 function CacheLogCreateTable() {
    if (!@mysql_query("CREATE TABLE IF NOT EXISTS `cachelog`(
                        `id` INT NOT NULL AUTO_INCREMENT,
                        `time` DATETIME,
                        `postfix` VARCHAR(4096) NOT NULL,
                        `resolution` INT,
                        `action` CHAR(64),
                        `ack` INT,
                        PRIMARY KEY (`id`),
                        INDEX (`time`)
                    )", $this->dbh)) {
	throw new ADEIException(translate("Creation of system tables (cachelog) within CACHE database is failed") . " (" . mysql_error($this->dbh) . ")");
    }
 }

 function CacheLogAdd($action, $postfix, $resolution) {
    if (!$postfix) $postfix = $this->default_postfix;
    $time = $this->SQLTime(time());
 
    $query = "INSERT INTO `cachelog` VALUES(NULL, '{$time}', '" . mysql_real_escape_string($postfix) . "', $resolution, '$action', 0)";
    if (!@mysql_query($query, $this->dbh)) {
        switch (mysql_errno($this->dbh)) {
	    case CACHE::MYSQL_ER_NO_SUCH_TABLE:
		$this->CacheLogCreateTable();
                if (@mysql_query($query, $this->dbh))
                    break;
            default:
	        throw new ADEIException(translate("Error logging info on %s:%s to CacheLog, error",  $postfix, $resolution) . ": " . mysql_error($this->dbh));
        }
    }
 }


 function CacheLogGet($filters = false) {
    $archive = false;
        
    if ($filters) {
        $where = "";
        if (isset($filters['archive'])) {
            $archive = $filters['archive'];
            unset($filters['archive']);
        }
        
        if (isset($filters['interval'])) {
            $from = $this->SQLTime($filters['interval'][0]);
            $to = $this->SQLTime($filters['interval'][1]);
            $where .= " `time` BETWEEN  $from AND $to";
            unset($filters['interval']);
        }
        
        foreach ($filters as $flt => $val) {
            if ($where) $where .= " AND ";
            if ($flt == "id")
                $where .= "`$flt` >= \"$val\"";
            else
                $where .= "`$flt` = \"$val\"";
        }
    }
    
    $query = "SELECT * FROM `cachelog`";
    if ($where) $query .= " WHERE $where";
    $res = @mysql_query($query, $this->dbh);
    if (!$res) {
        switch (mysql_errno($this->dbh)) {
	    case CACHE::MYSQL_ER_NO_SUCH_TABLE:
                return array();
            default:
	        throw new ADEIException(translate("Error querying CacheLog, error: %s, query: %s", mysql_error($this->dbh), $query));
        }
    }
    
    $list = array();
    while ($item = mysql_fetch_array($res, MYSQL_ASSOC)) {
        $info = $this->ParsePostfix($item['postfix']);
        foreach ($info as $key => $val) {
            $item[$key] = $val;
        }
        if ($archive !== false) {
            if (preg_match("/_\d{4,8}$/", $item['db_name'])) {
                if (!$archive) continue;
            } else {
                if ($archive) continue;
            }
        }
        array_push($list, $item);
    }
    
    return $list;
 }


 function GetPostfixType($db_group = false, $db_name = false, $db_server = false) {
	if ((!$db_server)||(!$db_name)||(!$db_group)) {
	    if ($db_server === false) $db_server = $this->default_db_server;
	    if ($db_name === false) $db_name = $this->default_db_name;
	    if ($db_group === false) $db_group = $this->default_db_group;
	    
	    if (($db_server === false)||($db_name === false)||($db_group === false))
		throw new ADEIException(translate("Server name, database and group is required to construct CACHE postfix"));
	}

	return $this->req->GetCustomOption('use_md5_postfix', $db_server, $db_name, $db_group);
 }
 
 function GetCachePostfix($db_group = false, $db_name = false, $db_server = false) {
    $postfix = $this->GetGroupPostfix($db_group, $db_name, $db_server);

    if (isset($this->md5_postfix)) $md5 = $this->md5_postfix;
    else $md5 = $this->GetPostfixType($db_group, $db_name, $db_server);
    
    if ($md5) {
	return "__md5_" . (is_string($md5)?$md5:"") .  md5($postfix);
    } else return $postfix;
 }
 
 function SetDefaultPostfix($postfix = false) {
    if ($postfix) {
	if ($postfix instanceof REQUEST) {
	    $postfix = $postfix->GetProps();
	}
	
	if (is_array($postfix)) {
	    if (isset($postfix['db_server'])) $this->default_db_server = $postfix['db_server'];
	    if (isset($postfix['db_name'])) $this->default_db_name = $postfix['db_name'];
	    if (isset($postfix['db_group'])) $this->default_db_group = $postfix['db_group'];
	    $this->md5_postfix = $this->GetPostfixType($this->default_db_group, $this->default_db_name, $this->default_db_server);
	    $this->default_postfix = $this->GetCachePostfix();
	} else {
	    $this->default_postfix = $postfix;
	}
    } else {
	$this->default_postfix = $this->GetCachePostfix();
    }
 }
 
 function GetTableName($resolution = 0, $postfix = false) {
    return "cache" . $resolution . ($postfix?$postfix:$this->default_postfix);
 }

 function DetectSubseconds($postfix = false) {
    $table = $this->GetTableName(0, $postfix);
    $res = mysql_query("SHOW COLUMNS FROM `$table`", $this->dbh);
    if (!$res) {
	switch (mysql_errno($this->dbh)) {
	    case CACHEDB::MYSQL_ER_NO_SUCH_TABLE:
    		throw new ADEIException(translate("The CACHE table '%s' is empty", $table), ADEIException::NO_CACHE);
	    default:
    		throw new ADEIException(translate("There is problem executing 'SHOW COLUMNS' request on CACHE table '%s'", $table));
	}
    }
    
    mysql_fetch_array($res); 		// skipping id column
    mysql_fetch_array($res); 		// skipping time column
    $row = mysql_fetch_array($res);	// possibly ns column
    if (!strcmp($row[0],"ns")) {
	if (!$postfix) $this->use_subseconds = true;
	return true;
    }

    if (!$postfix) $this->use_subseconds = false;
    return false;
 }
 
 function GetTableWidth($postfix = false, $resolution = 0) {
    $table = $this->GetTableName($resolution, $postfix);

    $res = mysql_query("SHOW COLUMNS FROM `$table`", $this->dbh);
    if (!$res) {
	switch (mysql_errno($this->dbh)) {
	    case CACHEDB::MYSQL_ER_NO_SUCH_TABLE:
    		throw new ADEIException(translate("The CACHE table '%s' is empty", $table), ADEIException::NO_CACHE);
	    default:
    		throw new ADEIException(translate("There is problem executing 'SHOW COLUMNS' request on CACHE table '%s'", $table));
	}
    }
    
    while ($col = mysql_fetch_array($res)) $lastcol = &$col['Field'];

    if (!preg_match("/(\d+)/", $lastcol, $m)) 
        throw new ADEIException("There is problem finding out the number of channels. Last cache column is '$lastcol'");
	
    return ($m[1] + 1);
 }
 
 function GetCacheWidth($postfix = false) {
    return $this->GetTableWidth($postfix, 0);
 }
 
 function GetCacheIDs($postfix = false) {
	// DS, check if we do not have a level0 CACHE
	$size = $this->GetCacheWidth($postfix);
	
	if ($this->base_mask) {
	    if ($this->base_mask->ids) return range(0, sizeof($this->base_mask->ids) - 1);
	    else $mask->ids = array();
	} else {
	    if ($size>0) return range(0, $size - 1);
	    else return array();
	}
 }

 function CreateCacheInterval($postfix = false, array &$iinfo = NULL, $flags = 0) {
    if (!is_array($iinfo)) {
	if ($this->req instanceof DATARequest)
	    $iinfo = $this->req->GetIntervalInfo();
    }

    $ivl = new INTERVAL($iinfo, NULL, NULL, $flags);
    $ivl->ApplyCache($this);

    return $ivl;
 }
 
 function CreateInterval(array &$iinfo = NULL, $flags = 0) {
    return $this->CreateCacheInterval(false, $iinfo, $flags);
 }

 function CreateCacheMask($postfix = false, array &$minfo = NULL, $flags = 0) {
    if (!$minfo) {
	if ($this->req instanceof GROUPRequest)
	    $minfo = $this->req->GetMaskInfo();
    }
    
    $mask = new MASK($minfo);
    if ($mask->ids === false) {
/*
	if ($this->base_mask) {
	    if ($this->base_mask->ids) $mask->ids = range(0, sizeof($this->base_mask->ids) - 1);
	    else $mask->ids = array();
	} else 
*/
	$mask->ids = $this->GetCacheIDs($postfix);
    }
    return $mask;
 }

 function CreateMask(array &$minfo = NULL, $flags = 0) {
    return $this->CreateCacheMask(false, $minfo, $flags);
 }

 function GetTableInfo($resolution = 0, $postfix = false, $flags = 0) {
    $table = $this->GetTableName($resolution, $postfix);

    $extra = "";
/*
    if ($flags&REQUEST::NEED_COUNT) {
            // This could be extremely slow on InnoDB (it will make a full scan of the index at minimum)
        $extra .= ", COUNT(time) AS records";
    }
*/

    $req = "SELECT EXTENDED_UNIX_TIMESTAMP(MIN(time)) AS first, EXTENDED_UNIX_TIMESTAMP(MAX(time)) AS last${extra} FROM `$table`";
    try {
        // DetectSubseconds will fail if caching table is not present yet. However, we would not refer to it during the caching process. Only Admin interface uses PREFER_EXACTINFO at the moment
        if ((!$resolution)&&($flags&REQUEST::PREFER_EXACTINFO)) {
                // In fact there could be difference between configuration & already existing caching tables. The best thing we can do is to fail with the error. If this gets a repeated problem, we will need to provide both values to the Admin interface
            if (($postfix)||(!isset($this->use_subseconds)))
                $use_subseconds = $this->DetectSubseconds($postfix);
            else
                $use_subseconds = $this->use_subseconds;
                
                // Querying 'ns' like this would be significantly slower
            if ($use_subseconds)
                $req = "SELECT (SELECT ADEI_TIMESTAMP(EXTENDED_UNIX_TIMESTAMP(time),ns)/1000000000 FROM `$table` ORDER BY id LIMIT 1) as first, (SELECT ADEI_TIMESTAMP(EXTENDED_UNIX_TIMESTAMP(time),ns)/1000000000 FROM `$table` ORDER BY id DESC LIMIT 1) as last${extra}";
        }
    } catch (ADEIException $ae) {
        // Just use non-subsecond version in this case
    }
        
    $res = mysql_query($req, $this->dbh);
    if (!$res) {
	switch (mysql_errno($this->dbh)) {
	    case CACHE::MYSQL_ER_NO_SUCH_TABLE:
		return false;
	    break;
	    default:
		throw new ADEIException(translate("SELECT request '%s' on CACHE table '%s' is failed. MySQL error: %s", $req, $table, mysql_error($this->dbh)));
	}
    }

    $info = mysql_fetch_assoc($res);

    if ($flags&REQUEST::NEED_COUNT) {
            // This could be inprecise, but other method is extremely slow on InnoDB (and very imprecise if done on the MySQL/Slave)
        $res = mysql_query("EXPLAIN SELECT COUNT(time) AS records FROM `$table`", $this->dbh);
        if ($res) {
            $vals = mysql_fetch_assoc($res);
            if ($vals) $info['records'] = $vals['rows'];
        } 
    }

    return $info;
 }
 
 function GetCacheInfo($postfix = false, $flags = 0) {
	// DS, check if we do not have a level0 CACHE
    return $this->GetTableInfo(0, $postfix, $flags);
 }

 function GetInfo($flags = 0) {
    return $this->GetCacheInfo(false, $flags);
 } 

 function GetCacheItemList($postfix = false, MASK $mask = NULL, $flags = 0) {
    $items = array();
    
    if ($this->base_mask) {
	$mask = $this->base_mask->Superpose($mask);
    }
    
    if (($mask)&&($mask->ids)) {
	foreach ($mask->ids as $i => $id) {
	    $items[$i] = array(
		"id" => $id,
		"name" =>  "Channel" . ($id+1),
	    );
	}
    } else {
        $size = $this->GetCacheWidth($postfix);

	for ($i=0;$i<$size;$i++) {
	    $items[$i] = array(
		"id" => $i,
		"name" =>  "Channel" . ($i+1),
	    );
	}
    }
    
    return $items;
 }

 function GetItemList(MASK &$mask = NULL, $flags = 0) {
    return $this->GetCacheItemList(false, $mask, $flags);
 }
 
 function SQLTime($time) {
    return strftime("%Y%m%d%H%M%S", floor($time));

/* 
    Subseconds are not supported by MySQL Datetime type
    if (is_int($time))
	return strftime("%Y%m%d%H%M%S", $time);
    else {
	return strftime("%Y%m%d%H%M%S", floor($time)) . substr(sprintf("%.6F", $time - floor($time)), 1);
    }
*/
 }
 
 function CreateTable($resolution, $items, $postfix = false) {
    global $ADEI_CACHE_ENGINE;
    global $ADEI_CACHE_COMPRESSION;
    global $ADEI_DELAYED_KEYS;

    if (($this instanceof CACHE) == false)
	throw new ADEIException(translate("CreateTable calls are only allowed on CACHE object"));

    $name = $this->GetTableName($resolution, $postfix);
    
    if (strcasecmp($ADEI_CACHE_COMPRESSION, "None"))
	$compression="COMPRESSION=\"$ADEI_CACHE_COMPRESSION\"";
    else
	$compression="";

    if ($resolution > 0) {
	for ($i = 0; $i < $items; $i++)
	    $query .= ", `min" . $i . "` DOUBLE, `max" . $i . "` DOUBLE, `mean" . $i . "` DOUBLE";

	/*, `duration` INT, `complete` BOOL,*/
	if (!mysql_query("CREATE TABLE IF NOT EXISTS `$name` (`time` DATETIME PRIMARY KEY, `n` BIGINT, `missing` INT" .  $query . ") ENGINE = $ADEI_CACHE_ENGINE  $compression", $this->dbh)) {
	    throw new ADEIException(translate("Unable to create cache table (resolution: %s, items: 3 + 3 * %s), error: %s", $resolution, $items, mysql_error($this->dbh)));
	}
    } else {	
	    // There is no way to create if not existing. So there is a lot of errors in log. Rarely changed, so moved to system.
//	$this->CreateStoredProcedures();

	for ($i = 0; $i < $items; $i++)
	    $query .= ", `v" . $i . "` DOUBLE";

	$id = "`id` BIGINT NOT NULL UNIQUE KEY";
	if ($this->use_subseconds) {
	    $time = "`time` DATETIME, `ns` INT, `subcache` INT";
	    $index = ", PRIMARY KEY (`time`, `ns`, `subcache`)";
	} else {
	    $time = "`time` DATETIME PRIMARY KEY";
	    $index = "";
	}
	
	if (!mysql_query("CREATE TABLE IF NOT EXISTS `$name` ($id, $time"  .  $query . "$index) ENGINE =  $ADEI_CACHE_ENGINE", $this->dbh)) {
	    throw new ADEIException(translate("Unable to create cache table (resolution: 0, items: 2/4 + %s), error: %s [%s]", $items, mysql_error($this->dbh), "CREATE TABLE IF NOT EXISTS `$name` ($time"  .  $query . ",$index)"));
	}
    }
    if ($ADEI_DELAYED_KEYS) {
	mysql_query("ALTER TABLE `$name` DELAY_KEY_WRITE = 1;");
    }

    $this->CacheLogAdd("create", $postfix, $resolution);
 }
 
 function Query($query) {
    if (!mysql_query($query, $this->dbh)) {
	throw new ADEIException(translate("Query is failed, error: %s [%s]", mysql_error($this->dbh), $query));
    }
 }

 function CreateQuery($table, $time, &$d) {
    if (($this instanceof CACHE) == false)
	throw new ADEIException(translate("CreateTable calls are only allowed on CACHE object"));

    if (is_object($d)) {
	$sqltime = $this->SQLTime(floor($time));
#	echo "Time: $time -> $sqltime\n";
        
	$query = "INSERT INTO `$table` VALUES ($sqltime, " . $d->n . ", " . $d->missing;
	if ($d->n > 0) {
	    for ($j = 0; $j < $this->items; $j++) {
		$query .= ", " . (($d->min[$j]!==NULL)?$d->min[$j]:"NULL") . ", " . (($d->max[$j]!==NULL)?$d->max[$j]:"NULL") . ", " . (($d->mean[$j]!==NULL)?$d->mean[$j]:"NULL");
	    }
	} else {
	    for ($j = 0; $j < $this->items; $j++) {
		$query .= ", 0, 0, 0";
	    }
	}
	$query .= ")";
    } else {
	$sqltime = $this->SQLTime($time);

	if ($this->use_subseconds) {
	    $point = strstr($time, ".");
	    if ($point) {
		$subs = substr($point, 1);
		$chars = strlen($subs);
		if ($chars<9) $subs .= str_repeat("0", 9 - $chars);
	    } else $subs= "0";
	    
	    $ns .= ", $subs, 0";
	    $id = "ADEI_TIMESTAMP(" . (floor($time)) . ", $subs)";
	} else {
	    $ns="";
	    $id = "ADEI_TIMESTAMP(" . (floor($time)) . ", 0)";
	}
	    
	$query = "INSERT INTO `$table` VALUES ($id, $sqltime" . $ns;
	foreach ($d as $val) {
	    if ($val === NULL)
		$query .= ", NULL";
	    else
		$query .= ", $val";
	}
	$query .= ")";
    }

    return $query;
 }

 function Insert($resolution, &$query) {
    global $ADEI_CONTINUOUS_TRANSACTION;
    global $ADEI_TRANSACTION_SIZE;
    
    if (($this instanceof CACHE) == false)
	throw new ADEIException(translate("CreateTable calls are only allowed on CACHE object"));
    
    if ($this->transaction_active) {
        $this->transaction_operations++;
    } else if ($ADEI_CONTINUOUS_TRANSACTION) {
	$this->StartTransaction(CACHEDB::INSERT_CALL);
        $this->transaction_operations++;
    }

    if ($this->transaction_operations > $ADEI_TRANSACTION_SIZE) {
        $this->Commit(CACHEDB::INSERT_CALL);
        $this->StartTransaction(CACHEDB::INSERT_CALL);
    }

    if (!@mysql_query($query, $this->dbh)) {
	$handled = false;
	switch (mysql_errno($this->dbh)) {
	     case CACHE::MYSQL_ER_NO_SUCH_TABLE:
		$this->CreateTable($resolution, $this->items);
		if (@mysql_query($query, $this->dbh)) $handled = true;
	     break;
	     case CACHE::MYSQL_ER_DUP_ENTRY:
	        if (!strstr($query, "cache0"))
		    throw new ADEIException(translate("Internal error. Trying to insert the block which is already in the cache (Resolution: $resolution [$query])."));
	        return CACHE::MYSQL_ER_DUP_ENTRY;
	     break;
	     case CACHE::MYSQL_ER_WRONG_VALUE_COUNT_ON_ROW:
		throw new ADEIException(translate("The number of items in caching table and database doesn't match. Please, fix your configuration."));
	     break;
	     case CACHE::MYSQL_ER_BAD_FIELD_ERROR:
	        // May be we have INF in the column list
	        $fixed_query = preg_replace("/,\s+-?(INF|NAN)/", ", NULL", $query, -1, $reps);
	        if (($fixed_query)&&($reps > 0)) {
		    $query = $fixed_query;
		    if (@mysql_query($query, $this->dbh)) $handled = true;
		}
	     break;
	}
	
	if (!$handled) {
	    throw new ADEIException(translate("Can not insert into the caching table (Resolution: %u), error %u: %s [query %s]", $resolution, mysql_errno($this->dbh), mysql_error($this->dbh), $query));
	}
    }
 
    return 0;
 }

 function StartTransaction($flags = 0) {
    global $ADEI_CONTINUOUS_TRANSACTION;
    global $ADEI_TRANSACTION_SIZE;

    if (!$ADEI_TRANSACTION_SIZE) return;
    if (($ADEI_CONTINUOUS_TRANSACTION)&&(($flags&CACHEDB::INTERNAL_CALL)==0)) return;

    if ($this->transaction_active) {
        $this->Commit(CACHEDB::START_CALL);
    }
    if (@mysql_query("START TRANSACTION")) {
        $this->transaction_operations = 0;
        $this->transaction_active = true;
    }
 }
 
 function Commit($flags = 0) {
    global $ADEI_CONTINUOUS_TRANSACTION;
    if (($ADEI_CONTINUOUS_TRANSACTION)&&(($flags&CACHEDB::INTERNAL_CALL)==0)) return;

    if ($this->transaction_active) {
#	echo "Commiting {$this->transaction_operations} operations as requested by {$flags}\n";
	if (!@mysql_query("COMMIT"))
	    throw new ADEIException(translate("Can't commit last transaction of %u operations,  error %u: %s", $this->transaction_operations, mysql_errno($this->dbh), mysql_error($this->dbh)));

	$this->transaction_active = false;
    }
 }



 function GetReady($table, $from, $to) {
    return new CACHEData($this, $table, $from, $to);
 }

 
 function GetCachePoints($postfix = false, MASK &$mask = NULL, INTERVAL &$ivl = NULL, $type = CACHEDB::TYPE_AUTO, $limit = 0, $amount_or_sampling = 0, $resolution = false) {
    if (!$mask) $mask = $this->CreateCacheMask();
    if (!$ivl) $ivl = $this->CreateCacheInterval();
    
    if ($type == CACHEDB::TYPE_ALL) {
	$res = new RAWPoint($this, $mask, $ivl, $limit, $amount_or_sampling);
    } else {
	$res = new DATAPoint($this, $mask, $ivl, $type, $amount_or_sampling, $limit, $resolution);
    }

    if (($postfix)||(!isset($this->use_subseconds))) {
	// we should find subsecond precision
	$use_subseconds = $this->DetectSubseconds($postfix);
	$res->SetOption("use_subseconds", $use_subseconds);

	if ($postfix) $res->SetOption("postfix", $postfix);
    }
    return $res;    
  }

  function GetDownloads($download = NULL, $sort = NULL) {
    if($sort != "ASC") $sort = "DESC";
    if(!$download) $query = "SELECT * FROM downloads ORDER BY startdate $sort";
    else $query = "SELECT * FROM downloads WHERE dl_id='".$download."' ORDER BY startdate $sort;";
    
    $res = @mysql_query($query, $this->dbh);   

    if (!$res) {
      switch (mysql_errno($this->dbh)) {
	case CACHE::MYSQL_ER_NO_SUCH_TABLE:
	    $this->CreateDownloadsTable();
	    $res = @mysql_query($query, $this->dbh);
	break;	     
      }
      if (!$res) {
        throw new ADEIException(translate("Can't get downloads from database, error") . ": " . mysql_error($this->dbh));
      }
    }
    return $res;
  }
  
  function UpdateDownloadCol($download, $col, $value, $fsize = NULL) {
    if($col == "status" && $value == "Ready" && !@mysql_query("UPDATE downloads SET filesize='".$fsize."', progress='100' ,enddate='".time()."' ,status='".$value."' WHERE dl_id ='".$download."';" , $this->dbh)) {
      throw new ADEIException(translate("Can't change download status, error") . ": " . mysql_error($this->dbh));
    }
    else if(!mysql_query("UPDATE downloads SET $col='".mysql_escape_string($value)."' WHERE dl_id ='".$download."';" , $this->dbh)) {
      throw new ADEIException(translate("Error while updating downloads table. Column: $col. Error") . ": " . mysql_error($this->dbh));
    }  
  } 
 
  function RemoveDownload($download) {
    if(!@mysql_query("DELETE FROM downloads WHERE dl_id ='".$download."';" , $this->dbh)) {
	throw new ADEIException(translate("Can not delete entry from the downloads table, error") . ": " . mysql_error($this->dbh));
    }
  }

  function AddDownload($props) {
    $query = "INSERT into downloads VALUES(";

    foreach($props as $item => $value) {
      if ($value === "") $query .= "NULL";
      else $query .= "'$value'";
      
      if($item != "auto_delete") $query .= ",";
      else $query .= ")";
    }
    
    if (!@mysql_query($query, $this->dbh)) {
      switch (mysql_errno($this->dbh)) {
	case CACHE::MYSQL_ER_NO_SUCH_TABLE:
	    $this->CreateDownloadsTable();
	    if(!@mysql_query($query,$this->dbh)) {
	      throw new ADEIException(translate("Error adding download. ERROR: ") . ": " . mysql_error($this->dbh));
	    } 	
	break;	     
	default:
	    throw new ADEIException(translate("Error adding download. ERROR: ") . ": " . mysql_error($this->dbh));
	break;
      }
    }
  }

  function CreateDownloadsTable() {
    $query = "CREATE TABLE IF NOT EXISTS downloads (
	      `dl_id` varchar(32) NOT NULL,
	      `dl_name` text COLLATE utf8_unicode_ci,
	      `db_server` text COLLATE utf8_unicode_ci NOT NULL,
	      `db_name` text COLLATE utf8_unicode_ci NOT NULL,
	      `db_group` text COLLATE utf8_unicode_ci NOT NULL,
	      `db_mask` text COLLATE utf8_unicode_ci,
	      `control_group` text COLLATE utf8_unicode_ci,
	      `resample` int(11),
	      `experiment` text COLLATE utf8_unicode_ci,
	      `window` text COLLATE utf8_unicode_ci,
	      `status` text COLLATE utf8_unicode_ci,
	      `startdate` text COLLATE utf8_unicode_ci,
	      `enddate` text COLLATE utf8_unicode_ci,
	      `format` text COLLATE utf8_unicode_ci,
	      `virtual` text COLLATE utf8_unicode_ci,
	      `srctree` text COLLATE utf8_unicode_ci,
	      `progress` int(11),	    
	      `user` text COLLATE utf8_unicode_ci,
	      `filesize` float,
	      `ctype` text COLLATE utf8_unicode_ci,
	      `filesremaining` int(11),
	      `readablewindow` text COLLATE utf8_unicode_ci,
	      `error` text COLLATE utf8_unicode_ci,
	      `detwindow` text COLLATE utf8_unicode_ci,	      
	      `axis_range` text COLLATE utf8_unicode_ci,
	      `temperature_axis_range` text COLLATE utf8_unicode_ci,
	      `voltage_axis_range` text COLLATE utf8_unicode_ci,
	      `aggregation` text COLLATE utf8_unicode_ci,
	      `interpolate` text COLLATE utf8_unicode_ci,
	      `show_gaps` text COLLATE utf8_unicode_ci,
	      `mask_mode` text COLLATE utf8_unicode_ci,
	      `auto_delete` text COLLATE utf8_unicode_ci,
	      UNIQUE KEY dl_ID (dl_id) ) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
    
    if(!@mysql_query($query,$this->dbh)) {
      throw new ADEIException(translate("Can't create downloads table, error") . ": " . mysql_error($this->dbh));
    } 
  }

}

?>