~ubuntu-branches/ubuntu/trusty/phpmyadmin/trusty

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
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Configuration handling.
 *
 * @package PhpMyAdmin
 */

if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * Load vendor configuration.
 */
require_once './libraries/vendor_config.php';

/**
 * Configuration class
 *
 * @package PhpMyAdmin
 */
class PMA_Config
{
    /**
     * @var string  default config source
     */
    var $default_source = './libraries/config.default.php';

    /**
     * @var array   default configuration settings
     */
    var $default = array();

    /**
     * @var array   configuration settings
     */
    var $settings = array();

    /**
     * @var string  config source
     */
    var $source = '';

    /**
     * @var int     source modification time
     */
    var $source_mtime = 0;
    var $default_source_mtime = 0;
    var $set_mtime = 0;

    /**
     * @var boolean
     */
    var $error_config_file = false;

    /**
     * @var boolean
     */
    var $error_config_default_file = false;

    /**
     * @var boolean
     */
    var $error_pma_uri = false;

    /**
     * @var array
     */
    var $default_server = array();

    /**
     * @var boolean whether init is done or not
     * set this to false to force some initial checks
     * like checking for required functions
     */
    var $done = false;

    /**
     * constructor
     *
     * @param string $source source to read config from
     */
    function __construct($source = null)
    {
        $this->settings = array();

        // functions need to refresh in case of config file changed goes in
        // PMA_Config::load()
        $this->load($source);

        // other settings, independent from config file, comes in
        $this->checkSystem();

        $this->checkIsHttps();
    }

    /**
     * sets system and application settings
     *
     * @return void
     */
    function checkSystem()
    {
        $this->set('PMA_VERSION', '4.0.8');
        /**
         * @deprecated
         */
        $this->set('PMA_THEME_VERSION', 2);
        /**
         * @deprecated
         */
        $this->set('PMA_THEME_GENERATION', 2);

        $this->checkPhpVersion();
        $this->checkWebServerOs();
        $this->checkWebServer();
        $this->checkGd2();
        $this->checkClient();
        $this->checkUpload();
        $this->checkUploadSize();
        $this->checkOutputCompression();
    }

    /**
     * whether to use gzip output compression or not
     *
     * @return void
     */
    function checkOutputCompression()
    {
        // If zlib output compression is set in the php configuration file, no
        // output buffering should be run
        if (@ini_get('zlib.output_compression')) {
            $this->set('OBGzip', false);
        }

        // disable output-buffering (if set to 'auto') for IE6, else enable it.
        if (strtolower($this->get('OBGzip')) == 'auto') {
            if ($this->get('PMA_USR_BROWSER_AGENT') == 'IE'
                && $this->get('PMA_USR_BROWSER_VER') >= 6
                && $this->get('PMA_USR_BROWSER_VER') < 7
            ) {
                $this->set('OBGzip', false);
            } else {
                $this->set('OBGzip', true);
            }
        }
    }

    /**
     * Determines platform (OS), browser and version of the user
     * Based on a phpBuilder article:
     *
     * @see http://www.phpbuilder.net/columns/tim20000821.php
     *
     * @return void
     */
    function checkClient()
    {
        if (PMA_getenv('HTTP_USER_AGENT')) {
            $HTTP_USER_AGENT = PMA_getenv('HTTP_USER_AGENT');
        } else {
            $HTTP_USER_AGENT = '';
        }

        // 1. Platform
        if (strstr($HTTP_USER_AGENT, 'Win')) {
            $this->set('PMA_USR_OS', 'Win');
        } elseif (strstr($HTTP_USER_AGENT, 'Mac')) {
            $this->set('PMA_USR_OS', 'Mac');
        } elseif (strstr($HTTP_USER_AGENT, 'Linux')) {
            $this->set('PMA_USR_OS', 'Linux');
        } elseif (strstr($HTTP_USER_AGENT, 'Unix')) {
            $this->set('PMA_USR_OS', 'Unix');
        } elseif (strstr($HTTP_USER_AGENT, 'OS/2')) {
            $this->set('PMA_USR_OS', 'OS/2');
        } else {
            $this->set('PMA_USR_OS', 'Other');
        }

        // 2. browser and version
        // (must check everything else before Mozilla)

        if (preg_match(
            '@Opera(/| )([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version
        )) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
            $this->set('PMA_USR_BROWSER_AGENT', 'OPERA');
        } elseif (preg_match(
            '@MSIE ([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version
        )) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
            $this->set('PMA_USR_BROWSER_AGENT', 'IE');
        } elseif (preg_match(
            '@OmniWeb/([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version
        )) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
            $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB');
            // Konqueror 2.2.2 says Konqueror/2.2.2
            // Konqueror 3.0.3 says Konqueror/3
        } elseif (preg_match(
            '@(Konqueror/)(.*)(;)@',
            $HTTP_USER_AGENT,
            $log_version
        )) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
            $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR');
            // must check Chrome before Safari
        } elseif (preg_match(
            '@Mozilla/([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version)
            && preg_match('@Chrome/([0-9]*)@', $HTTP_USER_AGENT, $log_version2)
        ) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[1] . '.' . $log_version2[1]);
            $this->set('PMA_USR_BROWSER_AGENT', 'CHROME');
            // newer Safari
        } elseif (preg_match(
            '@Mozilla/([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version)
            && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version2)
        ) {
            $this->set(
                'PMA_USR_BROWSER_VER', $log_version2[1]
            );
            $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
            // older Safari
        } elseif (preg_match(
            '@Mozilla/([0-9].[0-9]{1,2})@',
            $HTTP_USER_AGENT,
            $log_version)
            && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version2)
        ) {
            $this->set(
                'PMA_USR_BROWSER_VER', $log_version[1] . '.' . $log_version2[1]
            );
            $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
        } elseif (preg_match('@rv:1.9(.*)Gecko@', $HTTP_USER_AGENT)) {
            $this->set('PMA_USR_BROWSER_VER', '1.9');
            $this->set('PMA_USR_BROWSER_AGENT', 'GECKO');
        } elseif (preg_match('@Mozilla/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version)) {
            $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
            $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA');
        } else {
            $this->set('PMA_USR_BROWSER_VER', 0);
            $this->set('PMA_USR_BROWSER_AGENT', 'OTHER');
        }
    }

    /**
     * Whether GD2 is present
     *
     * @return void
     */
    function checkGd2()
    {
        if ($this->get('GD2Available') == 'yes') {
            $this->set('PMA_IS_GD2', 1);
        } elseif ($this->get('GD2Available') == 'no') {
            $this->set('PMA_IS_GD2', 0);
        } else {
            if (!@function_exists('imagecreatetruecolor')) {
                $this->set('PMA_IS_GD2', 0);
            } else {
                if (@function_exists('gd_info')) {
                    $gd_nfo = gd_info();
                    if (strstr($gd_nfo["GD Version"], '2.')) {
                        $this->set('PMA_IS_GD2', 1);
                    } else {
                        $this->set('PMA_IS_GD2', 0);
                    }
                } else {
                    $this->set('PMA_IS_GD2', 0);
                }
            }
        }
    }

    /**
     * Whether the Web server php is running on is IIS
     *
     * @return void
     */
    function checkWebServer()
    {
        // some versions return Microsoft-IIS, some Microsoft/IIS
        // we could use a preg_match() but it's slower
        if (PMA_getenv('SERVER_SOFTWARE')
            && stristr(PMA_getenv('SERVER_SOFTWARE'), 'Microsoft')
            && stristr(PMA_getenv('SERVER_SOFTWARE'), 'IIS')
        ) {
            $this->set('PMA_IS_IIS', 1);
        } else {
            $this->set('PMA_IS_IIS', 0);
        }
    }

    /**
     * Whether the os php is running on is windows or not
     *
     * @return void
     */
    function checkWebServerOs()
    {
        // Default to Unix or Equiv
        $this->set('PMA_IS_WINDOWS', 0);
        // If PHP_OS is defined then continue
        if (defined('PHP_OS')) {
            if (stristr(PHP_OS, 'win')) {
                // Is it some version of Windows
                $this->set('PMA_IS_WINDOWS', 1);
            } elseif (stristr(PHP_OS, 'OS/2')) {
                // Is it OS/2 (No file permissions like Windows)
                $this->set('PMA_IS_WINDOWS', 1);
            }
        }
    }

    /**
     * detects PHP version
     *
     * @return void
     */
    function checkPhpVersion()
    {
        $match = array();
        if (! preg_match(
            '@([0-9]{1,2}).([0-9]{1,2}).([0-9]{1,2})@',
            phpversion(),
            $match
        )) {
            preg_match(
                '@([0-9]{1,2}).([0-9]{1,2})@',
                phpversion(),
                $match
            );
        }
        if (isset($match) && ! empty($match[1])) {
            if (! isset($match[2])) {
                $match[2] = 0;
            }
            if (! isset($match[3])) {
                $match[3] = 0;
            }
            $this->set(
                'PMA_PHP_INT_VERSION',
                (int) sprintf('%d%02d%02d', $match[1], $match[2], $match[3])
            );
        } else {
            $this->set('PMA_PHP_INT_VERSION', 0);
        }
        $this->set('PMA_PHP_STR_VERSION', phpversion());
    }

    /**
     * detects if Git revision
     *
     * @return boolean
     */
    function isGitRevision()
    {
        // caching
        if (isset($_SESSION['is_git_revision'])) {
            if ($_SESSION['is_git_revision']) {
                $this->set('PMA_VERSION_GIT', 1);
            }
            return $_SESSION['is_git_revision'];
        }
        // find out if there is a .git folder
        $git_folder = '.git';
        if (! @file_exists($git_folder)
            || ! @file_exists($git_folder . '/config')
        ) {
            $_SESSION['is_git_revision'] = false;
            return false;
        }
        $_SESSION['is_git_revision'] = true;
        return true;
    }

    /**
     * detects Git revision, if running inside repo
     *
     * @return void
     */
    function checkGitRevision()
    {
        // find out if there is a .git folder
        $git_folder = '.git';
        if (! $this->isGitRevision()) {
            return;
        }

        if (! $ref_head = @file_get_contents($git_folder . '/HEAD')) {
            return;
        }
        $branch = false;
        // are we on any branch?
        if (strstr($ref_head, '/')) {
            $ref_head = substr(trim($ref_head), 5);
            if (substr($ref_head, 0, 11) === 'refs/heads/') {
                $branch = substr($ref_head, 11);
            } else {
                $branch = basename($ref_head);
            }

            $ref_file = $git_folder . '/' . $ref_head;
            if (@file_exists($ref_file)) {
                if (! $hash = @file_get_contents($ref_file)) {
                    return;
                }
                $hash = trim($hash);
            } else {
                // deal with packed refs
                if (! $packed_refs = @file_get_contents($git_folder . '/packed-refs')) {
                    return;
                }
                // split file to lines
                $ref_lines = explode("\n", $packed_refs);
                foreach ($ref_lines as $line) {
                    // skip comments
                    if ($line[0] == '#') {
                        continue;
                    }
                    // parse line
                    $parts = explode(' ', $line);
                    // care only about named refs
                    if (count($parts) != 2) {
                        continue;
                    }
                    // have found our ref?
                    if ($parts[1] == $ref_head) {
                        $hash = $parts[0];
                        break;
                    }
                }
                if (! isset($hash)) {
                    // Could not find ref
                    return;
                }
            }
        } else {
            $hash = trim($ref_head);
        }

        $commit = false;
        if ( !isset($_SESSION['PMA_VERSION_COMMITDATA_' . $hash])) {
            $git_file_name = $git_folder . '/objects/' . substr($hash, 0, 2)
                    . '/' . substr($hash, 2);
            if (file_exists($git_file_name) ) {
                if (! $commit = @file_get_contents($git_file_name)) {
                    return;
                }
                $commit = explode("\0", gzuncompress($commit), 2);
                $commit = explode("\n", $commit[1]);
                $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
            } else {
                $pack_names = array();
                // work with packed data
                if ($packs = @file_get_contents($git_folder . '/objects/info/packs')) {
                    // File exists. Read it, parse the file to get the names of the
                    // packs. (to look for them in .git/object/pack directory later)
                    foreach (explode("\n", $packs) as $line) {
                        // skip blank lines
                        if (strlen(trim($line)) == 0) {
                            continue;
                        }
                        // skip non pack lines
                        if ($line[0] != 'P') {
                            continue;
                        }
                        // parse names
                        $pack_names[] = substr($line, 2);
                    }
                } else {
                    // '.git/objects/info/packs' file can be missing
                    // (atlease in mysGit)
                    // File missing. May be we can look in the .git/object/pack
                    // directory for all the .pack files and use that list of
                    // files instead
                    $it = new DirectoryIterator($git_folder . '/objects/pack');
                    foreach ($it as $file_info) {
                        $file_name = $file_info->getFilename();
                        // if this is a .pack file
                        if ($file_info->isFile()
                            && substr($file_name, -5) == '.pack'
                        ) {
                            $pack_names[] = $file_name;
                        }
                    }
                }
                $hash = strtolower($hash);
                foreach ($pack_names as $pack_name) {
                    $index_name = str_replace('.pack', '.idx', $pack_name);

                    // load index
                    if (! $index_data = @file_get_contents($git_folder . '/objects/pack/' . $index_name)) {
                        continue;
                    }
                    // check format
                    if (substr($index_data, 0, 4) != "\377tOc") {
                        continue;
                    }
                    // check version
                    $version = unpack('N', substr($index_data, 4, 4));
                    if ($version[1] != 2) {
                        continue;
                    }
                    // parse fanout table
                    $fanout = unpack("N*", substr($index_data, 8, 256 * 4));

                    // find where we should search
                    $firstbyte = intval(substr($hash, 0, 2), 16);
                    // array is indexed from 1 and we need to get
                    // previous entry for start
                    if ($firstbyte == 0) {
                        $start = 0;
                    } else {
                        $start = $fanout[$firstbyte];
                    }
                    $end = $fanout[$firstbyte + 1];

                    // stupid linear search for our sha
                    $position = $start;
                    $found = false;
                    $offset = 8 + (256 * 4);
                    for ($position = $start; $position < $end; $position++) {
                        $sha = strtolower(
                            bin2hex(
                                substr(
                                    $index_data, $offset + ($position * 20), 20
                                )
                            )
                        );
                        if ($sha == $hash) {
                            $found = true;
                            break;
                        }
                    }
                    if (! $found) {
                        continue;
                    }
                    // read pack offset
                    $offset = 8 + (256 * 4) + (24 * $fanout[256]);
                    $pack_offset = unpack(
                        'N', substr($index_data, $offset + ($position * 4), 4)
                    );
                    $pack_offset = $pack_offset[1];

                    // open pack file
                    $pack_file = fopen(
                        $git_folder . '/objects/pack/' . $pack_name, 'rb'
                    );
                    if ($pack_file === false) {
                        continue;
                    }
                    // seek to start
                    fseek($pack_file, $pack_offset);

                    // parse header
                    $header = ord(fread($pack_file, 1));
                    $type = ($header >> 4) & 7;
                    $hasnext = ($header & 128) >> 7;
                    $size = $header & 0xf;
                    $offset = 4;

                    while ($hasnext) {
                        $byte = ord(fread($pack_file, 1));
                        $size |= ($byte & 0x7f) << $offset;
                        $hasnext = ($byte & 128) >> 7;
                        $offset += 7;
                    }

                    // we care only about commit objects
                    if ($type != 1) {
                        continue;
                    }

                    // read data
                    $commit = fread($pack_file, $size);
                    $commit = gzuncompress($commit);
                    $commit = explode("\n", $commit);
                    $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
                    fclose($pack_file);
                }
            }
        } else {
            $commit = $_SESSION['PMA_VERSION_COMMITDATA_' . $hash];
        }

        // check if commit exists in Github
        $is_remote_commit = false;
        if ($commit !== false
            && isset($_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash])
        ) {
            $is_remote_commit = $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash];
        } else {
            $link = 'https://api.github.com/repos/phpmyadmin/phpmyadmin/git/commits/'
                . $hash;
            $is_found = $this->checkHTTP($link, !$commit);
            switch($is_found) {
            case false:
                $is_remote_commit = false;
                $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = false;
                break;
            case null:
                // no remote link for now, but don't cache this as Github is down
                $is_remote_commit = false;
                break;
            default:
                $is_remote_commit = true;
                $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = true;
                if ($commit === false) {
                    // if no local commit data, try loading from Github
                    $commit_json = json_decode($is_found);
                }
                break;
            }
        }

        $is_remote_branch = false;
        if ($is_remote_commit && $branch !== false) {
            // check if branch exists in Github
            if (isset($_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash])) {
                $is_remote_branch = $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash];
            } else {
                $link = 'https://api.github.com/repos/phpmyadmin/phpmyadmin'
                    . '/git/trees/' . $branch;
                $is_found = $this->checkHTTP($link);
                switch($is_found) {
                case true:
                    $is_remote_branch = true;
                    $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = true;
                    break;
                case false:
                    $is_remote_branch = false;
                    $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = false;
                    break;
                case null:
                    // no remote link for now, but don't cache this as Github is down
                    $is_remote_branch = false;
                    break;
                }
            }
        }

        if ($commit !== false) {
            $author = array('name' => '', 'email' => '', 'date' => '');
            $committer = array('name' => '', 'email' => '', 'date' => '');

            do {
                $dataline = array_shift($commit);
                $datalinearr = explode(' ', $dataline, 2);
                $linetype = $datalinearr[0];
                if (in_array($linetype, array('author', 'committer'))) {
                    $user = $datalinearr[1];
                    preg_match('/([^<]+)<([^>]+)> ([0-9]+)( [^ ]+)?/', $user, $user);
                    $user2 = array(
                        'name' => trim($user[1]),
                        'email' => trim($user[2]),
                        'date' => date('Y-m-d H:i:s', $user[3]));
                    if (isset($user[4])) {
                        $user2['date'] .= $user[4];
                    }
                    $$linetype = $user2;
                }
            } while ($dataline != '');
            $message = trim(implode(' ', $commit));

        } elseif (isset($commit_json)) {
            $author = array(
                'name' => $commit_json->author->name,
                'email' => $commit_json->author->email,
                'date' => $commit_json->author->date);
            $committer = array(
                'name' => $commit_json->committer->name,
                'email' => $commit_json->committer->email,
                'date' => $commit_json->committer->date);
            $message = trim($commit_json->message);
        } else {
            return;
        }

        $this->set('PMA_VERSION_GIT', 1);
        $this->set('PMA_VERSION_GIT_COMMITHASH', $hash);
        $this->set('PMA_VERSION_GIT_BRANCH', $branch);
        $this->set('PMA_VERSION_GIT_MESSAGE', $message);
        $this->set('PMA_VERSION_GIT_AUTHOR', $author);
        $this->set('PMA_VERSION_GIT_COMMITTER', $committer);
        $this->set('PMA_VERSION_GIT_ISREMOTECOMMIT', $is_remote_commit);
        $this->set('PMA_VERSION_GIT_ISREMOTEBRANCH', $is_remote_branch);
    }

    /**
     * Checks if given URL is 200 or 404, optionally returns data
     *
     * @param mixed   $link     curl link
     * @param boolean $get_body whether to retrieve body of document
     *
     * @return test result or data
     */
    function checkHTTP($link, $get_body = false)
    {
        if (! function_exists('curl_init')) {
            return null;
        }
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $data = @curl_exec($ch);
        if ($data === false) {
            return null;
        }
        $ok = 'HTTP/1.1 200 OK';
        $notfound = 'HTTP/1.1 404 Not Found';
        if (substr($data, 0, strlen($ok)) === $ok) {
            return $get_body ? substr($data, strpos($data, "\r\n\r\n") + 4) : true;
        } elseif (substr($data, 0, strlen($notfound)) === $notfound) {
            return false;
        }
        return null;
    }

    /**
     * loads default values from default source
     *
     * @return boolean     success
     */
    function loadDefaults()
    {
        $cfg = array();
        if (! file_exists($this->default_source)) {
            $this->error_config_default_file = true;
            return false;
        }
        include $this->default_source;

        $this->default_source_mtime = filemtime($this->default_source);

        $this->default_server = $cfg['Servers'][1];
        unset($cfg['Servers']);

        $this->default = $cfg;
        $this->settings = PMA_arrayMergeRecursive($this->settings, $cfg);

        $this->error_config_default_file = false;

        return true;
    }

    /**
     * loads configuration from $source, usally the config file
     * should be called on object creation
     *
     * @param string $source config file
     *
     * @return bool
     */
    function load($source = null)
    {
        $this->loadDefaults();

        if (null !== $source) {
            $this->setSource($source);
        }

        if (! $this->checkConfigSource()) {
            return false;
        }

        $cfg = array();

        /**
         * Parses the configuration file, the eval is used here to avoid
         * problems with trailing whitespace, what is often a problem.
         */
        $old_error_reporting = error_reporting(0);
        $eval_result = eval('?' . '>' . trim(file_get_contents($this->getSource())));
        error_reporting($old_error_reporting);

        if ($eval_result === false) {
            $this->error_config_file = true;
        } else {
            $this->error_config_file = false;
            $this->source_mtime = filemtime($this->getSource());
        }

        /**
         * Backward compatibility code
         */
        if (!empty($cfg['DefaultTabTable'])) {
            $cfg['DefaultTabTable'] = str_replace(
                '_properties',
                '',
                str_replace(
                    'tbl_properties.php',
                    'tbl_sql.php',
                    $cfg['DefaultTabTable']
                )
            );
        }
        if (!empty($cfg['DefaultTabDatabase'])) {
            $cfg['DefaultTabDatabase'] = str_replace(
                '_details',
                '',
                str_replace(
                    'db_details.php',
                    'db_sql.php',
                    $cfg['DefaultTabDatabase']
                )
            );
        }

        $this->settings = PMA_arrayMergeRecursive($this->settings, $cfg);
        $this->checkPmaAbsoluteUri();
        $this->checkFontsize();

        // Handling of the collation must be done after merging of $cfg
        // (from config.inc.php) so that $cfg['DefaultConnectionCollation']
        // can have an effect. Note that the presence of collation
        // information in a cookie has priority over what is defined
        // in the default or user's config files.
        /**
         * @todo check validity of $_COOKIE['pma_collation_connection']
         */
        if (! empty($_COOKIE['pma_collation_connection'])) {
            $this->set(
                'collation_connection',
                strip_tags($_COOKIE['pma_collation_connection'])
            );
        } else {
            $this->set(
                'collation_connection',
                $this->get('DefaultConnectionCollation')
            );
        }
        // Now, a collation information could come from REQUEST
        // (an example of this: the collation selector in index.php)
        // so the following handles the setting of collation_connection
        // and later, in common.inc.php, the cookie will be set
        // according to this.
        $this->checkCollationConnection();

        return true;
    }

    /**
     * Loads user preferences and merges them with current config
     * must be called after control connection has been estabilished
     *
     * @return boolean
     */
    function loadUserPreferences()
    {
        // index.php should load these settings, so that phpmyadmin.css.php
        // will have everything avaiable in session cache
        $server = isset($GLOBALS['server'])
            ? $GLOBALS['server']
            : (!empty($GLOBALS['cfg']['ServerDefault'])
                ? $GLOBALS['cfg']['ServerDefault']
                : 0);
        $cache_key = 'server_' . $server;
        if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) {
            $config_mtime = max($this->default_source_mtime, $this->source_mtime);
            // cache user preferences, use database only when needed
            if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
                || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
            ) {
                // load required libraries
                include_once './libraries/user_preferences.lib.php';
                $prefs = PMA_loadUserprefs();
                $_SESSION['cache'][$cache_key]['userprefs']
                    = PMA_applyUserprefs($prefs['config_data']);
                $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
                $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
                $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
            }
        } elseif ($server == 0
            || ! isset($_SESSION['cache'][$cache_key]['userprefs'])
        ) {
            $this->set('user_preferences', false);
            return;
        }
        $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
        // type is 'db' or 'session'
        $this->set(
            'user_preferences',
            $_SESSION['cache'][$cache_key]['userprefs_type']
        );
        $this->set(
            'user_preferences_mtime',
            $_SESSION['cache'][$cache_key]['userprefs_mtime']
        );

        // backup some settings
        $org_fontsize = '';
        if (isset($this->settings['fontsize'])) {
            $org_fontsize = $this->settings['fontsize'];
        }
        // load config array
        $this->settings = PMA_arrayMergeRecursive($this->settings, $config_data);
        $GLOBALS['cfg'] = PMA_arrayMergeRecursive($GLOBALS['cfg'], $config_data);
        if (defined('PMA_MINIMUM_COMMON')) {
            return;
        }

        // settings below start really working on next page load, but
        // changes are made only in index.php so everything is set when
        // in frames

        // save theme
        $tmanager = $_SESSION['PMA_Theme_Manager'];
        if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) {
            if ((! isset($config_data['ThemeDefault'])
                && $tmanager->theme->getId() != 'original')
                || isset($config_data['ThemeDefault'])
                && $config_data['ThemeDefault'] != $tmanager->theme->getId()
            ) {
                // new theme was set in common.inc.php
                $this->setUserValue(
                    null,
                    'ThemeDefault',
                    $tmanager->theme->getId(),
                    'original'
                );
            }
        } else {
            // no cookie - read default from settings
            if ($this->settings['ThemeDefault'] != $tmanager->theme->getId()
                && $tmanager->checkTheme($this->settings['ThemeDefault'])
            ) {
                $tmanager->setActiveTheme($this->settings['ThemeDefault']);
                $tmanager->setThemeCookie();
            }
        }

        // save font size
        if ((! isset($config_data['fontsize'])
            && $org_fontsize != '82%')
            || isset($config_data['fontsize'])
            && $org_fontsize != $config_data['fontsize']
        ) {
            $this->setUserValue(null, 'fontsize', $org_fontsize, '82%');
        }

        // save language
        if (isset($_COOKIE['pma_lang']) || isset($_POST['lang'])) {
            if ((! isset($config_data['lang'])
                && $GLOBALS['lang'] != 'en')
                || isset($config_data['lang'])
                && $GLOBALS['lang'] != $config_data['lang']
            ) {
                $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
            }
        } else {
            // read language from settings
            if (isset($config_data['lang']) && PMA_langSet($config_data['lang'])) {
                $this->setCookie('pma_lang', $GLOBALS['lang']);
            }
        }

        // save connection collation
        if (isset($_COOKIE['pma_collation_connection'])
            || isset($_POST['collation_connection'])
        ) {
            if ((! isset($config_data['collation_connection'])
                && $GLOBALS['collation_connection'] != 'utf8_general_ci')
                || isset($config_data['collation_connection'])
                && $GLOBALS['collation_connection'] != $config_data['collation_connection']
            ) {
                $this->setUserValue(
                    null,
                    'collation_connection',
                    $GLOBALS['collation_connection'],
                    'utf8_general_ci'
                );
            }
        } else {
            // read collation from settings
            if (isset($config_data['collation_connection'])) {
                $GLOBALS['collation_connection']
                    = $config_data['collation_connection'];
                $this->setCookie(
                    'pma_collation_connection',
                    $GLOBALS['collation_connection']
                );
            }
        }
    }

    /**
     * Sets config value which is stored in user preferences (if available)
     * or in a cookie.
     *
     * If user preferences are not yet initialized, option is applied to
     * global config and added to a update queue, which is processed
     * by {@link loadUserPreferences()}
     *
     * @param string $cookie_name   can be null
     * @param string $cfg_path      configuration path
     * @param mixed  $new_cfg_value new value
     * @param mixed  $default_value default value
     *
     * @return void
     */
    function setUserValue($cookie_name, $cfg_path, $new_cfg_value,
        $default_value = null
    ) {
        // use permanent user preferences if possible
        $prefs_type = $this->get('user_preferences');
        if ($prefs_type) {
            include_once './libraries/user_preferences.lib.php';
            if ($default_value === null) {
                $default_value = PMA_arrayRead($cfg_path, $this->default);
            }
            PMA_persistOption($cfg_path, $new_cfg_value, $default_value);
        }
        if ($prefs_type != 'db' && $cookie_name) {
            // fall back to cookies
            if ($default_value === null) {
                $default_value = PMA_arrayRead($cfg_path, $this->settings);
            }
            $this->setCookie($cookie_name, $new_cfg_value, $default_value);
        }
        PMA_arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
        PMA_arrayWrite($cfg_path, $this->settings, $new_cfg_value);
    }

    /**
     * Reads value stored by {@link setUserValue()}
     *
     * @param string $cookie_name cookie name
     * @param mixed  $cfg_value   config value
     *
     * @return mixed
     */
    function getUserValue($cookie_name, $cfg_value)
    {
        $cookie_exists = isset($_COOKIE) && !empty($_COOKIE[$cookie_name]);
        $prefs_type = $this->get('user_preferences');
        if ($prefs_type == 'db') {
            // permanent user preferences value exists, remove cookie
            if ($cookie_exists) {
                $this->removeCookie($cookie_name);
            }
        } else if ($cookie_exists) {
            return $_COOKIE[$cookie_name];
        }
        // return value from $cfg array
        return $cfg_value;
    }

    /**
     * set source
     *
     * @param string $source source
     *
     * @return void
     */
    function setSource($source)
    {
        $this->source = trim($source);
    }

    /**
     * check config source
     *
     * @return boolean whether source is valid or not
     */
    function checkConfigSource()
    {
        if (! $this->getSource()) {
            // no configuration file set at all
            return false;
        }

        if (! file_exists($this->getSource())) {
            $this->source_mtime = 0;
            return false;
        }

        if (! is_readable($this->getSource())) {
            // manually check if file is readable
            // might be bug #3059806 Supporting running from CIFS/Samba shares

            $contents = false;
            $handle = @fopen($this->getSource(), 'r');
            if ($handle !== false) {
                $contents = @fread($handle, 1); // reading 1 byte is enough to test
                @fclose($handle);
            }
            if ($contents === false) {
                $this->source_mtime = 0;
                PMA_fatalError(
                    sprintf(
                        function_exists('__')
                        ? __('Existing configuration file (%s) is not readable.')
                        : 'Existing configuration file (%s) is not readable.',
                        $this->getSource()
                    )
                );
                return false;
            }
        }

        return true;
    }

    /**
     * verifies the permissions on config file (if asked by configuration)
     * (must be called after config.inc.php has been merged)
     *
     * @return void
     */
    function checkPermissions()
    {
        // Check for permissions (on platforms that support it):
        if ($this->get('CheckConfigurationPermissions')) {
            $perms = @fileperms($this->getSource());
            if (!($perms === false) && ($perms & 2)) {
                // This check is normally done after loading configuration
                $this->checkWebServerOs();
                if ($this->get('PMA_IS_WINDOWS') == 0) {
                    $this->source_mtime = 0;
                    /* Gettext is possibly still not loaded */
                    if (function_exists('__')) {
                        $msg = __('Wrong permissions on configuration file, should not be world writable!');
                    } else {
                        $msg = 'Wrong permissions on configuration file, should not be world writable!';
                    }
                    PMA_fatalError($msg);
                }
            }
        }
    }

    /**
     * returns specific config setting
     *
     * @param string $setting config setting
     *
     * @return mixed value
     */
    function get($setting)
    {
        if (isset($this->settings[$setting])) {
            return $this->settings[$setting];
        }
        return null;
    }

    /**
     * sets configuration variable
     *
     * @param string $setting configuration option
     * @param string $value   new value for configuration option
     *
     * @return void
     */
    function set($setting, $value)
    {
        if (! isset($this->settings[$setting])
            || $this->settings[$setting] != $value
        ) {
            $this->settings[$setting] = $value;
            $this->set_mtime = time();
        }
    }

    /**
     * returns source for current config
     *
     * @return string  config source
     */
    function getSource()
    {
        return $this->source;
    }

    /**
     * returns a unique value to force a CSS reload if either the config
     * or the theme changes
     * must also check the pma_fontsize cookie in case there is no
     * config file
     *
     * @return int Summary of unix timestamps and fontsize,
     * to be unique on theme parameters change
     */
    function getThemeUniqueValue()
    {
        if (null !== $this->get('fontsize')) {
            $fontsize = intval($this->get('fontsize'));
        } elseif (isset($_COOKIE['pma_fontsize'])) {
            $fontsize = intval($_COOKIE['pma_fontsize']);
        } else {
            $fontsize = 0;
        }
        return (
            $fontsize +
            $this->source_mtime +
            $this->default_source_mtime +
            $this->get('user_preferences_mtime') +
            $_SESSION['PMA_Theme']->mtime_info +
            $_SESSION['PMA_Theme']->filesize_info);
    }

    /**
     * $cfg['PmaAbsoluteUri'] is a required directive else cookies won't be
     * set properly and, depending on browsers, inserting or updating a
     * record might fail
     *
     * @return bool
     */
    function checkPmaAbsoluteUri()
    {
        // Setup a default value to let the people and lazy sysadmins work anyway,
        // they'll get an error if the autodetect code doesn't work
        $pma_absolute_uri = $this->get('PmaAbsoluteUri');
        $is_https = $this->detectHttps();

        if (strlen($pma_absolute_uri) < 5) {
            $url = array();

            // If we don't have scheme, we didn't have full URL so we need to
            // dig deeper
            if (empty($url['scheme'])) {
                // Scheme
                if ($is_https) {
                    $url['scheme'] = 'https';
                } else {
                    $url['scheme'] = 'http';
                }

                // Host and port
                if (PMA_getenv('HTTP_HOST')) {
                    // Prepend the scheme before using parse_url() since this
                    // is not part of the RFC2616 Host request-header
                    $parsed_url = parse_url(
                        $url['scheme'] . '://' . PMA_getenv('HTTP_HOST')
                    );
                    if (!empty($parsed_url['host'])) {
                        $url = $parsed_url;
                    } else {
                        $url['host'] = PMA_getenv('HTTP_HOST');
                    }
                } elseif (PMA_getenv('SERVER_NAME')) {
                    $url['host'] = PMA_getenv('SERVER_NAME');
                } else {
                    $this->error_pma_uri = true;
                    return false;
                }

                // If we didn't set port yet...
                if (empty($url['port']) && PMA_getenv('SERVER_PORT')) {
                    $url['port'] = PMA_getenv('SERVER_PORT');
                }

                // And finally the path could be already set from REQUEST_URI
                if (empty($url['path'])) {
                    // we got a case with nginx + php-fpm where PHP_SELF
                    // was not set, so PMA_PHP_SELF was not set as well 
                    if (isset($GLOBALS['PMA_PHP_SELF'])) {
                        $path = parse_url($GLOBALS['PMA_PHP_SELF']);
                    } else {
                        $path = parse_url(PMA_getenv('REQUEST_URI'));
                    }
                    $url['path'] = $path['path'];
                }
            }

            // Make url from parts we have
            $pma_absolute_uri = $url['scheme'] . '://';
            // Was there user information?
            if (!empty($url['user'])) {
                $pma_absolute_uri .= $url['user'];
                if (!empty($url['pass'])) {
                    $pma_absolute_uri .= ':' . $url['pass'];
                }
                $pma_absolute_uri .= '@';
            }
            // Add hostname
            $pma_absolute_uri .= $url['host'];
            // Add port, if it not the default one
            if (! empty($url['port'])
                && (($url['scheme'] == 'http' && $url['port'] != 80)
                || ($url['scheme'] == 'https' && $url['port'] != 443))
            ) {
                $pma_absolute_uri .= ':' . $url['port'];
            }
            // And finally path, without script name, the 'a' is there not to
            // strip our directory, when path is only /pmadir/ without filename.
            // Backslashes returned by Windows have to be changed.
            // Only replace backslashes by forward slashes if on Windows,
            // as the backslash could be valid on a non-Windows system.
            $this->checkWebServerOs();
            if ($this->get('PMA_IS_WINDOWS') == 1) {
                $path = str_replace("\\", "/", dirname($url['path'] . 'a'));
            } else {
                $path = dirname($url['path'] . 'a');
            }

            // To work correctly within transformations overview:
            if (defined('PMA_PATH_TO_BASEDIR') && PMA_PATH_TO_BASEDIR == '../../') {
                if ($this->get('PMA_IS_WINDOWS') == 1) {
                    $path = str_replace("\\", "/", dirname(dirname($path)));
                } else {
                    $path = dirname(dirname($path));
                }
            }

            // PHP's dirname function would have returned a dot
            // when $path contains no slash
            if ($path == '.') {
                $path = '';
            }
            // in vhost situations, there could be already an ending slash
            if (substr($path, -1) != '/') {
                $path .= '/';
            }
            $pma_absolute_uri .= $path;

            // We used to display a warning if PmaAbsoluteUri wasn't set, but now
            // the autodetect code works well enough that we don't display the
            // warning at all. The user can still set PmaAbsoluteUri manually.

        } else {
            // The URI is specified, however users do often specify this
            // wrongly, so we try to fix this.

            // Adds a trailing slash et the end of the phpMyAdmin uri if it
            // does not exist.
            if (substr($pma_absolute_uri, -1) != '/') {
                $pma_absolute_uri .= '/';
            }

            // If URI doesn't start with http:// or https://, we will add
            // this.
            if (substr($pma_absolute_uri, 0, 7) != 'http://'
                && substr($pma_absolute_uri, 0, 8) != 'https://'
            ) {
                $pma_absolute_uri
                    = ($is_https ? 'https' : 'http')
                    . ':' . (substr($pma_absolute_uri, 0, 2) == '//' ? '' : '//')
                    . $pma_absolute_uri;
            }
        }
        $this->set('PmaAbsoluteUri', $pma_absolute_uri);
    }

    /**
     * Converts currently used PmaAbsoluteUri to SSL based variant.
     *
     * @return String witch adjusted URI
     */
    function getSSLUri()
    {
        // grab current URL
        $url = $this->get('PmaAbsoluteUri');
        // Parse current URL
        $parsed = parse_url($url);
        // In case parsing has failed do stupid string replacement
        if ($parsed === false) {
            // Replace http protocol
            return preg_replace('@^http:@', 'https:', $url);
        }

        // Reconstruct URL using parsed parts
        if ($this->get('SSLPort')) {
            $port_number = $this->get('SSLPort');
        } else {
            $port_number = 443;
        }
        return 'https://' . $parsed['host'] . ':' . $port_number . $parsed['path'];
    }

    /**
     * check selected collation_connection
     *
     * @todo check validity of $_REQUEST['collation_connection']
     *
     * @return void
     */
    function checkCollationConnection()
    {
        if (! empty($_REQUEST['collation_connection'])) {
            $this->set(
                'collation_connection',
                strip_tags($_REQUEST['collation_connection'])
            );
        }
    }

    /**
     * checks for font size configuration, and sets font size as requested by user
     *
     * @return void
     */
    function checkFontsize()
    {
        $new_fontsize = '';

        if (isset($_GET['set_fontsize'])) {
            $new_fontsize = $_GET['set_fontsize'];
        } elseif (isset($_POST['set_fontsize'])) {
            $new_fontsize = $_POST['set_fontsize'];
        } elseif (isset($_COOKIE['pma_fontsize'])) {
            $new_fontsize = $_COOKIE['pma_fontsize'];
        }

        if (preg_match('/^[0-9.]+(px|em|pt|\%)$/', $new_fontsize)) {
            $this->set('fontsize', $new_fontsize);
        } elseif (! $this->get('fontsize')) {
            // 80% would correspond to the default browser font size
            // of 16, but use 82% to help read the monoface font
            $this->set('fontsize', '82%');
        }

        $this->setCookie('pma_fontsize', $this->get('fontsize'), '82%');
    }

    /**
     * checks if upload is enabled
     *
     * @return void
     */
    function checkUpload()
    {
        if (ini_get('file_uploads')) {
            $this->set('enable_upload', true);
            // if set "php_admin_value file_uploads Off" in httpd.conf
            // ini_get() also returns the string "Off" in this case:
            if ('off' == strtolower(ini_get('file_uploads'))) {
                $this->set('enable_upload', false);
            }
        } else {
            $this->set('enable_upload', false);
        }
    }

    /**
     * Maximum upload size as limited by PHP
     * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
     *
     * this section generates $max_upload_size in bytes
     *
     * @return void
     */
    function checkUploadSize()
    {
        if (! $filesize = ini_get('upload_max_filesize')) {
            $filesize = "5M";
        }

        if ($postsize = ini_get('post_max_size')) {
            $this->set(
                'max_upload_size',
                min(PMA_getRealSize($filesize), PMA_getRealSize($postsize))
            );
        } else {
            $this->set('max_upload_size', PMA_getRealSize($filesize));
        }
    }

    /**
     * check for https
     *
     * @return void
     */
    function checkIsHttps()
    {
        $this->set('is_https', $this->isHttps());
    }

    /**
     * Checks if protocol is https
     *
     * This function checks if the https protocol is used in the PmaAbsoluteUri
     * configuration setting, as opposed to detectHttps() which checks if the
     * https protocol is used on the active connection.
     *
     * @return bool
     */
    public function isHttps()
    {
        static $is_https = null;

        if (null !== $is_https) {
            return $is_https;
        }

        $url = parse_url($this->get('PmaAbsoluteUri'));

        if (isset($url['scheme']) && $url['scheme'] == 'https') {
            $is_https = true;
        } else {
            $is_https = false;
        }

        return $is_https;
    }

    /**
     * Detects whether https appears to be used.
     *
     * This function checks if the https protocol is used in the current connection
     * with the webserver, based on environment variables.
     * Please note that this just detects what we see, so
     * it completely ignores things like reverse proxies.
     *
     * @return bool
     */
    function detectHttps()
    {
        $is_https = false;

        $url = array();

        // At first we try to parse REQUEST_URI, it might contain full URL,
        if (PMA_getenv('REQUEST_URI')) {
            // produces E_WARNING if it cannot get parsed, e.g. '/foobar:/'
            $url = @parse_url(PMA_getenv('REQUEST_URI'));
            if ($url === false) {
                $url = array();
            }
        }

        // If we don't have scheme, we didn't have full URL so we need to
        // dig deeper
        if (empty($url['scheme'])) {
            // Scheme
            if (PMA_getenv('HTTP_SCHEME')) {
                $url['scheme'] = PMA_getenv('HTTP_SCHEME');
            } elseif (PMA_getenv('HTTPS')
                && strtolower(PMA_getenv('HTTPS')) == 'on'
            ) {
                $url['scheme'] = 'https';
            } elseif (PMA_getenv('HTTP_X_FORWARDED_PROTO')) {
                $url['scheme'] = strtolower(PMA_getenv('HTTP_X_FORWARDED_PROTO'));
            } elseif (PMA_getenv('HTTP_FRONT_END_HTTPS')
                && strtolower(PMA_getenv('HTTP_FRONT_END_HTTPS')) == 'on'
            ) {
                $url['scheme'] = 'https';
            } else {
                $url['scheme'] = 'http';
            }
        }

        if (isset($url['scheme']) && $url['scheme'] == 'https') {
            $is_https = true;
        } else {
            $is_https = false;
        }

        return $is_https;
    }

    /**
     * detect correct cookie path
     *
     * @return void
     */
    function checkCookiePath()
    {
        $this->set('cookie_path', $this->getCookiePath());
    }

    /**
     * Get cookie path
     *
     * @return string
     */
    public function getCookiePath()
    {
        static $cookie_path = null;

        if (null !== $cookie_path && !defined('TESTSUITE')) {
            return $cookie_path;
        }

        $parsed_url = parse_url($this->get('PmaAbsoluteUri'));

        $cookie_path   = $parsed_url['path'];

        return $cookie_path;
    }

    /**
     * enables backward compatibility
     *
     * @return void
     */
    function enableBc()
    {
        $GLOBALS['cfg']             = $this->settings;
        $GLOBALS['default_server']  = $this->default_server;
        unset($this->default_server);
        $GLOBALS['collation_connection'] = $this->get('collation_connection');
        $GLOBALS['is_upload']       = $this->get('enable_upload');
        $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
        $GLOBALS['cookie_path']     = $this->get('cookie_path');
        $GLOBALS['is_https']        = $this->get('is_https');

        $defines = array(
            'PMA_VERSION',
            'PMA_THEME_VERSION',
            'PMA_THEME_GENERATION',
            'PMA_PHP_STR_VERSION',
            'PMA_PHP_INT_VERSION',
            'PMA_IS_WINDOWS',
            'PMA_IS_IIS',
            'PMA_IS_GD2',
            'PMA_USR_OS',
            'PMA_USR_BROWSER_VER',
            'PMA_USR_BROWSER_AGENT'
            );

        foreach ($defines as $define) {
            if (! defined($define)) {
                define($define, $this->get($define));
            }
        }
    }

    /**
     * returns options for font size selection
     *
     * @param string $current_size current selected font size with unit
     *
     * @return array selectable font sizes
     *
     * @static
     */
    static protected function getFontsizeOptions($current_size = '82%')
    {
        $unit = preg_replace('/[0-9.]*/', '', $current_size);
        $value = preg_replace('/[^0-9.]*/', '', $current_size);

        $factors = array();
        $options = array();
        $options["$value"] = $value . $unit;

        if ($unit === '%') {
            $factors[] = 1;
            $factors[] = 5;
            $factors[] = 10;
        } elseif ($unit === 'em') {
            $factors[] = 0.05;
            $factors[] = 0.2;
            $factors[] = 1;
        } elseif ($unit === 'pt') {
            $factors[] = 0.5;
            $factors[] = 2;
        } elseif ($unit === 'px') {
            $factors[] = 1;
            $factors[] = 5;
            $factors[] = 10;
        } else {
            //unknown font size unit
            $factors[] = 0.05;
            $factors[] = 0.2;
            $factors[] = 1;
            $factors[] = 5;
            $factors[] = 10;
        }

        foreach ($factors as $key => $factor) {
            $option_inc = $value + $factor;
            $option_dec = $value - $factor;
            while (count($options) < 21) {
                $options["$option_inc"] = $option_inc . $unit;
                if ($option_dec > $factors[0]) {
                    $options["$option_dec"] = $option_dec . $unit;
                }
                $option_inc += $factor;
                $option_dec -= $factor;
                if (isset($factors[$key + 1])
                    && $option_inc >= $value + $factors[$key + 1]
                ) {
                    break;
                }
            }
        }
        ksort($options);
        return $options;
    }

    /**
     * returns html selectbox for font sizes
     *
     * @static
     *
     * @return string html selectbox
     */
    static protected function getFontsizeSelection()
    {
        $current_size = $GLOBALS['PMA_Config']->get('fontsize');
        // for the case when there is no config file (this is supported)
        if (empty($current_size)) {
            if (isset($_COOKIE['pma_fontsize'])) {
                $current_size = $_COOKIE['pma_fontsize'];
            } else {
                $current_size = '82%';
            }
        }
        $options = PMA_Config::getFontsizeOptions($current_size);

        $return = '<label for="select_fontsize">' . __('Font size')
            . ':</label>' . "\n"
            . '<select name="set_fontsize" id="select_fontsize"'
            . ' class="autosubmit">' . "\n";
        foreach ($options as $option) {
            $return .= '<option value="' . $option . '"';
            if ($option == $current_size) {
                $return .= ' selected="selected"';
            }
            $return .= '>' . $option . '</option>' . "\n";
        }
        $return .= '</select>';

        return $return;
    }

    /**
     * return complete font size selection form
     *
     * @static
     *
     * @return string html selectbox
     */
    static public function getFontsizeForm()
    {
        return '<form name="form_fontsize_selection" id="form_fontsize_selection"'
            . ' method="get" action="index.php" class="disableAjax">' . "\n"
            . PMA_generate_common_hidden_inputs() . "\n"
            . PMA_Config::getFontsizeSelection() . "\n"
            . '</form>';
    }

    /**
     * removes cookie
     *
     * @param string $cookie name of cookie to remove
     *
     * @return boolean result of setcookie()
     */
    function removeCookie($cookie)
    {
        if (defined('TESTSUITE')) {
            if (isset($_COOKIE[$cookie])) {
                unset($_COOKIE[$cookie]);
            }
            return true;
        }
        return setcookie(
            $cookie,
            '',
            time() - 3600,
            $this->getCookiePath(),
            '',
            $this->isHttps()
        );
    }

    /**
     * sets cookie if value is different from current cookie value,
     * or removes if value is equal to default
     *
     * @param string $cookie   name of cookie to remove
     * @param mixed  $value    new cookie value
     * @param string $default  default value
     * @param int    $validity validity of cookie in seconds (default is one month)
     * @param bool   $httponly whether cookie is only for HTTP (and not for scripts)
     *
     * @return boolean result of setcookie()
     */
    function setCookie($cookie, $value, $default = null, $validity = null,
        $httponly = true
    ) {
        if (strlen($value) && null !== $default && $value === $default) {
            // default value is used
            if (isset($_COOKIE[$cookie])) {
                // remove cookie
                return $this->removeCookie($cookie);
            }
            return false;
        }

        if (! strlen($value) && isset($_COOKIE[$cookie])) {
            // remove cookie, value is empty
            return $this->removeCookie($cookie);
        }

        if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
            // set cookie with new value
            /* Calculate cookie validity */
            if ($validity === null) {
                $validity = time() + 2592000;
            } elseif ($validity == 0) {
                $validity = 0;
            } else {
                $validity = time() + $validity;
            }
            if (defined('TESTSUITE')) {
                $_COOKIE[$cookie] = $value;
                return true;
            }
            return setcookie(
                $cookie,
                $value,
                $validity,
                $this->getCookiePath(),
                '',
                $this->isHttps(),
                $httponly
            );
        }

        // cookie has already $value as value
        return true;
    }
}
?>