summaryrefslogtreecommitdiffstats
path: root/non-puppet/qtmetrics/ci/showautotestdashboard.php
blob: ad93ced97a3005d27d543f6f1597433f28ca2507 (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
<?php
session_start();
?>

<?php
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of the Qt Metrics web portal.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3.0 as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU General Public License version 3.0 requirements will be
## met: http://www.gnu.org/copyleft/gpl.html.
##
##
## $QT_END_LICENSE$
##
#############################################################################
?>

<?php
include "definitions.php";
include "functions.php";
include(__DIR__.'/../commonfunctions.php');
include "metricsboxdefinitions.php";

/* The structure of array $arrayTestcaseConfs */
define("FAILINGTESTCASECONFNAME", 0);
define("FAILINGTESTCASECONFFAILED", 1);
define("FAILINGTESTCASECONFALL", 2);

/* Set the minimum build number to be checked for a project to optimize the performance (by default only to check the latest CITESTRESULTBUILDCOUNT builds)
   Input:   $latestBuildNumber                       (integer) Latest build number in the project
            $minBuildNumberInDatabase                (integer) The first build number that is available in the database
            $timescaleType                           (string)  The timescale filter
   Return:  (integer) The lowest build number to be checked
*/
function setMinBuildNumberToCheck($latestBuildNumber, $minBuildNumberInDatabase, $timescaleType)
{
    if (($latestBuildNumber - $minBuildNumberInDatabase) > CITESTRESULTBUILDCOUNT)      // Read only CITESTRESULTBUILDCOUNT latest builds
        $minBuildNumber = $latestBuildNumber - CITESTRESULTBUILDCOUNT + 1;
    else                                                                                // ... or the first that is available in the database
        $minBuildNumber = $minBuildNumberInDatabase;
    if ($timescaleType <> "All")                                                        // ... but if timescale filter used, use that instead
        $minBuildNumber = $minBuildNumberInDatabase;
    return $minBuildNumber;
}

/* Calculate percentage so that very low but not quite zero result is rounded to 1 and almost 100% but not quite is rounded to 99
   Input:   $numerator                              (integer)  The numerator
            $divider                                (integer)  The divider
   Return:  (integer) percentage (0-100)
*/
function calculatePercentage($numerator, $divider)
{
    $percentage = round(100 * ($numerator / $divider));                                 // Must be rounded to integer for sorting to work
    if ($percentage == 0 AND $numerator > 0)                                            // Not quite 0%
        $percentage = 1;
    if ($percentage == 100 AND $numerator <> $divider)                                  // Not quite 100%
        $percentage = 99;
    return $percentage;
}

/* Set pop-up message to help understanding the shown build scope, and to guide how to change the scope
   Input:   $timescaleType                           (string)  The timescale filter
            $timescaleValue                          (date)    The timescale date filter
   Return:  (string) Pop-up message
*/
function setSeeMoreNote($timescaleType, $timescaleValue)
{
    $seeMoreNote = '&nbsp;&nbsp;&nbsp;&raquo; <span class="popupMessage">see more'
        . '<span><b>How to see more builds:</b><br>';
    if ($timescaleType == "All") {
        $seeMoreNote = $seeMoreNote . 'By default the list below includes results checked from the latest ';
        if (CITESTRESULTBUILDCOUNT == 1)
            $seeMoreNote = $seeMoreNote . 'or selected build for clarity and to optimize the performance.';
        else
            $seeMoreNote = $seeMoreNote . CITESTRESULTBUILDCOUNT . ' builds to optimize the performance.';
    } else {
        $seeMoreNote = $seeMoreNote . 'The list below includes the results checked from the builds since '
            . $timescaleValue . '.';
    }
    $seeMoreNote = $seeMoreNote . ' You can include more builds with the timescale filter in the filter box on the top of the page.';
    if ($timescaleType <> "All")
        $seeMoreNote = $seeMoreNote . ' To show only the latest or selected build please clear the timescale filter.';
    $seeMoreNote = $seeMoreNote . '</span></span> &raquo;';
    return $seeMoreNote;
}

/* Scan the test result directory for test result zip files and their xml result files
   Input:   $testResultDirectory                     (string)  Full path to the test result directory (containing the project directories)
            $project                                 (string)  Project name filtered as in the test result directory and database
            $buildCheckType                          (const)   CHECKBUILDSINCE to check all builds since $buildNumber, CHECKBUILDONE to check only the $buildNumber
            $buildNumber                             (integer) Minimum build number to be checked
            $conf                                    (string)  Configuration name filtered
            $booCheckTestcases                       (boolean) TRUE to open the test result files in the zip file and check the test cases, FALSE just to scan the test result file names in the zip
            $arrayFailingAutotestNames               (array)   List of autotest names as in the test result directory and database
   Output:  $arrayFailingAutotestBuildConfigurations (array)   The list of project build-configuration pairs that have the result xml data
            $arrayFailingAutotestAllBuilds           (array)   The count of builds (in all project configurations and in all builds within the timescale) of each autotest
              The following used only when $booCheckTestcases == TRUE:
                $arrayTestcaseNames                  (array)   The names for test cases (all included)
                $arrayTestcaseFailed                 (array)   The count of fails in different project configuration builds for each test case
                $arrayTestcaseAll                    (array)   The count of different project configuration builds for each test case
                $arrayTestcaseConfs                  (array of arrays) The names, and failed and total count of builds of each configuration for each test case
                $failingTestcaseCount                (integer) The total number of failed test cases in all project configuration builds
                $testcaseCount                       (integer) The total number of test cases in all project configuration builds (any result)
                $arrayInvalidTestResultFiles         (array)   List of test results files that couldn't be opened
   Return:  (integer) The lowest build where the test result xml files are available, or MAXCIBUILDNUMBER if not any found
            (Note: The zip file may be empty -> save the data only if xml files found from the zip)
*/
define("CHECKBUILDSINCE", 0);
define("CHECKBUILDONE", 1);
function readProjectTestResultDirectory(
            $testResultDirectory, $project, $buildCheckType, $buildNumber, $conf, $booCheckTestcases, $arrayFailingAutotestNames,
            &$arrayFailingAutotestBuildConfigurations, &$arrayFailingAutotestAllBuilds,
            &$arrayTestcaseNames, &$arrayTestcaseFailed, &$arrayTestcaseAll, &$arrayTestcaseConfs,
            &$failingTestcaseCount, &$testcaseCount, &$arrayInvalidTestResultFiles)
{
    $arrayFailingTestcaseConfNames = array();
    /* Count the number of autotests */
    $autotestCount = count($arrayFailingAutotestNames);
    /* Check Project directory (structure is e.g. "QtBase_stable_Integration/build_03681/macx-ios-clang_OSX_10.8" */
    $projectTestResultDirectory = $testResultDirectory . $project;
    $minBuildNumberInDirectory = MAXCIBUILDNUMBER;                          // For saving the first build where test result xml files are available
    $booTestResultDirectory = FALSE;
    $arrayAllTestcaseNames = array();
    if (file_exists($projectTestResultDirectory)) {
        $booTestResultDirectory = TRUE;
        $directories = new RecursiveIteratorIterator(
            new ParentIterator(
                new RecursiveDirectoryIterator($projectTestResultDirectory)),
                RecursiveIteratorIterator::SELF_FIRST);
        /* Check each build directory */
        foreach ($directories as $directory) {                              // Check each CI project build history (e.g. "build_00220", "build_00219", "build_00218")
            $dirName = substr($directory, strpos($directory, $project) + strlen($project) + 1);         // Cut to e.g. "build_03681/macx-ios-clang_OSX_10.8"
            $buildNumberDirName = CIBUILDDIRECTORYPREFIX . createBuildNumberString($buildNumber);       // Convert "220" -> "build_00220"
            if (strlen($dirName) == strlen($buildNumberDirName))
                continue;                                                   // Skip the main build directory (to check only the configuration directories under it)
            if ($buildCheckType == CHECKBUILDSINCE) {                       // Check builds since the requested build ...
                if (strpos($dirName, CIBUILDDIRECTORYPREFIX) === 0 AND $dirName < $buildNumberDirName)
                    continue;                                               // Skip to next directory if not inside the build scope (calculated from time scope)
            } else {                                                        // ... or the requested build only
                if (strpos($dirName, CIBUILDDIRECTORYPREFIX) === 0 AND strpos($dirName, $buildNumberDirName) === FALSE)
                    continue;                                               // Skip to next directory if not the requested build
            }
            /* Continue if build belongs to the time scale */
            $handle = opendir($directory);
            while (($entry = readdir($handle)) !== FALSE) {                 // Check the results in zip file
                if ($entry == "." || $entry == "..")
                    continue;
                $configuration = substr($dirName, strlen($buildNumberDirName) + 1);                     // Cut to e.g. "macx-ios-clang_OSX_10.8"
                if ($conf <> "All" AND $configuration <> $conf)             // Skip if not the filtered configuration
                    continue;
                $dirNumber = (int)substr($dirName, strlen(CIBUILDDIRECTORYPREFIX), strlen(strval(MAXCIBUILDNUMBER)));    // Cut to e.g. "3681"
                $arrayFailingAutotestBuildConfigurations[] = $dirNumber . FILTERSEPARATOR . $configuration;     // Save each build-configuration pair with xml data to read failure data from database only for these
                if (!in_array($configuration, $arrayFailingTestcaseConfNames))                                  // If configuration name not listed yet ...
                    $arrayFailingTestcaseConfNames[] = $configuration;                                          // ... save it
                $filePath = $directory . '/' . $entry;
                if ($entry == CITESTRESULTSFILE AND is_file($filePath)) {
                    $zip = zip_open($filePath);
                    /* Check if the autotest has been run for this build */
                    while ($zip_entry = zip_read($zip)) {                   // Check all tst_* xml files in the zip
                        $xmlFilePath = zip_entry_name($zip_entry);
                        $xmlFile = basename(zip_entry_name($zip_entry));
                        for ($k=0; $k<$autotestCount; $k++) {               // Loop all failed autotest (Note: The ones that have always passed are excluded)
                            $zipTestFileNameIdentifiers = explode(";",ZIPTESTFILENAMEIDENTIFIERS);
                            $booTestFileNameMatch = FALSE;
                            foreach ($zipTestFileNameIdentifiers as $identifier) {  // Check each identified string for a test file name
                                if (strpos($xmlFile, $arrayFailingAutotestNames[$k] . $identifier) === 0)
                                    $booTestFileNameMatch = TRUE;
                            }
                            if ($booTestFileNameMatch) {                    // Find the match from the list of failed autotests
                                $arrayFailingAutotestAllBuilds[$k]++;       // Increase the count for related autotest
                                if ($minBuildNumberInDirectory > $dirNumber)
                                    $minBuildNumberInDirectory = $dirNumber;        // Save the lowest build where test result xml files are available
                                                                                    // (Note: The zip file may be empty -> save only if xml files found from the zip)

                                /* Open the test result xml files to read the test case results ($booCheckTestcases == TRUE) */
                                if ($booCheckTestcases) {
                                    if (!zip_entry_open($zip, $zip_entry))
                                        die('cannot open zip!');
                                    $xmlResultFile = 'zip://' . $filePath . '#' . $xmlFilePath;
                                    if (!($resultFile = simplexml_load_file($xmlResultFile))) { // Collect the invalid test result files that couldn't be opened
                                        $arrayInvalidTestResultFiles[] = substr($xmlResultFile, strpos($xmlResultFile, $project));
                                    } else {
                                        foreach ($resultFile->children() as $testCase) {
                                            if ($testCase->getName() == "TestFunction") {       // e.g. <TestFunction name="initTestCase">
                                                foreach ($testCase->children() as $result) {
                                                    if ($result->getName() == "Incident") {     // e.g. <Incident type="pass" file="" line="0" /> (inside the TestFunction)
                                                        $testTag = "";
                                                        // Detailed test name can be in the DataTag, e.g. <TestFunction name="test_qBinaryFind">
                                                        //                                                <Incident type="pass" file="" line="0">
                                                        //                                                <DataTag><![CDATA[sorted-duplicate]]></DataTag>
                                                        //                                                </Incident>
                                                        //                                                <Incident ...
                                                        foreach ($result->DataTag as $tag) {
                                                            if ($tag <> "")
                                                                $testTag = '[' . $tag . ']';
                                                        }
                                                        $testcaseFullName = $testCase['name'] . $testTag;               // e.g. test_qBinaryFind[sorted-duplicate]
                                                        /* Find the configuration (the configuration is always available in the $arrayFailingTestcaseConfNames) */
                                                        foreach ($arrayFailingTestcaseConfNames as $key => $confName) {
                                                            if ($confName == $configuration)
                                                                $confId = $key;
                                                        }
                                                        /* Save testcase data */
                                                        $arrayAllTestcaseNames[] = $testcaseFullName;                   // Collect all test cases (duplicate names cleared at the end)
                                                        if (!in_array($testcaseFullName, $arrayTestcaseNames)) { // If not yet listed ...
                                                            $arrayTestcaseNames[] = $testcaseFullName;               // Testcase name
                                                            $testcaseConfData = array(array());
                                                            $testcaseConfData[$confId][FAILINGTESTCASECONFNAME]
                                                                = $arrayFailingTestcaseConfNames[$confId];           // Configuration name for the testcase
                                                            if ($result['type'] == "fail") {
                                                                $arrayTestcaseFailed[]++;                            // Count the number of fails
                                                                $arrayTestcaseAll[]++;                               // Count all (any result)
                                                                $testcaseConfData[$confId][FAILINGTESTCASECONFFAILED]++;
                                                                $testcaseConfData[$confId][FAILINGTESTCASECONFALL]++;
                                                            } else {                                                 // Reserve the index for possible failures from other builds
                                                                $arrayTestcaseFailed[] = 0;
                                                                $arrayTestcaseAll[] = 1;
                                                                $testcaseConfData[$confId][FAILINGTESTCASECONFFAILED] = 0;
                                                                $testcaseConfData[$confId][FAILINGTESTCASECONFALL] = 1;
                                                            }
                                                            $arrayTestcaseConfs[] = $testcaseConfData;               // Save configuration specific data
                                                        } else {                                                     // ... or if already listed
                                                            foreach ($arrayTestcaseNames as $key => $testcaseName) {
                                                                if ($testcaseName == $testcaseFullName) {
                                                                    $arrayTestcaseConfs[$key][$confId][FAILINGTESTCASECONFNAME]
                                                                        = $arrayFailingTestcaseConfNames[$confId];   // Configuration name for the testcase
                                                                    if ($result['type'] == "fail") {
                                                                        $arrayTestcaseFailed[$key]++;                // Count the number of fails
                                                                        $arrayTestcaseAll[$key]++;                   // Count all (any result)
                                                                        $arrayTestcaseConfs[$key][$confId][FAILINGTESTCASECONFFAILED]++;
                                                                        $arrayTestcaseConfs[$key][$confId][FAILINGTESTCASECONFALL]++;
                                                                    } else {
                                                                        $arrayTestcaseAll[$key]++;
                                                                        $arrayTestcaseConfs[$key][$confId][FAILINGTESTCASECONFALL]++;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } // endif foreach as testCase
                                    } // endif else simplexml_load_file
                                } // endif booCheckTestcases

                                break;                                      // Match found, break to next file in zip
                            }
                        }
                    }
                    zip_close($zip);
                }
                clearstatcache();
            }
            closedir($handle);
        } // endif foreach as directory

        /* Calculate/arrange return data */
        $arrayFailingAutotestBuildConfigurations = array_unique($arrayFailingAutotestBuildConfigurations);
        $arrayAllTestcaseNames = array_unique($arrayAllTestcaseNames);
        $testcaseCount = count($arrayTestcaseNames);
        foreach ($arrayTestcaseNames as $key => $testcaseName) {
            if ($arrayTestcaseFailed[$key] > 0)
                $failingTestcaseCount++;
        }
        sort($arrayInvalidTestResultFiles);

    } // endif file_exists()
    return $minBuildNumberInDirectory;
}

/************************************************************/
/* START                                                    */
/************************************************************/

$timeStart = microtime(true);

/* Get the input parameters */
$round = $_GET["round"];
$arrayFilters = array();
$arrayFilter = array();
$filters = $_GET["filters"];
$filters = rawurldecode($filters);            // Decode the encoded parameter (encoding in ajaxrequest.js)
$arrayFilters = explode(FILTERSEPARATOR, $filters);
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERPROJECT]);
$project = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERCONF]);
$conf = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERAUTOTEST]);
$autotest = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERBUILD]);
$build = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERTIMESCALETYPE]);
$timescaleType = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERTIMESCALEVALUE]);
$timescaleValue = $arrayFilter[1];
$arrayFilter = explode(FILTERVALUESEPARATOR, $arrayFilters[FILTERSORTBY]);
$sortBy = $arrayFilter[1];

/* Sort field definitions */
define("AUTOTESTSORTBYNOTSET", 0);
define("AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF", 1);
define("AUTOTESTSORTBYSIGNAUTOTESTINSIGNCONF", 2);
define("AUTOTESTSORTBYINSIGNAUTOTESTBLOCKINGCONF", 3);
define("AUTOTESTSORTBYINSIGNAUTOTESTINSIGNGCONF", 4);
define("AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE", 5);

/* Connect to the server */
require(__DIR__.'/../connect.php');
$timeConnect = microtime(true);
include(__DIR__.'/../commondefinitions.php');

/* Select database */
if ($useMysqli) {
    // Selected in mysqli_connect() call
} else {
    $selectdb="USE $db";
    $result = mysql_query($selectdb) or die ("Failure: Unable to use the database !");
}

/* Check the the latest/selected build number for the Project */
if ($project <> "All") {
    foreach ($_SESSION['arrayProjectName'] as $projectKey => $projectValue) {
        if ($project == $projectValue)
            $latestBuildNumber = $_SESSION['arrayProjectBuildLatest'][$projectKey];
            $minBuildNumberInDirectory = $latestBuildNumber;                        // Initialize, to be calculated later from test results
    }
    $buildNumber = $latestBuildNumber - $build;                                     // Selected build
}

/*************************************************************/
/* NESTED LEVEL 1: No autotest filtering done (default view) */
/*************************************************************/

if ($autotest == "All") {
    echo '<div class="metricsBoxHeader">';
    echo '<div class="metricsBoxHeaderIcon">';
    if ($round == 1)
        echo "<img src=\"images/ajax-loader.gif\" alt=\"loading\">&nbsp&nbsp";      // On the first round show the loading icon
    else
        echo '<a href="javascript:void(0);" class="imgLink" onclick="showMessageWindow(\'ci/msgautotestdashboardlevel1.html\')">
              <img src="images/info.png" alt="info"></a>&nbsp&nbsp';
    echo '</div>';
    echo '<div class="metricsBoxHeaderText">';
    if ($project == "All")
        echo '<b>AUTOTEST DASHBOARD:</b> Select Autotest &nbsp&nbsp&nbsp <i>(filter a Project to see data from all builds with failure %)</i>';
    else
        echo '<b>AUTOTEST DASHBOARD:</b> Select Autotest';
    echo '</div>';
    echo '</div>';

    if (isset($_SESSION['arrayAutotestName'])) {

        /* Get all (failing) Autotest names and required Project data */
        $arrayFailingAutotestNames = array();
        $arrayFailingAutotestNames = $_SESSION['arrayAutotestName'];
        $autotestCount = count($arrayFailingAutotestNames);
        $arrayProjectName = $_SESSION['arrayProjectName'];
        $arrayProjectBuildLatest = $_SESSION['arrayProjectBuildLatest'];
        $arrayProjectBuildLatestTimestamp = $_SESSION['arrayProjectBuildLatestTimestamp'];

        /* Arrays for number and names Configurations for each Autotest in the latest/selected Build (categorised as significant/insignificant) */
        define("SIGNAUTOTESTBLOCKINGCONF", 0);
        $arrayFailingSignAutotestBlockingConfCount = array();
        $arrayFailingSignAutotestBlockingConfNames = array();
        $arrayFailingSignAutotestBlockingConfProjects = array();
        define("SIGNAUTOTESTINSIGNCONF", 1);
        $arrayFailingSignAutotestInsignConfCount = array();
        $arrayFailingSignAutotestInsignConfNames = array();
        $arrayFailingSignAutotestInsignConfProjects = array();
        define("INSIGNAUTOTESTBLOCKINGCONF", 2);
        $arrayFailingInsignAutotestBlockingConfCount = array();
        $arrayFailingInsignAutotestBlockingConfNames = array();
        $arrayFailingInsignAutotestBlockingConfProjects = array();
        define("INSIGNAUTOTESTINSIGNCONF", 3);
        $arrayFailingInsignAutotestInsignConfCount = array();
        $arrayFailingInsignAutotestInsignConfNames = array();
        $arrayFailingInsignAutotestInsignConfProjects = array();

        /* Step 1: Read failing Autotests for the latest/selected Build (for each Project and Configuration) */
        $timeLatestStart = microtime(true);
        $maxCount = 0;                                                              // Max count of Autotests in any category (used for sorting the lists)
        $latestAutotests = 0;                                                       // Total count of Autotests in any category (used to identify if any was found)
        $projectFilter = "";
        $buildFilter = "";
        if ($project <> "All") {                                                    // Project filtering
            $projectFilterLatest = "test_latest.project=\"$project\"";
            $projectFilter = "test.project=\"$project\"";
            $buildFilter = "AND test.build_number=$buildNumber";
        }
        $confFilter = "";
        if ($conf <> "All") {                                                       // Conf filtering
            $confFilterLatest = "AND test_latest.cfg=\"$conf\"";
            $confFilter = "AND test.cfg=\"$conf\"";
        }
        if ($build == 0)                                // Show the latest build ...
            $sql = cleanSqlString(
                   "SELECT name, test_latest.insignificant, test_latest.timestamp, cfg_latest.cfg, cfg_latest.insignificant
                    FROM test_latest left join cfg_latest on (test_latest.project = cfg_latest.project AND
                                                              test_latest.cfg = cfg_latest.cfg AND
                                                              test_latest.build_number = cfg_latest.build_number)
                    WHERE $projectFilterLatest $confFilterLatest");
        else                                            // ... or the selected build
            $sql = cleanSqlString(
                   "SELECT name, test.insignificant, test.timestamp, cfg.cfg, cfg.insignificant
                    FROM test left join cfg on (test.project = cfg.project AND
                                                test.cfg = cfg.cfg AND
                                                test.build_number = cfg.build_number)
                    WHERE $projectFilter $buildFilter $confFilter");
        $dbColumnTestName = 0;
        $dbColumnTestInsignificant = 1;
        $dbColumnTestTimestamp = 2;
        $dbColumnCfgCfg = 3;
        $dbColumnCfgInsignificant = 4;
        $timeLatestSelectStart = microtime(true);
        if ($useMysqli) {
            $result = mysqli_query($conn, $sql);
            $numberOfRows = mysqli_num_rows($result);
        } else {
            $selectdb="USE $db";
            $result = mysql_query($selectdb) or die (mysql_error());
            $result = mysql_query($sql) or die (mysql_error());
            $numberOfRows = mysql_num_rows($result);
        }
        $timeLatestSelectEnd = microtime(true);
        for ($j=0; $j<$numberOfRows; $j++) {                                        // Loop the queried Autotests
            if ($useMysqli)
                $resultRow = mysqli_fetch_row($result);
            else
                $resultRow = mysql_fetch_row($result);
            if ($project == "All" AND $timescaleType == "Since") {                  // When all Projects shown and Timescale filtered
                if ($resultRow[$dbColumnTestTimestamp] < $timescaleValue) {         // ... and this is not within the Timescale ...
                    continue;                                                       // ... skip to the next Autotest (in the for loop)
                }
            }
            if ($resultRow[$dbColumnCfgInsignificant] == 0) {                       // Check the Autotest failing category
                if ($resultRow[$dbColumnTestInsignificant] == 0) {
                    $autotestFailureCategory = SIGNAUTOTESTBLOCKINGCONF;
                } else {
                    $autotestFailureCategory = INSIGNAUTOTESTBLOCKINGCONF;
                }
            } else {
                if ($resultRow[$dbColumnTestInsignificant] == 0) {
                    $autotestFailureCategory = SIGNAUTOTESTINSIGNCONF;
                } else {
                    $autotestFailureCategory = INSIGNAUTOTESTINSIGNCONF;
                }
            }
            for ($k=0; $k<$autotestCount; $k++) {                                   // Loop all the available Autotests to collect data per one autotest
                if ($arrayFailingAutotestNames[$k] == $resultRow[$dbColumnTestName]) {
                    switch ($autotestFailureCategory) {
                        case SIGNAUTOTESTBLOCKINGCONF:
                            if (!strpos($arrayFailingSignAutotestBlockingConfNames[$k],$resultRow[$dbColumnCfgCfg])) {   // Each Conf to be listed only once
                                $arrayFailingSignAutotestBlockingConfCount[$k]++;
                                $latestAutotests++;
                                $arrayFailingSignAutotestBlockingConfNames[$k]
                                    = $arrayFailingSignAutotestBlockingConfNames[$k] . '<br>' . $resultRow[$dbColumnCfgCfg];
                                if ($arrayFailingSignAutotestBlockingConfCount[$k] > $maxCount)
                                    $maxCount = $arrayFailingSignAutotestBlockingConfCount[$k];
                            }
                            $arrayFailingSignAutotestBlockingConfProjects[$k]
                                = $arrayFailingSignAutotestBlockingConfProjects[$k] . '<br>'
                                . $projectValue . ' (' . $resultRow[$dbColumnCfgCfg] . ')';                              // List Projects for each Conf (i.e. one Project may appear several times)
                            break;
                        case SIGNAUTOTESTINSIGNCONF:
                            if (!strpos($arrayFailingSignAutotestInsignConfNames[$k],$resultRow[$dbColumnCfgCfg])) {     // Each Conf to be listed only once
                                $arrayFailingSignAutotestInsignConfCount[$k]++;
                                $latestAutotests++;
                                $arrayFailingSignAutotestInsignConfNames[$k]
                                    = $arrayFailingSignAutotestInsignConfNames[$k] . '<br>' . $resultRow[$dbColumnCfgCfg];
                                if ($arrayFailingSignAutotestInsignConfCount[$k] > $maxCount)
                                    $maxCount = $arrayFailingSignAutotestInsignConfCount[$k];
                            }
                            $arrayFailingSignAutotestInsignConfProjects[$k]
                                = $arrayFailingSignAutotestInsignConfProjects[$k] . '<br>'
                                . $projectValue . ' (' . $resultRow[$dbColumnCfgCfg] . ')';                              // List Projects for each Conf (i.e. one Project may appear several times)
                            break;
                        case INSIGNAUTOTESTBLOCKINGCONF:
                            if (!strpos($arrayFailingInsignAutotestBlockingConfNames[$k],$resultRow[$dbColumnCfgCfg])) { // Each Conf to be listed only once
                                $arrayFailingInsignAutotestBlockingConfCount[$k]++;
                                $latestAutotests++;
                                $arrayFailingInsignAutotestBlockingConfNames[$k]
                                    = $arrayFailingInsignAutotestBlockingConfNames[$k] . '<br>' . $resultRow[$dbColumnCfgCfg];
                                if ($arrayFailingInsignAutotestBlockingConfCount[$k] > $maxCount)
                                    $maxCount = $arrayFailingInsignAutotestBlockingConfCount[$k];
                            }
                            $arrayFailingInsignAutotestBlockingConfProjects[$k]
                                = $arrayFailingInsignAutotestBlockingConfProjects[$k] . '<br>'
                                . $projectValue . ' (' . $resultRow[$dbColumnCfgCfg] . ')';                              // List Projects for each Conf (i.e. one Project may appear several times)
                            break;
                        case INSIGNAUTOTESTINSIGNCONF:
                            if (!strpos($arrayFailingInsignAutotestInsignConfNames[$k],$resultRow[$dbColumnCfgCfg])) {   // Each Conf to be listed only once
                                $arrayFailingInsignAutotestInsignConfCount[$k]++;
                                $latestAutotests++;
                                $arrayFailingInsignAutotestInsignConfNames[$k]
                                    = $arrayFailingInsignAutotestInsignConfNames[$k] . '<br>' . $resultRow[$dbColumnCfgCfg];
                                if ($arrayFailingInsignAutotestInsignConfCount[$k] > $maxCount)
                                    $maxCount = $arrayFailingInsignAutotestInsignConfCount[$k];
                            }
                            $arrayFailingInsignAutotestInsignConfProjects[$k]
                                = $arrayFailingInsignAutotestInsignConfProjects[$k] . '<br>'
                                . $projectValue . ' (' . $resultRow[$dbColumnCfgCfg] . ')';                              // List Projects for each Conf (i.e. one Project may appear several times)
                            break;
                    }
                    break;                                                          // Match found, skip the rest
                }
            }            // Endfor all available Autotests
        }                // Endfor queried Autotests

        /* Save data to session variables to be able to use them in nested level 2 below */
        $_SESSION['arrayFailingSignAutotestBlockingConfCount'] = $arrayFailingSignAutotestBlockingConfCount;
        $_SESSION['arrayFailingSignAutotestBlockingConfNames'] = $arrayFailingSignAutotestBlockingConfNames;
        $_SESSION['arrayFailingSignAutotestBlockingConfProjects'] = $arrayFailingSignAutotestBlockingConfProjects;
        $_SESSION['arrayFailingSignAutotestInsignConfCount'] = $arrayFailingSignAutotestInsignConfCount;
        $_SESSION['arrayFailingSignAutotestInsignConfNames'] = $arrayFailingSignAutotestInsignConfNames;
        $_SESSION['arrayFailingSignAutotestInsignConfProjects'] = $arrayFailingSignAutotestInsignConfProjects;
        $_SESSION['arrayFailingInsignAutotestBlockingConfCount'] = $arrayFailingInsignAutotestBlockingConfCount;
        $_SESSION['arrayFailingInsignAutotestBlockingConfNames'] = $arrayFailingInsignAutotestBlockingConfNames;
        $_SESSION['arrayFailingInsignAutotestBlockingConfProjects'] = $arrayFailingInsignAutotestBlockingConfProjects;
        $_SESSION['arrayFailingInsignAutotestInsignConfCount'] = $arrayFailingInsignAutotestInsignConfCount;
        $_SESSION['arrayFailingInsignAutotestInsignConfNames'] = $arrayFailingInsignAutotestInsignConfNames;
        $_SESSION['arrayFailingInsignAutotestInsignConfProjects'] = $arrayFailingInsignAutotestInsignConfProjects;

        if ($useMysqli) {
            mysqli_free_result($result);                                            // Free result set
        }
        $timeLatestEnd = microtime(true);

        /* Step 2: Read detailed Autotest result data with possible timescale filtering (ONLY ON SECOND ROUND AND WHEN PROJECT FILTER USED) */
        $arrayFailingAutotestFailedBuilds = array();
        $arrayFailingAutotestAllBuilds = array();
        $arrayFailingAutotestFailedPercentage = array();
        $arrayFailingAutotestBuildConfigurations = array();

        $allAutotestsCount = 0;
        $booPrintDetailedResultsTitle = FALSE;
        $booPrintDetailedResultsData = FALSE;
        if (isset($_SESSION['previousProject']) AND $project == "All")
            unset($_SESSION['previousProject']);                                    // Clear the session variable if Project filter cleared
        if ($project <> "All")
            $booPrintDetailedResultsTitle = TRUE;                                   // Title printed only when Project filtered (server performance issue with huge data amount)
        if ($round == 2 AND $project <> "All")
            $booPrintDetailedResultsData = TRUE;                                    // Data printed only on 2nd round and when Project filtered (server performance issue with huge data amount)
        if ($booPrintDetailedResultsData) {
            $timeAllStart = microtime(true);

            /* Step 2.1: All autotests for comparison (read from the autotest xml files) */

            /* Get the first available build number or the first after the selected time scale. Note: Another check is which builds include the test result xml files in the first place (see $minBuildNumberInDirectory) */
            $minBuildNumberInDatabase = MAXCIBUILDNUMBER;
            $projectFilter = "project=\"$project\"";                                // Project is filtered here
            $timescaleFilter = "";
            if ($timescaleType <> "All")
                    $timescaleFilter = "AND timestamp>=\"$timescaleValue\"";
            $sql = cleanSqlString(
                   "SELECT min(build_number)
                    FROM ci
                    WHERE $projectFilter $timescaleFilter");
            $dbColumnCiBuildNumber = 0;
            if ($useMysqli) {
                $result2 = mysqli_query($conn, $sql);
            } else {
                $selectdb = "USE $db";
                $result2 = mysql_query($selectdb) or die (mysql_error());
                $result2 = mysql_query($sql) or die (mysql_error());
            }
            if ($useMysqli)
                $resultRow2 = mysqli_fetch_row($result2);
            else
                $resultRow2 = mysql_fetch_row($result2);
            if ($resultRow2[$dbColumnCiBuildNumber] <> NULL AND $resultRow2[$dbColumnCiBuildNumber] <> "")
                $minBuildNumberInDatabase = $resultRow2[$dbColumnCiBuildNumber];
            if ($useMysqli)
                mysqli_free_result($result2);                                       // Free result set
            $_SESSION['minBuildNumberInDatabase'] = $minBuildNumberInDatabase;      // Save for level 2

            /* Read the test results from the Project directory (structure is e.g. QtBase_stable_Integration/build_03681/macx-ios-clang_OSX_10.8 */
            if (isset($_SESSION['previousProject'])) {
                $previousProject = $_SESSION['previousProject'];
                $previousConfiguration = $_SESSION['previousConfiguration'];
                $previousBuild = $_SESSION['previousBuild'];
                $previousTimescaleType = $_SESSION['previousTimescaleType'];
                $previousTimescaleValue = $_SESSION['previousTimescaleValue'];
            } else {
                $previousProject = "NA";
                $previousConfiguration = "NA";
                $previousBuild = "NA";
                $previousTimescaleType = "NA";
                $previousTimescaleValue = "NA";
            }
            $booReloadTestResults = TRUE;                                                                   // Performance optimization: Check when the test results need to be (re)loaded from the zip files (which takes time)
            if ($project == $previousProject AND $conf == $previousConfiguration AND
                $timescaleType == $previousTimescaleType AND $timescaleValue == $previousTimescaleValue)
                $booReloadTestResults = FALSE;                                                              // No need to reload the test results if project and other filters not changed
            if ($timescaleType == "All" AND $build <> $previousBuild)
                $booReloadTestResults = TRUE;                                                               // Reload if build changed when timescale not filtered (then the test results are shown for selected build)
            if (!$booReloadTestResults) {                                                                   // Use the session variables ...
                $arrayFailingAutotestAllBuilds = $_SESSION['arrayFailingAutotestAllBuilds'];
                $arrayFailingAutotestBuildConfigurations = $_SESSION['arrayFailingAutotestBuildConfigurations'];
                $minBuildNumberInDirectory = $_SESSION['minBuildNumberInDirectory'];
            } else {                                                                                        // ... otherwise read the data from the zip files
                if ($timescaleType == "All") {                                                              // If timescale not filtered read only the latest/selected build
                    $buildCheckType = CHECKBUILDONE;
                    $buildNumberToCheck = $buildNumber;
                } else {                                                                                    // If timescale filtered read all the available builds since the date
                    $buildCheckType = CHECKBUILDSINCE;
                    $buildNumberToCheck = setMinBuildNumberToCheck($latestBuildNumber, $minBuildNumberInDatabase, $timescaleType);
                }
                $minBuildNumberInDirectory = readProjectTestResultDirectory(
                    CITESTRESULTSDIRECTORY, $project, $buildCheckType, $buildNumberToCheck, $conf, FALSE, $arrayFailingAutotestNames,
                    $arrayFailingAutotestBuildConfigurations, $arrayFailingAutotestAllBuilds);              // Returns the first available build number if timescale filtered, otherwise returns the selected build
            }

            $timeAllXmlDirectoryCheckEnd = microtime(true);

            /* Step 2.2: Failed autotests for comparison (read from the database) */

            /* Read failed Autotests from the database only for those builds and configurations that have also the xml data */
            $projectFilter = "project = \"$project\"";                              // Project is filtered here
            $confFilter = "cfg = \"NA\"";                                           // Any value that does NOT match with any cfg
            foreach ($arrayFailingAutotestBuildConfigurations as $buildConfiguration) {     // In format "03681;macx-ios-clang_OSX_10.8"
                $arrayBuildConfiguration = explode(FILTERSEPARATOR, $buildConfiguration);
                $xmlBuild = (int)$arrayBuildConfiguration[0];
                $xmlConf = $arrayBuildConfiguration[1];                             // If configuration filtered, this includes only the filtered configuration (therefore no need to check the $conf here)
                if ($xmlBuild >= $minBuildNumberInDirectory)
                    $confFilter = $confFilter . ' OR (build_number = ' . $xmlBuild . ' AND cfg = "' . $xmlConf . '")';    // Include only the confs that had the xml report file
            }
            $confFilter = "($confFilter)";                                          // Close with () due to OR
            if ($timescaleType == "All")                                            // If timescale not filtered read only the latest/selected build
                $buildFilter = " build_number = $buildNumber";
            else                                                                    // If timescale filtered read all the available builds since the date
                $buildFilter = " build_number >= $minBuildNumberInDirectory";
            $timeAllSelectStart = microtime(true);
            $sql = cleanSqlString(
                   "SELECT name
                    FROM test
                    WHERE $projectFilter AND $buildFilter AND $confFilter");        // (Note: No need to check timescale here, the build_number is used instead
            $dbColumnTestName = 0;
            if ($useMysqli) {
                $result2 = mysqli_query($conn, $sql);
                $numberOfRows2 = mysqli_num_rows($result2);
            } else {
                $selectdb = "USE $db";
                $result2 = mysql_query($selectdb) or die (mysql_error());
                $result2 = mysql_query($sql) or die (mysql_error());
                $numberOfRows2 = mysql_num_rows($result2);
            }

            /* Calculate the builds where autotest has failed */
            for ($j=0; $j<$numberOfRows2; $j++) {
                if ($useMysqli)
                    $resultRow2 = mysqli_fetch_row($result2);
                else
                    $resultRow2 = mysql_fetch_row($result2);
                for ($k=0; $k<$autotestCount; $k++) {                               // Loop all the available Autotests to collect data per one autotest
                    if ($arrayFailingAutotestNames[$k] == $resultRow2[$dbColumnTestName])
                        $arrayFailingAutotestFailedBuilds[$k]++;                    // Save fail count
                }
            }
            if ($useMysqli)
                mysqli_free_result($result2);                                       // Free result set
            $timeAllDbFailedCheckEnd = microtime(true);

            /* Step 2.3: Calculate the failure percentage */
            for ($k=0; $k<$autotestCount; $k++)
                $arrayFailingAutotestFailedPercentage[$k]
                    = round(100 * ($arrayFailingAutotestFailedBuilds[$k] / $arrayFailingAutotestAllBuilds[$k]));  // Must be rounded to integer for sorting to work

            /* Save the calculated data for level 2 and for returning from Level 2 to Level 1 (so that it would not be needed to read the data from xml files) */
            $_SESSION['arrayFailingAutotestFailedBuilds'] = $arrayFailingAutotestFailedBuilds;
            $_SESSION['arrayFailingAutotestAllBuilds'] = $arrayFailingAutotestAllBuilds;
            $_SESSION['arrayFailingAutotestFailedPercentage'] = $arrayFailingAutotestFailedPercentage;
            $_SESSION['minBuildNumberInDirectory'] = $minBuildNumberInDirectory;
            $_SESSION['arrayFailingAutotestBuildConfigurations'] = $arrayFailingAutotestBuildConfigurations;
            $_SESSION['previousProject'] = $project;
            $_SESSION['previousConfiguration'] = $conf;
            $_SESSION['previousBuild'] = $build;
            $_SESSION['previousTimescaleType'] = $timescaleType;
            $_SESSION['previousTimescaleValue'] = $timescaleValue;

            $timeAllEnd = microtime(true);
        } // endif $booPrintDetailedResultsData

        /* Read the timestamp of the latest/selected build and the first build with detailed test result data */
        if ($project <> "All") {
            for ($k=0; $k<=1; $k++) {                                               // Run twice: 0 = latest/selected build, 1 = first build with detailed test result data
                $projectFilter = "project = \"$project\"";                          // Project is filtered here
                if ($k == 0) {
                    if ($build == 0) {                                              // Show the latest build ...
                        $from = "ci_latest";
                        $buildFilter = "";
                    } else {                                                        // ... or the selected build
                        $from = "ci";
                        $buildFilter = "AND build_number = $buildNumber";
                    }
                } else {
                    $from = "ci";
                    $buildFilter = "AND build_number = $minBuildNumberInDirectory";
                }
                $sql = cleanSqlString(
                       "SELECT min(timestamp)
                        FROM $from
                        WHERE $projectFilter $buildFilter");
                $dbColumnCiTimestamp = 0;
                if ($useMysqli) {
                    $result2 = mysqli_query($conn, $sql);
                    $numberOfRows2 = mysqli_num_rows($result2);
                } else {
                    $selectdb = "USE $db";
                    $result2 = mysql_query($selectdb) or die (mysql_error());
                    $result2 = mysql_query($sql) or die (mysql_error());
                    $numberOfRows2 = mysql_num_rows($result2);
                }
                if ($useMysqli)
                    $resultRow2 = mysqli_fetch_row($result2);
                else
                    $resultRow2 = mysql_fetch_row($result2);
                if ($k == 0)
                    $buildTimestamp = $resultRow2[$dbColumnCiTimestamp];
                else
                    $minBuildNumberInDirectoryTimestamp = $resultRow2[$dbColumnCiTimestamp];
                if ($useMysqli)
                    mysqli_free_result($result2);                                   // Free result set
            }
        }

        /* Print the used filters */
        if ($project <> "All" OR $conf <> "All" OR $timescaleType <> "All") {
            echo '<table>';
            if ($project <> "All")
                echo '<tr><td>Project:</td><td class="tableCellBackgroundTitle">' . $project . '</td></tr>';
            if ($conf <> "All")
                echo '<tr><td>Configuration:</td><td class="tableCellBackgroundTitle">' . $conf . '</td></tr>';
            if ($timescaleType == "Since")
                echo '<tr><td>Since:</td><td class="timescaleSince">' . $timescaleValue . '</td></tr>';
            if ($project <> "All")
                echo '<tr><td>Build:</td><td>' . $buildNumber . ' ('
                    . substr($buildTimestamp, 0, strpos($buildTimestamp, " ")) . ')</td></tr>';
            if ($booPrintDetailedResultsData) {
                if ($minBuildNumberInDirectory == MAXCIBUILDNUMBER) {
                    $testResultBuilds = '(not any test result files available)';
                    $testResultBuildsSeeMore = '';
                } else {
                    $testResultBuilds = $minBuildNumberInDirectory . ' ('
                        . substr($minBuildNumberInDirectoryTimestamp, 0, strpos($minBuildNumberInDirectoryTimestamp, " ")) . ')';
                    if ($timescaleType == "Since")
                        $testResultBuilds = $testResultBuilds . ' onwards';
                    $testResultBuildsSeeMore = setSeeMoreNote($timescaleType, $timescaleValue);
                }
                echo '<tr><td>Test Results:</td><td>' . $testResultBuilds . $testResultBuildsSeeMore . '</td></tr>';
            }
            echo '</table>';
            echo '<div class="metricsTitle">';
            echo '<b>Failed autotests</b>';
            echo '</div>';
        }

        /* Set the default sorting */
        if ($booPrintDetailedResultsData) {
            if ($sortBy == AUTOTESTSORTBYNOTSET) {
                if ($minBuildNumberInDirectory == MAXCIBUILDNUMBER)
                    $sortBy = AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF;
                else
                    $sortBy = AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE;                           // Sorting based the Failed % when all builds data available and shown
                }
        } else {
            if ($sortBy == AUTOTESTSORTBYNOTSET)
                $sortBy = AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF;                               // Default sorting is the significant blocking when only the latest/selected build shown
        }

        /* Print the titles */
        echo '<table class="fontSmall">';
        echo '<tr>';                                                                            // First row
        echo '<th></th>';
        if ($timescaleType == "All" AND CITESTRESULTBUILDCOUNT == 1) {                          // Timescale not filtered (and the dashboard is configured to show just the latest build)
            if ($booPrintDetailedResultsTitle)
                echo '<td colspan="7" ';
            else
                echo '<td colspan="4" ';
            if ($project == "All") {                                                            // When Project not filtered the list shows latest builds from any date
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered">';
                echo '<b>LATEST PROJECT BUILDS</b></td>';
            } else {                                                                            // When Project filtered the list shows latest/selected build only
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered tableCellBuildSelected">';
                if ($build == 0)
                    echo 'LATEST BUILD</td>';
                else
                    echo 'BUILD ' . $buildNumber . '</td>';
            }
        }
        if ($timescaleType == "All" AND CITESTRESULTBUILDCOUNT > 1) {                           // Timescale not filtered (and the dashboard is configured to show n latest builds)
            echo '<td colspan="4" ';
            if ($project == "All") {                                                            // When Project not filtered the list shows latest builds from any date
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered">';
                echo '<b>LATEST PROJECT BUILDS</b></td>';
            } else {                                                                            // When Project filtered the list shows the latest/selected build only
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered tableCellBuildSelected">';
                if ($build == 0)
                    echo 'LATEST BUILD</td>';
                else
                    echo 'BUILD ' . $buildNumber . '</td>';
            }
            if ($booPrintDetailedResultsTitle) {
                echo '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered timescaleAll">';
                echo '<b>ALL BUILDS</b></td>';
            }
        }
        if ($timescaleType == "Since") {                                                        // Timescale filtered
            echo '<td colspan="4" ';
            if ($project == "All") {                                                            // When Project not filtered the list shows latest builds since selected date
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered">';
                echo '<b>LATEST PROJECT BUILDS SINCE ' . $timescaleValue . '</b></td>';
            } else {                                                                            // When Project filtered the list shows the latest/selected build only
                echo 'class="tableBottomBorder tableSideBorder tableCellCentered tableCellBuildSelected">';
                if ($build == 0)
                    echo 'LATEST BUILD</td>';
                else
                    echo 'BUILD ' . $buildNumber . '</td>';
            }
            if ($booPrintDetailedResultsTitle) {
                echo '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered timescaleSince">';
                echo 'ALL BUILDS SINCE ' . $timescaleValue . '</td>';
            }
        }
        echo '</tr>';
        echo '<tr>';                                                                            // Second row
        echo '<th></th>';
        echo '<th colspan="2" class="tableBottomBorder tableSideBorder">Failed Significant Autotests</th>';
        echo '<th colspan="2" class="tableBottomBorder tableSideBorder">Failed Insignificant Autotests</th>';
        if ($booPrintDetailedResultsTitle) {
            if ($round == 1) {
                $xmlBuildInfo = 'Detailed Test Results <span class="loading"><span>.</span><span>.</span><span>.</span></span>';
            } else {
                if ($minBuildNumberInDirectory == MAXCIBUILDNUMBER) {             // No builds found with test result xml files
                    $xmlBuildInfo = "(not any Builds with test result files)";
                } else {
                    if ($timescaleType == "All" AND CITESTRESULTBUILDCOUNT == 1)
                        $xmlBuildInfo = "Detailed Test Results";
                    else
                        $xmlBuildInfo = "Detailed Test Results since Build $minBuildNumberInDirectory";
                }
            }
            echo '<th colspan="3" class="tableBottomBorder tableSideBorder">' . $xmlBuildInfo . '</th>';
        }
        echo '</tr>';
        echo '<tr class="tableBottomBorder">';                                                  // Third row
        echo '<th class="tableCellAlignRight"><a href="javascript:void(0);" onclick="showMessageWindow(\'ci/msgfailuredescription.html\')"> Failure category</a></th>';
        echo '<td class="sortField tableLeftBorder tableCellCentered tableCellBackgroundRedDark">';
        if ($sortBy == AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF)
            echo '1) Blocking<br>Confs&nbsp;&nbsp;&nbsp;<b>&diams;</b>';          // Identify selected sorting
        else
            echo '<a href="javascript:void(0);" onclick="filterAutotest(\'All\',' . AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF . ')">
                  1) Blocking<br>Confs&nbsp;&nbsp;&nbsp;<b><img src="images/sort-descending.png" alt="Sort" title="sort descending"></b></a>';
        echo '</td>';
        echo '<td class="sortField tableRightBorder tableCellCentered tableCellBackgroundRed">';
        if ($sortBy == AUTOTESTSORTBYSIGNAUTOTESTINSIGNCONF)
            echo '2) Insignificant<br>Confs&nbsp;&nbsp;&nbsp;<b>&diams;</b>';     // Identify selected sorting
        else
            echo '<a href="javascript:void(0);" onclick="filterAutotest(\'All\',' . AUTOTESTSORTBYSIGNAUTOTESTINSIGNCONF . ')">
                  2) Insignificant<br>Confs&nbsp;&nbsp;&nbsp;<b><img src="images/sort-descending.png" alt="Sort" title="sort descending"></b></a>';
        echo '</td>';
        echo '<td class="sortField tableLeftBorder tableCellCentered tableCellBackgroundRedLight">';
        if ($sortBy == AUTOTESTSORTBYINSIGNAUTOTESTBLOCKINGCONF)
            echo '3) Blocking<br>Confs&nbsp;&nbsp;&nbsp;<b>&diams;</b>';          // Identify selected sorting
        else
            echo '<a href="javascript:void(0);" onclick="filterAutotest(\'All\',' . AUTOTESTSORTBYINSIGNAUTOTESTBLOCKINGCONF . ')">
                  3) Blocking<br>Confs&nbsp;&nbsp;&nbsp;<b><img src="images/sort-descending.png" alt="Sort" title="sort descending"></b></a>';
        echo '</td>';
        echo '<td class="sortField tableRightBorder tableCellCentered tableCellBackgroundRedLight">';
        if ($sortBy == AUTOTESTSORTBYINSIGNAUTOTESTINSIGNGCONF)
            echo '4) Insignificant<br>Confs&nbsp;&nbsp;&nbsp;<b>&diams;</b>';     // Identify selected sorting
        else
            echo '<a href="javascript:void(0);" onclick="filterAutotest(\'All\',' . AUTOTESTSORTBYINSIGNAUTOTESTINSIGNGCONF . ')">
                  4) Insignificant<br>Confs&nbsp;&nbsp;&nbsp;<b><img src="images/sort-descending.png" alt="Sort" title="sort descending"></b></a>';
        echo '</td>';
        if ($booPrintDetailedResultsTitle) {
            echo '<td class="tableBottomBorder tableLeftBorder tableCellCentered">Builds where<br>failed</td>';
            echo '<td class="tableBottomBorder tableCellCentered">Builds where<br>run (all)</td>';
            echo '<td class="sortField tableBottomBorder tableRightBorder tableCellCentered">';
            if ($sortBy == AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE)
                echo 'Failed %<br>&diams;';                                       // Identify selected sorting
            else
                echo '<a href="javascript:void(0);" onclick="filterAutotest(\'All\',' . AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE . ')">
                      Failed %<br><img src="images/sort-descending.png" alt="Sort" title="sort descending"></a>';
            echo '</td>';
        }
        echo '</tr>';

        /* Print list of Autotests */
        $k = 0;
        $listCutMode = FALSE;
        $failingSignAutotestBlockingConfCount = 0;
        $failingSignAutotestInsignConfCount = 0;
        $failingInsignAutotestBlockingConfCount = 0;
        $failingInsignAutotestInsignConfCount = 0;
        $arrayFailingAutotestFailedBuildsSum = 0;
        $arrayFailingAutotestAllBuildsSum = 0;
        $arrayFailingAutotestFailedPercentageSum = 0;
        if ($maxCount < 100)
            $maxCount = 100;                                                            // Loop at least the percentage scale
        for ($countOrder=$maxCount; $countOrder>=0; $countOrder--) {                    // Sort the list by looping from the highest count
            for ($i=0; $i<$autotestCount; $i++) {                                       // Loop the Autotests
                switch ($sortBy) {                                                      // Check the next value to print in sorting
                    case AUTOTESTSORTBYSIGNAUTOTESTBLOCKINGCONF:
                        $sortFieldValue = $arrayFailingSignAutotestBlockingConfCount[$i];
                        break;
                    case AUTOTESTSORTBYSIGNAUTOTESTINSIGNCONF:
                        $sortFieldValue = $arrayFailingSignAutotestInsignConfCount[$i];
                        break;
                    case AUTOTESTSORTBYINSIGNAUTOTESTBLOCKINGCONF:
                        $sortFieldValue = $arrayFailingInsignAutotestBlockingConfCount[$i];
                        break;
                    case AUTOTESTSORTBYINSIGNAUTOTESTINSIGNGCONF:
                        $sortFieldValue = $arrayFailingInsignAutotestInsignConfCount[$i];
                        break;
                    case AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE:
                        $sortFieldValue = $arrayFailingAutotestFailedPercentage[$i];
                        break;
                }
                if ($sortFieldValue == $countOrder) {                                   // Print the ones that are next in the sorting order
                    if ($arrayFailingSignAutotestBlockingConfCount[$i]
                        + $arrayFailingSignAutotestInsignConfCount[$i]
                        + $arrayFailingInsignAutotestBlockingConfCount[$i]
                        + $arrayFailingInsignAutotestInsignConfCount[$i]
                        + $arrayFailingAutotestFailedBuilds[$i] > 0) {                  // Don't print if not any failures in Latest/All Builds
                        if ($k % 2 == 0)
                            echo '<tr>';
                        else
                            echo '<tr class="tableBackgroundColored">';

                        /* Autotest name */
                        echo '<td><a href="javascript:void(0);" onclick="filterAutotest(\'' . $arrayFailingAutotestNames[$i]
                            . '\')">' . $arrayFailingAutotestNames[$i] . '</a></td>';

                        /* Latest/Selected Build: Significant Autotests in blocking Configuration (with names as a popup) */
                        if ($arrayFailingSignAutotestBlockingConfCount[$i] > 0) {
                            echo '<td class="tableLeftBorder tableCellCentered fontColorRed"><span class="popupMessage">'
                                . $arrayFailingSignAutotestBlockingConfCount[$i]
                                . '<span><b>' . $arrayFailingAutotestNames[$i] . ':</b><br>'
                                . substr($arrayFailingSignAutotestBlockingConfNames[$i],strlen('<br>'))
                                . '</span></span></td>';                                // Skip leading '<br>' set above
                        } else {
                            echo '<td class="tableLeftBorder tableCellCentered">-</td>';
                        }

                        /* Latest/Selected Build: Significant Autotests in insignificant Configuration (with names as a popup) */
                        if ($arrayFailingSignAutotestInsignConfCount[$i] > 0)
                            echo '<td class="tableCellCentered"><span class="popupMessage">'
                                . $arrayFailingSignAutotestInsignConfCount[$i]
                                . '<span><b>' . $arrayFailingAutotestNames[$i] . ':</b><br>'
                                . substr($arrayFailingSignAutotestInsignConfNames[$i],strlen('<br>'))
                                . '</span></span></td>';                                // Skip leading '<br>' set above
                        else
                            echo '<td class="tableCellCentered">-</td>';

                        /* Latest/Selected Build: Insignificant Autotests in blocking Configuration (with names as a popup) */
                        if ($arrayFailingInsignAutotestBlockingConfCount[$i] > 0)
                            echo '<td class="tableLeftBorder tableCellCentered"><span class="popupMessage">'
                                . $arrayFailingInsignAutotestBlockingConfCount[$i]
                                . '<span><b>' . $arrayFailingAutotestNames[$i] . ':</b><br>'
                                . substr($arrayFailingInsignAutotestBlockingConfNames[$i],strlen('<br>'))
                                . '</span></span></td>';                                // Skip leading '<br>' set above
                        else
                            echo '<td class="tableLeftBorder tableCellCentered">-</td>';

                        /* Latest/Selected Build: Insignificant Autotests in insignificant Configuration (with names as a popup) */
                        if ($arrayFailingInsignAutotestInsignConfCount[$i] > 0)
                            echo '<td class="tableRightBorder tableCellCentered"><span class="popupMessage">'
                                . $arrayFailingInsignAutotestInsignConfCount[$i]
                                . '<span><b>' . $arrayFailingAutotestNames[$i] . ':</b><br>'
                                . substr($arrayFailingInsignAutotestInsignConfNames[$i],strlen('<br>'))
                                . '</span></span></td>';                                // Skip leading '<br>' set above
                        else
                            echo '<td class="tableRightBorder tableCellCentered">-</td>';

                        if ($booPrintDetailedResultsTitle) {
                            if ($booPrintDetailedResultsData) {
                                /* Detailed test results: Builds where failed */
                                if ($arrayFailingAutotestFailedBuilds[$i] > 0)
                                    echo '<td class="tableLeftBorder tableCellCentered">'
                                        . $arrayFailingAutotestFailedBuilds[$i] . '</td>';
                                else
                                    echo '<td class="tableLeftBorder tableCellCentered">-</td>';

                                /* Detailed test results: Builds where run (all) */
                                if ($arrayFailingAutotestAllBuilds[$i] > 0)
                                    echo '<td class="tableCellCentered">'
                                        . $arrayFailingAutotestAllBuilds[$i] . '</td>';
                                else
                                    if ($booTestResultDirectory)
                                        echo '<td class="tableCellCentered">-</td>';
                                    else
                                        echo '<td class="tableCellCentered">(n/a)</td>';

                                /* Detailed test results: Failed % */
                                if ($arrayFailingAutotestFailedPercentage[$i] > 0) {
                                    if ($arrayFailingAutotestFailedPercentage[$i] >= AUTOTESTFAILUREWARNINGLEVEL)
                                        echo '<td class="tableRightBorder tableCellCentered fontColorRed">';
                                    else
                                        echo '<td class="tableRightBorder tableCellCentered">';
                                    echo $arrayFailingAutotestFailedPercentage[$i] . '%</td>';
                                } else {
                                    echo '<td class="tableRightBorder tableCellCentered">-</td>';
                                }

                            } else {
                                echo '<td class="tableLeftBorder tableCellCentered"></td>';
                                echo '<td class="tableCellCentered"></td>';
                                echo '<td class="tableRightBorder tableCellCentered"></td>';
                            }
                        }

                        echo '</tr>';
                        $k++;

                        /* Count the totals */
                        $failingSignAutotestBlockingConfCount = $failingSignAutotestBlockingConfCount + $arrayFailingSignAutotestBlockingConfCount[$i];
                        $failingSignAutotestInsignConfCount = $failingSignAutotestInsignConfCount + $arrayFailingSignAutotestInsignConfCount[$i];
                        $failingInsignAutotestBlockingConfCount = $failingInsignAutotestBlockingConfCount + $arrayFailingInsignAutotestBlockingConfCount[$i];
                        $failingInsignAutotestInsignConfCount = $failingInsignAutotestInsignConfCount + $arrayFailingInsignAutotestInsignConfCount[$i];
                        $arrayFailingAutotestFailedBuildsSum = $arrayFailingAutotestFailedBuildsSum + $arrayFailingAutotestFailedBuilds[$i];
                        $arrayFailingAutotestAllBuildsSum = $arrayFailingAutotestAllBuildsSum + $arrayFailingAutotestAllBuilds[$i];

                    }
                    if ($k > 12 AND !isset($_SESSION['failingAutotestsShowFullList'])) {     // List cut mode: By default show only n items in the list to leave room for possible other metrics boxes
                        $listCutMode = TRUE;
                        break;
                    }
                }         // Endif sorting order
            }             // Endfor Autotests
        }                 // Endfor sorting
        $printedAutotests = $k;

        /* Print Totals summary row */
        if ($listCutMode == FALSE) {
            $arrayFailingAutotestFailedPercentageSum = 100 * round($arrayFailingAutotestFailedBuildsSum / $arrayFailingAutotestAllBuildsSum, 2);
            echo '<tr>';
            echo '<td class="tableRightBorder tableTopBorder">total (' . $printedAutotests . ')</td>';
            echo '<td class="tableTopBorder tableCellCentered">' . $failingSignAutotestBlockingConfCount . '</td>';
            echo '<td class="tableRightBorder tableTopBorder tableCellCentered">' . $failingSignAutotestInsignConfCount . '</td>';
            echo '<td class="tableTopBorder tableCellCentered">' . $failingInsignAutotestBlockingConfCount . '</td>';
            echo '<td class="tableRightBorder tableTopBorder tableCellCentered">' . $failingInsignAutotestInsignConfCount . '</td>';
            if ($booPrintDetailedResultsTitle) {
                if ($booPrintDetailedResultsData) {
                    echo '<td class="tableTopBorder tableCellCentered">' . $arrayFailingAutotestFailedBuildsSum . '</td>';
                    echo '<td class="tableTopBorder tableCellCentered">' . $arrayFailingAutotestAllBuildsSum . '</td>';
                    echo '<td class="tableRightBorder tableTopBorder tableCellCentered">' . $arrayFailingAutotestFailedPercentageSum . '%</td>';
                } else {
                    echo '<td class="tableTopBorder tableCellCentered"></td>';
                    echo '<td class="tableTopBorder tableCellCentered"></td>';
                    echo '<td class="tableRightBorder tableTopBorder tableCellCentered"></td>';
                }
            }
            echo '</tr>';
        }
        echo '</table>';

        if ($round == 2 AND !isset($_SESSION['failingAutotestsShowFullList'])) {
            echo '<br/><a href="javascript:void(0);" onclick="filterAutotest(\'All\')">Show full list...</a><br/><br/>';  // List cut mode: If only first n items shown, add a link to see all
            $_SESSION['failingAutotestsShowFullList'] = TRUE;                                                             // List cut mode: After refreshing the metrics box, show all items instead (set below to return the default 'cut mode')
        }

    } else {
        echo '<br/>Filter values not ready or they are expired, please <a href="javascript:void(0);" onclick="reloadFilters()">reload</a> ...';
    }

    /* Elapsed time */
    if ($showElapsedTime) {
        $timeEnd = microtime(true);
        $time = round($timeEnd - $timeStart, 4);
        $timeDbConnect = round($timeConnect - $timeStart, 4);
        $timeLatest = round($timeLatestEnd - $timeLatestStart, 4);
        $timeLatestSelect = round($timeLatestSelectEnd - $timeLatestSelectStart, 4);
        $timeLatestCalculation = round($timeLatest - $timeLatestSelect, 4);
        if (isset($timeAllEnd)) {
            $timeAll = round($timeAllEnd - $timeAllStart, 4);
            $timeAllXml = round($timeAllXmlDirectoryCheckEnd - $timeAllStart, 4);
            $timeAllDb = round($timeAllDbFailedCheckEnd - $timeAllXmlDirectoryCheckEnd, 4);
            $timeAllCalculation = round($timeAll - $timeAllXml - $timeAllDb, 4);
        }
        echo "<div class=\"elapdedTime\">";
        echo "<ul><li>";
        echo "<b>Total time:</b>&nbsp $time s (round $round)<br>";
        echo "Latest builds: $timeLatest s
            (database connect time: $timeDbConnect s,
             database read time: $timeLatestSelect s,
             calculation: $timeLatestCalculation s)<br>";
        if (isset($timeAll))
            echo "All builds:&nbsp&nbsp&nbsp&nbsp&nbsp $timeAll s
            (database connect time: $timeDbConnect s,
             directory read time: $timeAllXml s,
             database read time: $timeAllDb s,
             calculation: $timeAllCalculation s)<br>";
        echo "</li></ul>";
        echo "</div>";
    }

}

/*************************************************************/
/* NESTED LEVEL 2: Autotest filtered                         */
/*************************************************************/

if ($autotest <> "All") {
    echo '<div class="metricsBoxHeader">';
    echo '<div class="metricsBoxHeaderIcon">';
    if ($round == 1)
        echo "<img src=\"images/ajax-loader.gif\" alt=\"loading\">&nbsp&nbsp";  // On the first round show the loading icon
    else
        echo '<a href="javascript:void(0);" class="imgLink" onclick="showMessageWindow(\'ci/msgautotestdashboardlevel2.html\')">
              <img src="images/info.png" alt="info"></a>&nbsp&nbsp';
    echo '</div>';
    echo '<div class="metricsBoxHeaderText">';
    echo '<b>AUTOTEST DASHBOARD:</b> <a href="javascript:void(0);" onclick="filterAutotest(\'All\')">Select Autotest</a> -> ' . $autotest;
    echo '</div>';
    echo '</div>';

    /* Get the data calculated on level 1 */
    $arrayFailingAutotestNames = array();
    $arrayFailingAutotestNames = $_SESSION['arrayAutotestName'];
    $autotestCount = count($arrayFailingAutotestNames);
    $arrayFailingAutotestFailedBuilds = array();
    $arrayFailingAutotestFailedBuilds = $_SESSION['arrayFailingAutotestFailedBuilds'];
    $arrayFailingAutotestAllBuilds = array();
    $arrayFailingAutotestAllBuilds = $_SESSION['arrayFailingAutotestAllBuilds'];
    $arrayFailingAutotestFailedPercentage = array();
    $arrayFailingAutotestFailedPercentage = $_SESSION['arrayFailingAutotestFailedPercentage'];
    $arrayAutotestName = array();
    $arrayAutotestName[] = $autotest;                                           // Save selected autotest into array for the readProjectTestResultDirectory function call below

    if (isset($_SESSION['arrayAutotestName'])) {
        foreach ($_SESSION['arrayAutotestName'] as $key => $value) {
            /* Selected Autotest */
            if ($autotest == $value) {
                $timeAutotestHistoryStart = microtime(true);

                if ($project <> "All") {
                    /* Read the timestamp of the latest/selected build */
                    $projectFilter = "project = \"$project\"";                          // Project is filtered here
                    if ($build == 0) {                                                  // Show the latest build ...
                        $from = "ci_latest";
                        $buildFilter = "";
                    } else {                                                            // ... or the selected build
                        $from = "ci";
                        $buildFilter = "AND build_number = $buildNumber";
                    }
                    $sql = cleanSqlString(
                           "SELECT timestamp
                            FROM $from
                            WHERE $projectFilter $buildFilter");
                    $dbColumnCiTimestamp = 0;
                    if ($useMysqli) {
                        $result2 = mysqli_query($conn, $sql);
                        $numberOfRows2 = mysqli_num_rows($result2);
                    } else {
                        $selectdb = "USE $db";
                        $result2 = mysql_query($selectdb) or die (mysql_error());
                        $result2 = mysql_query($sql) or die (mysql_error());
                        $numberOfRows2 = mysql_num_rows($result2);
                    }
                    if ($useMysqli)
                        $resultRow2 = mysqli_fetch_row($result2);
                    else
                        $resultRow2 = mysql_fetch_row($result2);
                    $buildTimestamp = $resultRow2[$dbColumnCiTimestamp];
                    if ($useMysqli)
                        mysqli_free_result($result2);                                   // Free result set
                    /* Read the timestamp of the first build inside the selected timescale */
                    $firstTimescaleBuild = MAXCIBUILDNUMBER;
                    if ($timescaleType <> "All") {
                        $from = "ci";
                        $timescaleFilter = "AND timestamp >= \"$timescaleValue\"";
                        $sql = cleanSqlString(
                               "SELECT min(build_number)
                                FROM $from
                                WHERE $projectFilter $timescaleFilter");
                        $dbColumnCiBuildNumber = 0;
                        if ($useMysqli) {
                            $result2 = mysqli_query($conn, $sql);
                            $numberOfRows2 = mysqli_num_rows($result2);
                        } else {
                            $selectdb = "USE $db";
                            $result2 = mysql_query($selectdb) or die (mysql_error());
                            $result2 = mysql_query($sql) or die (mysql_error());
                            $numberOfRows2 = mysql_num_rows($result2);
                        }
                        if ($useMysqli)
                            $resultRow2 = mysqli_fetch_row($result2);
                        else
                            $resultRow2 = mysql_fetch_row($result2);
                        if ($resultRow2[$dbColumnCiBuildNumber] <> NULL AND $resultRow2[$dbColumnCiBuildNumber] <> "")
                            $firstTimescaleBuild = $resultRow2[$dbColumnCiBuildNumber];
                        if ($useMysqli)
                            mysqli_free_result($result2);                               // Free result set
                    }
                }

                /* Print the used filters */
                echo '<table>';
                echo '<tr><td>Autotest: </td><td class="tableCellBackgroundTitle">' . $autotest . '</td></tr>';
                if ($project <> "All")
                    echo '<tr><td>Project: </td><td class="tableCellBackgroundTitle">' . $project . '</td></tr>';
                if ($conf <> "All")
                    echo '<tr><td>Configuration: </td><td class="tableCellBackgroundTitle">' . $conf . '</td></tr>';
                if ($timescaleType == "Since")
                    echo '<tr><td>Since:</td><td class="timescaleSince">' . $timescaleValue . '</td></tr>';
                if ($project <> "All")
                    echo '<tr><td>Build:</td><td>' . $buildNumber . ' ('
                        . substr($buildTimestamp, 0, strpos($buildTimestamp, " ")) . ')</td></tr>';
               echo '</table>';

                /* 1. Autotest history */

                /* Read Autotest history data from the database */
                $projectFilter = "";
                if ($project <> "All")
                    $projectFilter = "AND project=\"$project\"";
                $confFilter = "";
                if ($conf <> "All")
                    $confFilter = " AND cfg=\"$conf\"";
                $sql = cleanSqlString(
                       "SELECT name, project, build_number, cfg, insignificant, timestamp
                        FROM test
                        WHERE name=\"$autotest\" $projectFilter $confFilter
                        ORDER BY project, build_number, cfg");                            // (Note: Timescale filter not used because it is very slow; Timescale checked instead when looping the data)
                $dbColumnTestName = 0;
                $dbColumnTestProject = 1;
                $dbColumnTestBuildNumber = 2;
                $dbColumnTestCfg = 3;
                $dbColumnTestInsignificant = 4;
                $dbColumnTestTimestamp = 5;
                if ($useMysqli) {
                    $result = mysqli_query($conn, $sql);
                    $numberOfRows = mysqli_num_rows($result);
                } else {
                    $selectdb="USE $db";
                    $result = mysql_query($selectdb) or die (mysql_error());
                    $result = mysql_query($sql) or die (mysql_error());
                    $numberOfRows = mysql_num_rows($result);
                }

                /* Save the Project, Conf and Build counts for the Autotest */
                $arrayFailingAutotestProjectNames = array();
                $arrayFailingAutotestProjectNames = $_SESSION['arrayProjectName'];
                $arrayFailingAutotestProjectConfNames = array();
                $arrayFailingAutotestProjectConfBuilds = array();
                $arrayFailingAutotestConfNames = array();
                $arrayFailingAutotestConfBuilds = array();
                $checkedProject = "";
                $checkedProjectCount = 0;
                for ($j=0; $j<$numberOfRows; $j++) {
                    if ($useMysqli)
                        $resultRow = mysqli_fetch_row($result);
                    else
                        $resultRow = mysql_fetch_row($result);
                    if ($resultRow[$dbColumnTestProject] <> $checkedProject) {                      // Clear Project specific Conf list when Project changes (the database list is in Project order)
                        $arrayFailingAutotestConfNames = array();
                        $arrayFailingAutotestConfBuilds = array();
                        $checkedProject = $resultRow[$dbColumnTestProject];
                        $checkedProjectCount++;
                    }
                    foreach ($arrayFailingAutotestProjectNames as $projectKey => $projectValue) {   // Find the correct Project
                        if ($projectValue == $resultRow[$dbColumnTestProject]) {
                            foreach ($_SESSION['arrayConfName'] as $confKey => $confValue) {        // Find the correct Configuration
                                if ($confValue == $resultRow[$dbColumnTestCfg]) {
                                    $arrayFailingAutotestConfNames[$confKey] = $confValue;
                                    $confString = ',' . $resultRow[$dbColumnTestBuildNumber]
                                        . '-' . $resultRow[$dbColumnTestInsignificant]
                                        . '-' . $resultRow[$dbColumnTestTimestamp] . ',';           // Format is ",buildNumber-testInsign" (where testInsign = 0/1); This will be used later for search usage when printing
                                    $arrayFailingAutotestConfBuilds[$confKey] = $arrayFailingAutotestConfBuilds[$confKey] . $confString;
                                    break;                                                          // Match found, skip the rest
                                }
                            }
                            $arrayFailingAutotestProjectConfNames[$projectKey] = $arrayFailingAutotestConfNames;     // Save Project specific Conf list (it uses the Project and Conf ids as saved in the initial loading of the page)
                            $arrayFailingAutotestProjectConfBuilds[$projectKey] = $arrayFailingAutotestConfBuilds;
                            break;                                                                  // Match found, skip the rest
                        }
                    }
                }

                if ($useMysqli)
                    mysqli_free_result($result);                                                    // Free result set

                /* Print Autotest history data */
                echo '<div class="metricsTitle">';
                echo '<b>Result history by Project Configuration</b> in last ' . HISTORYBUILDCOUNT . ' Builds';
                echo '</div>';
                echo '<table class="fontSmall">';
                echo '<tr class="tableCellAlignLeft">';
                echo '<th></th>';
                echo '<th></th>';
                echo '<th colspan="' . HISTORYBUILDCOUNT . '" class="tableSideBorder">&nbsp;';
                if ($project <> "All") {
                    echo 'Results in Builds';
                    if ($timescaleType == "Since")
                        echo ' (since ' . $timescaleValue . ')';
                    echo ' - see <a href="javascript:void(0);" onclick="showMessageWindow(\'ci/msgautotestresultdescription.html\')">notation</a>';
                }
                echo '</th>';
                echo '</tr>';
                echo '<tr class="tableCellAlignLeft">';
                echo '<th class="tableBottomBorder">Project';
                if ($project <> "All" AND $checkedProjectCount > 0)                                 // When a project filtered and some data found
                    echo ' - <a href="javascript:void(0);" onclick="filterProjectAutotest(\'All\''
                        . ',\'' . $autotest . '\')">see all</a>';                                   // ... add link to filter all projects for this autotest
                echo '</th>';
                echo '<th class="tableBottomBorder">Configuration</th>';
                if ($project == "All") {
                    echo '<th colspan="' . HISTORYBUILDCOUNT . '" class="tableBottomBorder tableSideBorder">Results in Builds';
                    if ($timescaleType == "Since")
                        echo ' (since ' . $timescaleValue . ')';
                    echo ' - see <a href="javascript:void(0);" onclick="showMessageWindow(\'ci/msgautotestresultdescription.html\')">notation</a>';
                    echo '</th>';
                } else {
                    $lastPrintedBuild = $latestBuildNumber;
                    $firstPrintedBuild = 1;
                    if ($lastPrintedBuild > HISTORYBUILDCOUNT)                                      // Limit number of Builds printed (the last HISTORYBUILDCOUNT ones)
                        $firstPrintedBuild = $lastPrintedBuild - HISTORYBUILDCOUNT + 1;
                    if ($lastPrintedBuild <= HISTORYBUILDCOUNT) {                                   // If latest Build number is less than the HISTORYBUILDCOUNT ...
                        for ($i=1; $i<=HISTORYBUILDCOUNT-$lastPrintedBuild; $i++) {
                            if (HISTORYBUILDCOUNT - $lastPrintedBuild >= $i)
                                echo '<td class="tableBottomBorder tableSideBorder"></td>';         // ... print empty cells to the left
                        }
                    }
                    for ($i=$firstPrintedBuild; $i<=$lastPrintedBuild; $i++) {                      // Print the Builds
                        $filteredBuild = '<b>' . $i . '</b>';
                        $cellColor = '<td class="tableBottomBorder tableSideBorder tableCellCentered">';
                        if ($timescaleType == "All") {
                            $buildNumberOffset = $latestBuildNumber - $i;
                            if ($buildNumberOffset == $build) {
                                $filteredBuild = $i;
                                $cellColor = '<td class="tableBottomBorder tableSideBorder tableCellCentered tableCellBuildSelected">';
                            }
                        } else {
                            if ($i >= $firstTimescaleBuild)
                                $cellColor = '<td class="tableBottomBorder tableSideBorder tableCellCentered timescaleSince">';
                        }
                        echo $cellColor . $filteredBuild . '</td>';
                    }
                }
                echo '</tr>';
                $arrayProjectBuildLatest = $_SESSION['arrayProjectBuildLatest'];
                $k = 0;
                $previousProject = "";
                foreach ($arrayFailingAutotestProjectNames as $projectKey => $projectValue) {
                    foreach ($_SESSION['arrayConfName'] as $confKey => $confValue) {
                        if ($arrayFailingAutotestProjectConfNames[$projectKey][$confKey] <> "") {
                            if ($k % 2 == 0)
                                echo '<tr>';
                            else
                                echo '<tr class="tableBackgroundColored">';
                            if ($projectValue == $previousProject) {                                // For better readability print the Project (and a line) only when it changes
                                echo '<td></td>';
                                echo '<td>' . $confValue . '</td>';
                            } else {
                                echo '<td class="tableTopBorder"><a href="javascript:void(0);" onclick="filterProjectAutotest(\''
                                    . $projectValue . '\'' . ',\'' . $autotest . '\')">' . $projectValue . '</a></td>';   // Link to filter the project and autotest
                                echo '<td class="tableTopBorder">' . $confValue . '</td>';
                            }
                            $previousProject = $projectValue;
                            $lastPrintedBuild = $arrayProjectBuildLatest[$projectKey];
                            $firstPrintedBuild = 1;
                            if ($lastPrintedBuild > HISTORYBUILDCOUNT)                              // Limit number of Builds printed (the last HISTORYBUILDCOUNT ones)
                                $firstPrintedBuild = $lastPrintedBuild - HISTORYBUILDCOUNT + 1;
                            if ($lastPrintedBuild <= HISTORYBUILDCOUNT) {                           // If latest Build number is less than the HISTORYBUILDCOUNT ...
                                for ($i=1; $i<=HISTORYBUILDCOUNT-$lastPrintedBuild; $i++) {
                                    if (HISTORYBUILDCOUNT - $lastPrintedBuild >= $i)
                                        echo '<td class="tableSingleBorder"></td>';                 // ... print empty cells to the left
                                }
                            }
                            for ($i=$firstPrintedBuild; $i<=$lastPrintedBuild; $i++) {              // Print the Builds
                                /* Check Configuration result and significance from database (both for failed and successful Autotests) */
                                $sql = cleanSqlString(
                                       "SELECT result, insignificant, timestamp
                                        FROM cfg
                                        WHERE cfg=\"$confValue\" AND project=\"$projectValue\" AND build_number=$i");    // Will return one row
                                $dbColumnCfgResult = 0;
                                $dbColumnCfgInsignificant = 1;
                                $dbColumnCfgTimestamp = 2;
                                if ($useMysqli) {
                                    $result2 = mysqli_query($conn, $sql);
                                    $resultRow2 = mysqli_fetch_row($result2);
                                } else {
                                    $selectdb="USE $db";
                                    $result2 = mysql_query($selectdb) or die (mysql_error());
                                    $result2 = mysql_query($sql) or die (mysql_error());
                                    $resultRow2 = mysql_fetch_row($result2);
                                }
                                $buildResult = "other";
                                if ($resultRow2[$dbColumnCfgResult] == "SUCCESS")
                                    $buildResult = "SUCCESS";
                                if ($resultRow2[$dbColumnCfgResult] == "FAILURE")
                                    $buildResult = "FAILURE";
                                $booBuildSign = FALSE;
                                if ($resultRow2[$dbColumnCfgInsignificant] == 0)
                                    $booBuildSign = TRUE;
                                $booBuildOutOfTimescale = FALSE;
                                if ($timescaleType == "Since")
                                    if ($resultRow2[$dbColumnCfgTimestamp] < $timescaleValue)
                                        $booBuildOutOfTimescale = TRUE;
                                /* Check Autotest result and significance from the array saved above */
                                $booSignAutotest = strpos(',' . $arrayFailingAutotestProjectConfBuilds[$projectKey][$confKey], ',' . strval($i) . '-0');
                                $booFailedAutotest = strpos(',' . $arrayFailingAutotestProjectConfBuilds[$projectKey][$confKey], ',' . strval($i) . '-');
                                $buildNumberString = createBuildNumberString($i);
                                /* Print the failed Build */
                                if ($booFailedAutotest) {
                                    if ($booSignAutotest) {
                                        if ($booBuildSign) {
                                            if ($booBuildOutOfTimescale) {
                                                // Dark red background (and bold) to indicate significant failure in blocking Conf, grey font color to indicate out of Timescale
                                                echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRedDark fontColorGrey"><b>' . $i . '</b></td>';
                                            } else {
                                                // Dark red background (and bold) to indicate significant failure in blocking Conf; link to log file
                                                echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRedDark"><b>
                                                    <a href="' . LOGFILEPATHCI . $projectValue . '/build_' . $buildNumberString
                                                    . '/' . $confValue . '/log.txt.gz" target="_blank">' . $i . '</a></b></td>';
                                            }
                                        } else {
                                            if ($booBuildOutOfTimescale) {
                                                // Red background to indicate significant failure in insignificant Conf, grey font color to indicate out of Timescale
                                                echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRed fontColorGrey">' . $i . '</td>';
                                            } else {
                                                // Red background to indicate significant failure in insignificant Conf; link to log file
                                                echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRed">
                                                    <a href="' . LOGFILEPATHCI . $projectValue . '/build_' . $buildNumberString
                                                    . '/' . $confValue . '/log.txt.gz" target="_blank">' . $i . '</a></td>';
                                            }
                                        }
                                    } else {
                                        if ($booBuildOutOfTimescale) {
                                            // Light red background to indicate insignificant failure, grey font color to indicate out of Timescale
                                            echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRedLight fontColorGrey">' . $i . '</td>';
                                        } else {
                                            // Light red background to indicate insignificant failure; link to log file
                                            echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundRedLight">
                                                    <a href="' . LOGFILEPATHCI . $projectValue . '/build_' . $buildNumberString
                                                    . '/' . $confValue . '/log.txt.gz" target="_blank">' . $i . '</a></td>';
                                        }
                                    }
                                /* Print the successful or not run Build */
                                } else {
                                    if ($buildResult == "SUCCESS") {
                                        if ($booBuildOutOfTimescale) {
                                            // Green background to indicate success, grey font color to indicate out of Timescale
                                            echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundGreen fontColorGrey">' . $i . '</td>';
                                        } else {
                                            // Green background to indicate success; log file link
                                            echo '<td class="tableSingleBorder tableCellCentered tableCellBackgroundGreen">
                                                  <a href="' . LOGFILEPATHCI . $projectValue . '/build_' . $buildNumberString
                                                  . '/' . $confValue . '/log.txt.gz" target="_blank">' . $i . '</a></td>';
                                        }
                                    } else {       // It's not checked whether the failed Build has some failed Autotests or not i.e. to interpret if the Autotest here was SUCCESS or not run at all i.e. the Build was aborted
                                        if ($booBuildOutOfTimescale) {
                                            // White background to indicate not a failure, grey font color to indicate out of Timescale
                                            echo '<td class="tableSingleBorder tableCellCentered fontColorGrey">' . $i . '</td>';
                                        } else {
                                            // White background to indicate not a failure; log file link
                                            echo '<td class="tableSingleBorder tableCellCentered">
                                                  <a href="' . LOGFILEPATHCI . $projectValue . '/build_' . $buildNumberString
                                                  . '/' . $confValue . '/log.txt.gz" target="_blank">' . $i . '</a></td>';
                                        }
                                    }
                                }
                            }
                            echo '</tr>';
                            $k++;
                        }
                    }
                }
                echo '<tr class="tableTopBorder"><td></td><td></td><td colspan="' . HISTORYBUILDCOUNT . '"></td></tr>';    // Print bottom line to the end of the table
                echo '</table><br/>';
                if ($useMysqli)
                    mysqli_free_result($result2);                           // Free result set
                $timeAutotestHistoryEnd = microtime(true);

                /* 2. Autotest case data */

                $arrayTestcaseNames = array();
                $arrayTestcaseFailed = array();
                $arrayTestcaseAll = array();
                $arrayInvalidTestResultFiles = array();
                $arrayTestcaseConfs = array();
                $failingTestcaseCount = 0;
                $testcaseCount = 0;
                if ($round == 1) {
                    echo '<div class="metricsTitle">';
                    echo '<b>Test cases <span class="loading"><span>.</span><span>.</span><span>.</span></span> </b>';
                    echo '</div>';
                } else {
                    echo '<div class="metricsTitle">';
                    echo '<b>Test cases</b>';                                                           // Title to be continued below with build details ...
                    if ($checkedProjectCount == 1) {                                                    // Data shown only for one project for performance reasons

                        /* Get the first available/filtered build in database */
                        $minBuildNumberInDatabase = $_SESSION['minBuildNumberInDatabase'];

                        /* Read the test results from the Project directory (structure is e.g. QtBase_stable_Integration/build_03681/macx-ios-clang_OSX_10.8 */
                        if ($timescaleType == "All") {                                                  // If timescale not filtered read only the latest/selected build
                            $buildCheckType = CHECKBUILDONE;
                            $buildNumberToCheck = $buildNumber;
                        } else {                                                                        // If timescale filtered read all the available builds since the date
                            $buildCheckType = CHECKBUILDSINCE;
                            $buildNumberToCheck = setMinBuildNumberToCheck($latestBuildNumber, $minBuildNumberInDatabase, $timescaleType);
                        }
                        $minBuildNumberInDirectory = readProjectTestResultDirectory(
                            CITESTRESULTSDIRECTORY, $checkedProject, $buildCheckType, $buildNumberToCheck, $conf, TRUE, $arrayAutotestName,
                            $arrayFailingAutotestBuildConfigurations, $arrayFailingAutotestAllBuilds,
                            $arrayTestcaseNames, $arrayTestcaseFailed, $arrayTestcaseAll, $arrayTestcaseConfs,
                            $failingTestcaseCount, $testcaseCount, $arrayInvalidTestResultFiles);       // Returns the first available build number if timescale filtered, otherwise the selected build

                        /* If test result files found */
                        if ($minBuildNumberInDirectory < MAXCIBUILDNUMBER) {

                            /* Calculate the failure percentage */
                            $maxCount = 0;
                            for ($k=0; $k<$testcaseCount; $k++) {
                                $arrayTestcaseFailedPercentage[$k] = calculatePercentage($arrayTestcaseFailed[$k], $arrayTestcaseAll[$k]);
                                if ($arrayTestcaseFailed[$k] > $maxCount)
                                    $maxCount = $arrayTestcaseFailed[$k];                               // Save maxCount for sorting
                                if ($arrayTestcaseAll[$k] > $maxCount)
                                    $maxCount = $arrayTestcaseAll[$k];                                  // Save maxCount for sorting
                            }

                            /* Read the timestamp of the first build with detailed test result data */
                            if ($project <> "All") {
                                $projectFilter = "project = \"$project\"";                              // Project is filtered here
                                $buildFilter = "build_number = $minBuildNumberInDirectory";
                                $from = "ci";
                                $sql = "SELECT min(timestamp)
                                        FROM $from
                                        WHERE $projectFilter AND $buildFilter";
                                $dbColumnCiTimestamp = 0;
                                if ($useMysqli) {
                                    $result2 = mysqli_query($conn, $sql);
                                    $numberOfRows2 = mysqli_num_rows($result2);
                                } else {
                                    $selectdb = "USE $db";
                                    $result2 = mysql_query($selectdb) or die (mysql_error());
                                    $result2 = mysql_query($sql) or die (mysql_error());
                                    $numberOfRows2 = mysql_num_rows($result2);
                                }
                                if ($useMysqli)
                                    $resultRow2 = mysqli_fetch_row($result2);
                                else
                                    $resultRow2 = mysql_fetch_row($result2);
                                $minBuildNumberInDirectoryTimestamp = $resultRow2[$dbColumnCiTimestamp];
                                if ($useMysqli)
                                    mysqli_free_result($result2);                                       // Free result set
                            }

                            /* Print the test report info */
                            $buildCount = $latestBuildNumber - $minBuildNumberInDirectory + 1;
                            if ($timescaleType == "All")
                                $testResultBuilds = ' from build ';
                            else
                                $testResultBuilds = ' from ' . $buildCount . ' builds since ';
                            $testResultBuilds = $testResultBuilds . $minBuildNumberInDirectory . ' ('
                                . substr($minBuildNumberInDirectoryTimestamp, 0, strpos($minBuildNumberInDirectoryTimestamp, " ")) . ')';
                            $testResultBuildsSeeMore = setSeeMoreNote($timescaleType, $timescaleValue);
                            $failingTestcasePercentage = calculatePercentage($failingTestcaseCount, $testcaseCount);
                            echo $testResultBuilds . $testResultBuildsSeeMore . '</div>';               // ... the title closed here

                            /* Set the default sorting to Failed % when displayed */
                            $sortBy = AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE;

                            /* Print the test case table titles */
                            echo '<table class="fontSmall">';
                            echo '<tr>';
                            echo '<th></th>';
                            if ($timescaleType == "All" AND CITESTRESULTBUILDCOUNT == 1) {
                                $buildData = '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered tableCellBuildSelected">';
                                if ($build == 0)
                                    $buildData = $buildData . 'LATEST BUILD</td>';
                                else
                                    $buildData = $buildData . 'BUILD ' . $buildNumber . '</td>';
                            }
                            if ($timescaleType == "All" AND CITESTRESULTBUILDCOUNT > 1)
                                $buildData = '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered timescaleAll">
                                    <b>ALL BUILDS (SINCE ' . $_SESSION['minBuildDate'] . ')</b></td>';
                            if ($timescaleType == "Since") {
                                if ($minBuildNumberInDirectory == $firstTimescaleBuild)         // Data available since the same build as filtered by date
                                    $buildData = '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered timescaleSince">';
                                else                                                            // Data available only for certain builds after those filtered by date
                                    $buildData = '<td colspan="3" class="tableBottomBorder tableSideBorder tableCellCentered timescaleSinceBuild">';
                                $buildData = $buildData . 'ALL BUILDS</td>';
                            }
                            echo $buildData;
                            if ($conf == "All") {                                               // Show list of configurations only when not filtered
                                echo '<th></th>';
                                echo $buildData;
                            }
                            echo '</tr>';

                            echo '<tr>';
                            echo '<th></th>';
                            $xmlBuildInfo = '<th colspan="3" class="tableBottomBorder tableSideBorder">Detailed Test Results';
                            if ($timescaleType == "Since" OR CITESTRESULTBUILDCOUNT > 1)
                                $xmlBuildInfo = $xmlBuildInfo . ' since Build ' . $minBuildNumberInDirectory;
                            $xmlBuildInfo = $xmlBuildInfo . '</th>';
                            echo $xmlBuildInfo;
                            if ($conf == "All") {                                               // Show list of configurations only when not filtered
                                echo '<th></th>';
                                echo $xmlBuildInfo;
                            }
                            echo '</tr>';

                            echo '<tr>';
                            echo '<th class="tableBottomBorder tableCellAlignLeft">Failed test cases</th>';
                            echo '<td class="tableBottomBorder tableLeftBorder tableCellCentered">Failed</td>';
                            echo '<td class="tableBottomBorder tableCellCentered">Total</td>';
                            echo '<td class="sortField tableBottomBorder tableRightBorder tableCellCentered">';
                            if ($sortBy == AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE)
                                echo 'Failed % &diams;';                                        // Identify selected sorting
                            else
                                echo '<a href="javascript:void(0);" onclick="filterAutotest(\'' . $autotest . '\',' . AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE . ')">
                                      Failed % <img src="images/sort-descending.png" alt="Sort" title="sort descending"></a>';
                            echo '</td>';
                            if ($conf == "All") {                                               // Show list of configurations only when not filtered
                                echo '<th class="tableBottomBorder tableCellAlignLeft">';
                                echo 'Configuration';
                                echo '<td class="tableBottomBorder tableLeftBorder tableCellCentered">Failed</td>';
                                echo '<td class="tableBottomBorder tableCellCentered">Total</td>';
                                echo '<td class="sortField tableBottomBorder tableRightBorder tableCellCentered">Failed %</td>';
                                echo '</th>';
                            }
                            echo '</tr>';

                            /* Print list of test cases */
                            $k = 0;
                            if ($maxCount < 100)
                                $maxCount = 100;                                                // Loop at least the percentage scale
                            for ($countOrder=$maxCount; $countOrder>=0; $countOrder--) {        // Sort the list by looping from the highest count
                                for ($i=0; $i<$testcaseCount; $i++) {                           // Loop the test cases
                                    if ($sortBy == AUTOTESTSORTBYAUTOTESTFAILEDPERCENTAGE)
                                        $sortFieldValue = $arrayTestcaseFailedPercentage[$i];
                                    else
                                        $sortFieldValue = $arrayTestcaseFailed[$i];
                                    if ($sortFieldValue == $countOrder) {                       // Print the ones that are next in the sorting order
                                        if ($arrayTestcaseFailed[$i]
                                            + $arrayTestcaseFailedPercentage[$i] > 0) {         // Skip if not any failures
                                            if ($k % 2 == 0)
                                                echo '<tr>';
                                            else
                                                echo '<tr class="tableBackgroundColored">';

                                            /* Test case name */
                                            echo '<td>' . $arrayTestcaseNames[$i] . '</td>';

                                            /* Test case: Builds where failed */
                                            echo '<td class="tableLeftBorder tableCellCentered tableWidth2">';
                                            if ($arrayTestcaseFailed[$i] > 0)
                                                echo $arrayTestcaseFailed[$i];
                                            else
                                                echo '-';
                                            echo '</td>';

                                            /* Test case: Builds where run (all) */
                                            echo '<td class="tableCellCentered tableWidth2">';
                                            if ($arrayTestcaseAll[$i] > 0)
                                                echo $arrayTestcaseAll[$i];
                                            else
                                                echo '-';
                                            echo '</td>';

                                            /* Test case: Failed % */
                                            if ($arrayTestcaseFailedPercentage[$i] >= AUTOTESTFAILUREWARNINGLEVEL)
                                                echo '<td class="tableRightBorder tableCellCentered fontColorRed tableWidth1">';
                                            else
                                                echo '<td class="tableRightBorder tableCellCentered tableWidth2">';
                                            if ($arrayTestcaseFailedPercentage[$i] > 0)
                                                echo $arrayTestcaseFailedPercentage[$i] . '%';
                                            else
                                                echo '-';
                                            echo '</td>';

                                            /* Configurations */
                                            if ($conf == "All") {                                       // Show list of configurations only when not filtered

                                                /* Configuration: Name */
                                                echo '<td class="tableTopBorder tableLeftBorder">';
                                                echo '<table>';
                                                $m = 0;
                                                foreach ($arrayTestcaseConfs[$i] as $confKey => $testcaseConf)
                                                    if ($testcaseConf[FAILINGTESTCASECONFFAILED] > 0) {
                                                        if ($m == 0)
                                                            echo '<tr>';
                                                        else
                                                            echo '<tr class="tableTopBorder">';
                                                        echo '<td>' . $testcaseConf[FAILINGTESTCASECONFNAME] . '</td>';
                                                        echo '</tr>';
                                                        $m++;
                                                    }
                                                echo '</table>';
                                                echo '</td>';

                                                /* Configuration: Failed testcases */
                                                echo '<td class="tableTopBorder tableLeftBorder">';
                                                echo '<table class="tableWidth2">';
                                                $m = 0;
                                                foreach ($arrayTestcaseConfs[$i] as $confKey => $testcaseConf)
                                                    if ($testcaseConf[FAILINGTESTCASECONFFAILED] > 0) {
                                                        if ($m == 0)
                                                            echo '<tr>';
                                                        else
                                                            echo '<tr class="tableTopBorder">';
                                                        echo '<td class="tableCellCentered">' . $testcaseConf[FAILINGTESTCASECONFFAILED] . '</td>';
                                                        echo '</tr>';
                                                        $m++;
                                                    }
                                                echo '</table>';
                                                echo '</td>';

                                                /* Configuration: All testcases */
                                                echo '<td class="tableTopBorder">';
                                                echo '<table class="tableWidth2">';
                                                $m = 0;
                                                foreach ($arrayTestcaseConfs[$i] as $confKey => $testcaseConf)
                                                    if ($testcaseConf[FAILINGTESTCASECONFFAILED] > 0) {
                                                        if ($m == 0)
                                                            echo '<tr>';
                                                        else
                                                            echo '<tr class="tableTopBorder">';
                                                        echo '<td class="tableCellCentered">' . $testcaseConf[FAILINGTESTCASECONFALL] . '</td>';
                                                        echo '</tr>';
                                                        $m++;
                                                    }
                                                echo '</table>';
                                                echo '</td>';

                                                /* Configuration: Failed % */
                                                echo '<td class="tableTopBorder tableRightBorder">';
                                                echo '<table class="tableWidth2">';
                                                $m = 0;
                                                foreach ($arrayTestcaseConfs[$i] as $confKey => $testcaseConf)
                                                    if ($testcaseConf[FAILINGTESTCASECONFFAILED] > 0) {
                                                        if ($m == 0)
                                                            echo '<tr>';
                                                        else
                                                            echo '<tr class="tableTopBorder">';
                                                        $testcaseConfFailedPercentage = calculatePercentage(
                                                            $testcaseConf[FAILINGTESTCASECONFFAILED],
                                                            $testcaseConf[FAILINGTESTCASECONFALL]);
                                                        if ($testcaseConfFailedPercentage >= AUTOTESTFAILUREWARNINGLEVEL)
                                                            echo '<td class="tableCellCentered fontColorRed">';
                                                        else
                                                            echo '<td class="tableCellCentered">';
                                                        echo $testcaseConfFailedPercentage . '%';
                                                        echo '</td>';
                                                        echo '</tr>';
                                                        $m++;
                                                    }
                                                echo '</table>';
                                                echo '</td>';
                                            }

                                            echo '</tr>';
                                            $k++;
                                        }
                                    } // Endif sorting order
                                } // Endfor Autotests
                            } // Endfor sorting
                            $printedTestcases = $k;

                            /* Print Totals summary row */
                            $arrayTestcaseFailedSum = 0;
                            $arrayTestcaseAllSum = 0;
                            $arrayTestcaseFailedPercentageSum = 0;
                            for ($i=0; $i<$testcaseCount; $i++) {                               // Loop the test cases
                                if ($arrayTestcaseFailed[$i] > 0) {
                                    $arrayTestcaseFailedSum = $arrayTestcaseFailedSum + $arrayTestcaseFailed[$i];
                                    $arrayTestcaseAllSum = $arrayTestcaseAllSum + $arrayTestcaseAll[$i];
                                }
                            }
                            $arrayTestcaseFailedPercentageSum = 100 * round($arrayTestcaseFailedSum / $arrayTestcaseAllSum, 2);
                            echo '<tr>';
                            echo '<td class="tableTopBorder">total (' . $failingTestcaseCount . ' failed / ' . $testcaseCount
                                . ' total = ' . $failingTestcasePercentage . '%)</td>';
                            echo '<td class="tableCellCentered tableLeftBorder tableTopBorder">' . $arrayTestcaseFailedSum . '</td>';
                            echo '<td class="tableCellCentered tableTopBorder">' . $arrayTestcaseAllSum . '</td>';
                            echo '<td class="tableRightBorder tableTopBorder tableCellCentered">' . $arrayTestcaseFailedPercentageSum . '%</td>';
                            if ($conf == "All")                                                 // Show list of configurations only when not filtered
                                echo '<td colspan="4" class="tableRightBorder tableTopBorder tableCellCentered"></td>';
                            echo '</tr>';
                            echo '</table>';

                            /* Print the list of files that couldn't be opened */
                            if (count($arrayInvalidTestResultFiles) > 0) {
                                echo '<br>';
                                echo '<table class="fontSmall fontColorGrey">';
                                echo '<tr>';
                                echo '<th class="tableCellAlignLeft">Total ' . count($arrayInvalidTestResultFiles)
                                    . ' test result files could not be opened (the xml format may be invalid)</th>';
                                echo '</tr>';
                                foreach ($arrayInvalidTestResultFiles as $invalidFile) {
                                    echo '<tr>';
                                    echo '<td>' . $invalidFile . '</td>';
                                    echo '</tr>';
                                }
                                echo '</table>';
                            }

                        } else {
                            echo '</div><br/><br/>(not any test result files available)<br/><br/>';
                        }

                    } else {
                        echo '</div><br/><br/><i>Please select one of the Projects above to see the test case list...</i><br/><br/>';
                    }
                    $timeAutotestCaseEnd = microtime(true);
                }

                break;                                                  // Match found, skip the rest

            } // endif Selected Autotest
        } // endif foreach
    } else {
        echo '<br/>Filter values not ready or they are expired, please <a href="javascript:void(0);" onclick="reloadFilters()">reload</a> ...';
    }

    /* Elapsed time */
    if ($showElapsedTime) {
        $timeEnd = microtime(true);
        $timeDbConnect = round($timeConnect - $timeStart, 2);
        $timeHistory = round($timeAutotestHistoryEnd - $timeAutotestHistoryStart, 2);
        if (isset($timeAutotestCaseEnd))
            $timeCases = round($timeAutotestCaseEnd - $timeAutotestHistoryEnd, 2);
        $time = round($timeEnd - $timeStart, 2);
        echo "<div class=\"elapdedTime\">";
        echo "<ul><li>";
        echo "Total time: $time s (database connect time: $timeDbConnect s, history list time: $timeHistory s";
        if (isset($timeAutotestCaseEnd))
            echo ", test case list time: $timeCases s";
        echo ")</li></ul>";
        echo "</div>";
    }

}

/* Close connection to the server */
require(__DIR__.'/../connectionclose.php');

?>