Welcome to mirror list, hosted at ThFree Co, Russian Federation.

server_privileges.lib.php « libraries - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 93e101cde7752548322ab9553b48677202f7bc08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * set of functions with the Privileges section in pma
 *
 * @package PhpMyAdmin
 */

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

/**
 * Get Html for User Group Dialog
 *
 * @param string $username     username
 * @param bool   $is_menuswork Is menuswork set in configuration
 *
 * @return string html
 */
function PMA_getHtmlForUserGroupDialog($username, $is_menuswork)
{
    $html = '';
    if (! empty($_REQUEST['edit_user_group_dialog']) && $is_menuswork) {
        $dialog = PMA_getHtmlToChooseUserGroup($username);
        $response = PMA_Response::getInstance();
        if ($GLOBALS['is_ajax_request']) {
            $response->addJSON('message', $dialog);
            exit;
        } else {
            $html .= $dialog;
        }
    }

    return $html;
}

/**
 * Escapes wildcard in a database+table specification
 * before using it in a GRANT statement.
 *
 * Escaping a wildcard character in a GRANT is only accepted at the global
 * or database level, not at table level; this is why I remove
 * the escaping character. Internally, in mysql.tables_priv.Db there are
 * no escaping (for example test_db) but in mysql.db you'll see test\_db
 * for a db-specific privilege.
 *
 * @param string $dbname    Database name
 * @param string $tablename Table name
 *
 * @return string the escaped (if necessary) database.table
 */
function PMA_wildcardEscapeForGrant($dbname, $tablename)
{
    if (!/*overload*/mb_strlen($dbname)) {
        $db_and_table = '*.*';
    } else {
        if (/*overload*/mb_strlen($tablename)) {
            $db_and_table = PMA_Util::backquote(
                PMA_Util::unescapeMysqlWildcards($dbname)
            )
            . '.' . PMA_Util::backquote($tablename);
        } else {
            $db_and_table = PMA_Util::backquote($dbname) . '.*';
        }
    }
    return $db_and_table;
}

/**
 * Generates a condition on the user name
 *
 * @param string $initial the user's initial
 *
 * @return string   the generated condition
 */
function PMA_rangeOfUsers($initial = '')
{
    // strtolower() is used because the User field
    // might be BINARY, so LIKE would be case sensitive
    if ($initial === null || $initial === '') {
        return '';
    }

    $ret = " WHERE `User` LIKE '"
        . PMA_Util::sqlAddSlashes($initial, true) . "%'"
        . " OR `User` LIKE '"
        . PMA_Util::sqlAddSlashes(/*overload*/mb_strtolower($initial), true)
        . "%'";
    return $ret;
} // end function

/**
 * Formats privilege name for a display
 *
 * @param array   $privilege Privilege information
 * @param boolean $html      Whether to use HTML
 *
 * @return string
 */
function PMA_formatPrivilege($privilege, $html)
{
    if ($html) {
        return '<dfn title="' . $privilege[2] . '">'
            . $privilege[1] . '</dfn>';
    } else {
        return $privilege[1];
    }
}

/**
 * Parses privileges into an array, it modifies the array
 *
 * @param array &$row Results row from
 *
 * @return void
 */
function PMA_fillInTablePrivileges(&$row)
{
    $row1 = $GLOBALS['dbi']->fetchSingleRow(
        'SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';',
        'ASSOC', $GLOBALS['userlink']
    );
    // note: in MySQL 5.0.3 we get "Create View', 'Show view';
    // the View for Create is spelled with uppercase V
    // the view for Show is spelled with lowercase v
    // and there is a space between the words

    $av_grants = explode(
        '\',\'',
        /*overload*/mb_substr(
            $row1['Type'],
            /*overload*/mb_strpos($row1['Type'], '(') + 2,
            /*overload*/mb_strpos($row1['Type'], ')')
            - /*overload*/mb_strpos($row1['Type'], '(') - 3
        )
    );

    $users_grants = explode(',', $row['Table_priv']);

    foreach ($av_grants as $current_grant) {
        $row[$current_grant . '_priv']
            = in_array($current_grant, $users_grants) ? 'Y' : 'N';
    }
    unset($row['Table_priv']);
}


/**
 * Extracts the privilege information of a priv table row
 *
 * @param array|null $row        the row
 * @param boolean    $enableHTML add <dfn> tag with tooltips
 * @param boolean    $tablePrivs whether row contains table privileges
 *
 * @global  resource $user_link the database connection
 *
 * @return array
 */
function PMA_extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
{
    if ($tablePrivs) {
        $grants = PMA_getTableGrantsArray();
    } else {
        $grants = PMA_getGrantsArray();
    }

    if (! is_null($row) && isset($row['Table_priv'])) {
        PMA_fillInTablePrivileges($row);
    }

    $privs = array();
    $allPrivileges = true;
    foreach ($grants as $current_grant) {
        if ((! is_null($row) && isset($row[$current_grant[0]]))
            || (is_null($row) && isset($GLOBALS[$current_grant[0]]))
        ) {
            if ((! is_null($row) && $row[$current_grant[0]] == 'Y')
                || (is_null($row)
                && ($GLOBALS[$current_grant[0]] == 'Y'
                || (is_array($GLOBALS[$current_grant[0]])
                && count($GLOBALS[$current_grant[0]]) == $_REQUEST['column_count']
                && empty($GLOBALS[$current_grant[0] . '_none']))))
            ) {
                $privs[] = PMA_formatPrivilege($current_grant, $enableHTML);
            } elseif (! empty($GLOBALS[$current_grant[0]])
                && is_array($GLOBALS[$current_grant[0]])
                && empty($GLOBALS[$current_grant[0] . '_none'])
            ) {
                $privs[] = PMA_formatPrivilege($current_grant, $enableHTML)
                    . ' (`' . join('`, `', $GLOBALS[$current_grant[0]]) . '`)';
            } else {
                $allPrivileges = false;
            }
        }
    }
    if (empty($privs)) {
        if ($enableHTML) {
            $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
        } else {
            $privs[] = 'USAGE';
        }
    } elseif ($allPrivileges
        && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])
    ) {
        if ($enableHTML) {
            $privs = array('<dfn title="'
                . __('Includes all privileges except GRANT.')
                . '">ALL PRIVILEGES</dfn>'
            );
        } else {
            $privs = array('ALL PRIVILEGES');
        }
    }
    return $privs;
} // end of the 'PMA_extractPrivInfo()' function

/**
 * Returns an array of table grants and their descriptions
 *
 * @return array array of table grants
 */
function PMA_getTableGrantsArray()
{
    return array(
        array(
            'Delete',
            'DELETE',
            $GLOBALS['strPrivDescDelete']
        ),
        array(
            'Create',
            'CREATE',
            $GLOBALS['strPrivDescCreateTbl']
        ),
        array(
            'Drop',
            'DROP',
            $GLOBALS['strPrivDescDropTbl']
        ),
        array(
            'Index',
            'INDEX',
            $GLOBALS['strPrivDescIndex']
        ),
        array(
            'Alter',
            'ALTER',
            $GLOBALS['strPrivDescAlter']
        ),
        array(
            'Create View',
            'CREATE_VIEW',
            $GLOBALS['strPrivDescCreateView']
        ),
        array(
            'Show view',
            'SHOW_VIEW',
            $GLOBALS['strPrivDescShowView']
        ),
        array(
            'Trigger',
            'TRIGGER',
            $GLOBALS['strPrivDescTrigger']
        ),
    );
}

/**
 * Get the grants array which contains all the privilege types
 * and relevant grant messages
 *
 * @return array
 */
function PMA_getGrantsArray()
{
    return array(
        array(
            'Select_priv',
            'SELECT',
            __('Allows reading data.')
        ),
        array(
            'Insert_priv',
            'INSERT',
            __('Allows inserting and replacing data.')
        ),
        array(
            'Update_priv',
            'UPDATE',
            __('Allows changing data.')
        ),
        array(
            'Delete_priv',
            'DELETE',
            __('Allows deleting data.')
        ),
        array(
            'Create_priv',
            'CREATE',
            __('Allows creating new databases and tables.')
        ),
        array(
            'Drop_priv',
            'DROP',
            __('Allows dropping databases and tables.')
        ),
        array(
            'Reload_priv',
            'RELOAD',
            __('Allows reloading server settings and flushing the server\'s caches.')
        ),
        array(
            'Shutdown_priv',
            'SHUTDOWN',
            __('Allows shutting down the server.')
        ),
        array(
            'Process_priv',
            'PROCESS',
            __('Allows viewing processes of all users.')
        ),
        array(
            'File_priv',
            'FILE',
            __('Allows importing data from and exporting data into files.')
        ),
        array(
            'References_priv',
            'REFERENCES',
            __('Has no effect in this MySQL version.')
        ),
        array(
            'Index_priv',
            'INDEX',
            __('Allows creating and dropping indexes.')
        ),
        array(
            'Alter_priv',
            'ALTER',
            __('Allows altering the structure of existing tables.')
        ),
        array(
            'Show_db_priv',
            'SHOW DATABASES',
            __('Gives access to the complete list of databases.')
        ),
        array(
            'Super_priv',
            'SUPER',
            __(
                'Allows connecting, even if maximum number of connections '
                . 'is reached; required for most administrative operations '
                . 'like setting global variables or killing threads of other users.'
            )
        ),
        array(
            'Create_tmp_table_priv',
            'CREATE TEMPORARY TABLES',
            __('Allows creating temporary tables.')
        ),
        array(
            'Lock_tables_priv',
            'LOCK TABLES',
            __('Allows locking tables for the current thread.')
        ),
        array(
            'Repl_slave_priv',
            'REPLICATION SLAVE',
            __('Needed for the replication slaves.')
        ),
        array(
            'Repl_client_priv',
            'REPLICATION CLIENT',
            __('Allows the user to ask where the slaves / masters are.')
        ),
        array(
            'Create_view_priv',
            'CREATE VIEW',
            __('Allows creating new views.')
        ),
        array(
            'Event_priv',
            'EVENT',
            __('Allows to set up events for the event scheduler.')
        ),
        array(
            'Trigger_priv',
            'TRIGGER',
            __('Allows creating and dropping triggers.')
        ),
        // for table privs:
        array(
            'Create View_priv',
            'CREATE VIEW',
            __('Allows creating new views.')
        ),
        array(
            'Show_view_priv',
            'SHOW VIEW',
            __('Allows performing SHOW CREATE VIEW queries.')
        ),
        // for table privs:
        array(
            'Show view_priv',
            'SHOW VIEW',
            __('Allows performing SHOW CREATE VIEW queries.')
        ),
        array(
            'Create_routine_priv',
            'CREATE ROUTINE',
            __('Allows creating stored routines.')
        ),
        array(
            'Alter_routine_priv',
            'ALTER ROUTINE',
            __('Allows altering and dropping stored routines.')
        ),
        array(
            'Create_user_priv',
            'CREATE USER',
            __('Allows creating, dropping and renaming user accounts.')
        ),
        array(
            'Execute_priv',
            'EXECUTE',
            __('Allows executing stored routines.')
        ),
    );
}

/**
 * Displays on which column(s) a table-specific privilege is granted
 *
 * @param array  $columns          columns array
 * @param array  $row              first row from result or boolean false
 * @param string $name_for_select  privilege types - Select_priv, Insert_priv
 *                                 Update_priv, References_priv
 * @param string $priv_for_header  privilege for header
 * @param string $name             privilege name: insert, select, update, references
 * @param string $name_for_dfn     name for dfn
 * @param string $name_for_current name for current
 *
 * @return string $html_output html snippet
 */
function PMA_getHtmlForColumnPrivileges($columns, $row, $name_for_select,
    $priv_for_header, $name, $name_for_dfn, $name_for_current
) {
    $html_output = '<div class="item" id="div_item_' . $name . '">' . "\n"
        . '<label for="select_' . $name . '_priv">' . "\n"
        . '<code><dfn title="' . $name_for_dfn . '">'
        . $priv_for_header . '</dfn></code>' . "\n"
        . '</label><br />' . "\n"
        . '<select id="select_' . $name . '_priv" name="'
        . $name_for_select . '[]" multiple="multiple" size="8">' . "\n";

    foreach ($columns as $currCol => $currColPrivs) {
        $html_output .= '<option '
            . 'value="' . htmlspecialchars($currCol) . '"';
        if ($row[$name_for_select] == 'Y'
            || $currColPrivs[$name_for_current]
        ) {
            $html_output .= ' selected="selected"';
        }
        $html_output .= '>'
            . htmlspecialchars($currCol) . '</option>' . "\n";
    }

    $html_output .= '</select>' . "\n"
        . '<i>' . __('Or') . '</i>' . "\n"
        . '<label for="checkbox_' . $name_for_select
        . '_none"><input type="checkbox"'
        . ' name="' . $name_for_select . '_none" id="checkbox_'
        . $name_for_select . '_none" title="'
        . _pgettext('None privileges', 'None') . '" />'
        . _pgettext('None privileges', 'None') . '</label>' . "\n"
        . '</div>' . "\n";
    return $html_output;
} // end function

/**
 * Get sql query for display privileges table
 *
 * @param string $db       the database
 * @param string $table    the table
 * @param string $username username for database connection
 * @param string $hostname hostname for database connection
 *
 * @return string sql query
 */
function PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
{
    if ($db == '*') {
        return "SELECT * FROM `mysql`.`user`"
            . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
            . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
    } elseif ($table == '*') {
        return "SELECT * FROM `mysql`.`db`"
            . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
            . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
            . " AND '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
            . " LIKE `Db`;";
    }
    return "SELECT `Table_priv`"
        . " FROM `mysql`.`tables_priv`"
        . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
        . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
        . " AND `Db` = '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
        . " AND `Table_name` = '" . PMA_Util::sqlAddSlashes($table) . "';";
}

/**
 * Displays a dropdown to select the user group
 * with menu items configured to each of them.
 *
 * @param string $username username
 *
 * @return string html to select the user group
 */
function PMA_getHtmlToChooseUserGroup($username)
{
    $html_output = '<form class="ajax" id="changeUserGroupForm"'
            . ' action="server_privileges.php" method="post">';
    $params = array('username' => $username);
    $html_output .= PMA_URL_getHiddenInputs($params);
    $html_output .= '<fieldset id="fieldset_user_group_selection">';
    $html_output .= '<legend>' . __('User group') . '</legend>';

    $cfgRelation = PMA_getRelationsParam();
    $groupTable = PMA_Util::backquote($cfgRelation['db'])
        . "." . PMA_Util::backquote($cfgRelation['usergroups']);
    $userTable = PMA_Util::backquote($cfgRelation['db'])
        . "." . PMA_Util::backquote($cfgRelation['users']);

    $userGroups = array();
    $sql_query = "SELECT DISTINCT `usergroup` FROM " . $groupTable;
    $result = PMA_queryAsControlUser($sql_query, false);
    if ($result) {
        while ($row = $GLOBALS['dbi']->fetchRow($result)) {
            $userGroups[] = $row[0];
        }
    }
    $GLOBALS['dbi']->freeResult($result);

    $userGroup = '';
    if (isset($GLOBALS['username'])) {
        $sql_query = "SELECT `usergroup` FROM " . $userTable
            . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
        $userGroup = $GLOBALS['dbi']->fetchValue(
            $sql_query, 0, 0, $GLOBALS['controllink']
        );
    }

    $html_output .= __('User group') . ': ';
    $html_output .= '<select name="userGroup">';
    $html_output .= '<option value=""></option>';
    foreach ($userGroups as $oneUserGroup) {
        $html_output .= '<option value="' . htmlspecialchars($oneUserGroup) . '"'
            . ($oneUserGroup == $userGroup ? ' selected="selected"' : '')
            . '>'
            . htmlspecialchars($oneUserGroup)
            . '</option>';
    }
    $html_output .= '</select>';
    $html_output .= '<input type="hidden" name="changeUserGroup" value="1">';
    $html_output .= '</fieldset>';
    $html_output .= '</form>';
    return $html_output;
}

/**
 * Sets the user group from request values
 *
 * @param string $username  username
 * @param string $userGroup user group to set
 *
 * @return void
 */
function PMA_setUserGroup($username, $userGroup)
{
    $cfgRelation = PMA_getRelationsParam();
    $userTable = PMA_Util::backquote($cfgRelation['db'])
        . "." . PMA_Util::backquote($cfgRelation['users']);

    $sql_query = "SELECT `usergroup` FROM " . $userTable
        . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
    $oldUserGroup = $GLOBALS['dbi']->fetchValue(
        $sql_query, 0, 0, $GLOBALS['controllink']
    );

    if ($oldUserGroup === false) {
        $upd_query = "INSERT INTO " . $userTable . "(`username`, `usergroup`)"
            . " VALUES ('" . PMA_Util::sqlAddSlashes($username) . "', "
            . "'" . PMA_Util::sqlAddSlashes($userGroup) . "')";
    } else {
        if (empty($userGroup)) {
            $upd_query = "DELETE FROM " . $userTable
                . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
        } elseif ($oldUserGroup != $userGroup) {
            $upd_query = "UPDATE " . $userTable
                . " SET `usergroup`='" . PMA_Util::sqlAddSlashes($userGroup) . "'"
                . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
        }
    }
    if (isset($upd_query)) {
        PMA_queryAsControlUser($upd_query);
    }
}

/**
 * Displays the privileges form table
 *
 * @param string  $db     the database
 * @param string  $table  the table
 * @param boolean $submit whether to display the submit button or not
 *
 * @global  array     $cfg         the phpMyAdmin configuration
 * @global  resource  $user_link   the database connection
 *
 * @return string html snippet
 */
function PMA_getHtmlToDisplayPrivilegesTable($db = '*',
    $table = '*', $submit = true
) {
    $html_output = '';
    $sql_query = '';

    if ($db == '*') {
        $table = '*';
    }

    if (isset($GLOBALS['username'])) {
        $username = $GLOBALS['username'];
        $hostname = $GLOBALS['hostname'];
        $sql_query = PMA_getSqlQueryForDisplayPrivTable(
            $db, $table, $username, $hostname
        );
        $row = $GLOBALS['dbi']->fetchSingleRow($sql_query);
    }
    if (empty($row)) {
        if ($table == '*' && $GLOBALS['is_superuser']) {
            if ($db == '*') {
                $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
            } elseif ($table == '*') {
                $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
            }
            $res = $GLOBALS['dbi']->query($sql_query);
            while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
                if (mb_substr($row1[0], 0, 4) == 'max_') {
                    $row[$row1[0]] = 0;
                } else {
                    $row[$row1[0]] = 'N';
                }
            }
            $GLOBALS['dbi']->freeResult($res);
        } elseif ($table == '*') {
            $row = array();
        } else {
            $row = array('Table_priv' => '');
        }
    }
    if (isset($row['Table_priv'])) {
        PMA_fillInTablePrivileges($row);

        // get columns
        $res = $GLOBALS['dbi']->tryQuery(
            'SHOW COLUMNS FROM '
            . PMA_Util::backquote(
                PMA_Util::unescapeMysqlWildcards($db)
            )
            . '.' . PMA_Util::backquote($table) . ';'
        );
        $columns = array();
        if ($res) {
            while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
                $columns[$row1[0]] = array(
                    'Select' => false,
                    'Insert' => false,
                    'Update' => false,
                    'References' => false
                );
            }
            $GLOBALS['dbi']->freeResult($res);
        }
        unset($res, $row1);
    }
    // table-specific privileges
    if (! empty($columns)) {
        $html_output .= PMA_getHtmlForTableSpecificPrivileges(
            $username, $hostname, $db, $table, $columns, $row
        );
    } else {
        // global or db-specific
        $html_output .= PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row);
    }
    $html_output .= '</fieldset>' . "\n";
    if ($submit) {
        $html_output .= '<fieldset id="fieldset_user_privtable_footer" '
            . 'class="tblFooters">' . "\n"
            . '<input type="hidden" name="update_privs" value="1" />' . "\n"
            . '<input type="submit" value="' . __('Go') . '" />' . "\n"
            . '</fieldset>' . "\n";
    }
    return $html_output;
} // end of the 'PMA_displayPrivTable()' function

/**
 * Get HTML for "Resource limits"
 *
 * @param array $row first row from result or boolean false
 *
 * @return string html snippet
 */
function PMA_getHtmlForResourceLimits($row)
{
    $html_output = '<fieldset>' . "\n"
        . '<legend>' . __('Resource limits') . '</legend>' . "\n"
        . '<p><small>'
        . '<i>' . __('Note: Setting these options to 0 (zero) removes the limit.')
        . '</i></small></p>' . "\n";

    $html_output .= '<div class="item">' . "\n"
        . '<label for="text_max_questions">'
        . '<code><dfn title="'
        . __(
            'Limits the number of queries the user may send to the server per hour.'
        )
        . '">'
        . 'MAX QUERIES PER HOUR'
        . '</dfn></code></label>' . "\n"
        . '<input type="number" name="max_questions" id="text_max_questions" '
        . 'value="'
        . (isset($row['max_questions']) ? $row['max_questions'] : '0')
        . '" min="0" '
        . 'title="'
        . __(
            'Limits the number of queries the user may send to the server per hour.'
        )
        . '" />' . "\n"
        . '</div>' . "\n";

    $html_output .= '<div class="item">' . "\n"
        . '<label for="text_max_updates">'
        . '<code><dfn title="'
        . __(
            'Limits the number of commands that change any table '
            . 'or database the user may execute per hour.'
        ) . '">'
        . 'MAX UPDATES PER HOUR'
        . '</dfn></code></label>' . "\n"
        . '<input type="number" name="max_updates" id="text_max_updates" '
        . 'value="'
        . (isset($row['max_updates']) ? $row['max_updates'] : '0')
        . '" min="0" '
        . 'title="'
        . __(
            'Limits the number of commands that change any table '
            . 'or database the user may execute per hour.'
        )
        . '" />' . "\n"
        . '</div>' . "\n";

    $html_output .= '<div class="item">' . "\n"
        . '<label for="text_max_connections">'
        . '<code><dfn title="'
        . __(
            'Limits the number of new connections the user may open per hour.'
        ) . '">'
        . 'MAX CONNECTIONS PER HOUR'
        . '</dfn></code></label>' . "\n"
        . '<input type="number" name="max_connections" id="text_max_connections" '
        . 'value="'
        . (isset($row['max_connections']) ? $row['max_connections'] : '0')
        . '" min="0" '
        . 'title="' . __(
            'Limits the number of new connections the user may open per hour.'
        )
        . '" />' . "\n"
        . '</div>' . "\n";

    $html_output .= '<div class="item">' . "\n"
        . '<label for="text_max_user_connections">'
        . '<code><dfn title="'
        . __('Limits the number of simultaneous connections the user may have.')
        . '">'
        . 'MAX USER_CONNECTIONS'
        . '</dfn></code></label>' . "\n"
        . '<input type="number" name="max_user_connections" '
        . 'id="text_max_user_connections" '
        . 'value="'
        . (isset($row['max_user_connections']) ? $row['max_user_connections'] : '0')
        . '" '
        . 'title="'
        . __('Limits the number of simultaneous connections the user may have.')
        . '" />' . "\n"
        . '</div>' . "\n";

    $html_output .= '</fieldset>' . "\n";

    return $html_output;
}

/**
 * Get the HTML snippet for table specific privileges
 *
 * @param string $username username for database connection
 * @param string $hostname hostname for database connection
 * @param string $db       the database
 * @param string $table    the table
 * @param array  $columns  columns array
 * @param array  $row      current privileges row
 *
 * @return string $html_output
 */
function PMA_getHtmlForTableSpecificPrivileges(
    $username, $hostname, $db, $table, $columns, $row
) {
    $res = $GLOBALS['dbi']->query(
        'SELECT `Column_name`, `Column_priv`'
        . ' FROM `mysql`.`columns_priv`'
        . ' WHERE `User`'
        . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
        . ' AND `Host`'
        . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'"
        . ' AND `Db`'
        . ' = \'' . PMA_Util::sqlAddSlashes(
            PMA_Util::unescapeMysqlWildcards($db)
        ) . "'"
        . ' AND `Table_name`'
        . ' = \'' . PMA_Util::sqlAddSlashes($table) . '\';'
    );

    while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
        $row1[1] = explode(',', $row1[1]);
        foreach ($row1[1] as $current) {
            $columns[$row1[0]][$current] = true;
        }
    }
    $GLOBALS['dbi']->freeResult($res);
    unset($res, $row1, $current);

    $html_output = '<input type="hidden" name="grant_count" '
        . 'value="' . count($row) . '" />' . "\n"
        . '<input type="hidden" name="column_count" '
        . 'value="' . count($columns) . '" />' . "\n"
        . '<fieldset id="fieldset_user_priv">' . "\n"
        . '<legend data-submenu-label="Table">' . __('Table-specific privileges')
        . PMA_Util::showHint(
            __('Note: MySQL privilege names are expressed in English.')
        )
        . '</legend>' . "\n";

    // privs that are attached to a specific column
    $html_output .= PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn(
        $columns, $row
    );

    // privs that are not attached to a specific column
    $html_output .= '<div class="item">' . "\n"
        . PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
        . '</div>' . "\n";

    // for Safari 2.0.2
    $html_output .= '<div class="clearfloat"></div>' . "\n";

    return $html_output;
}

/**
 * Get HTML snippet for privileges that are attached to a specific column
 *
 * @param array $columns columns array
 * @param array $row     first row from result or boolean false
 *
 * @return string $html_output
 */
function PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn($columns, $row)
{
    $html_output = PMA_getHtmlForColumnPrivileges(
        $columns, $row, 'Select_priv', 'SELECT',
        'select', __('Allows reading data.'), 'Select'
    );

    $html_output .= PMA_getHtmlForColumnPrivileges(
        $columns, $row, 'Insert_priv', 'INSERT',
        'insert', __('Allows inserting and replacing data.'), 'Insert'
    );

    $html_output .= PMA_getHtmlForColumnPrivileges(
        $columns, $row, 'Update_priv', 'UPDATE',
        'update', __('Allows changing data.'), 'Update'
    );

    $html_output .= PMA_getHtmlForColumnPrivileges(
        $columns, $row, 'References_priv', 'REFERENCES', 'references',
        __('Has no effect in this MySQL version.'), 'References'
    );
    return $html_output;
}

/**
 * Get HTML for privileges that are not attached to a specific column
 *
 * @param array $row first row from result or boolean false
 *
 * @return string $html_output
 */
function PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
{
    $html_output = '';

    foreach ($row as $current_grant => $current_grant_value) {
        $grant_type = substr($current_grant, 0, -5);
        if (in_array($grant_type, array('Select', 'Insert', 'Update', 'References'))
        ) {
            continue;
        }
        // make a substitution to match the messages variables;
        // also we must substitute the grant we get, because we can't generate
        // a form variable containing blanks (those would get changed to
        // an underscore when receiving the POST)
        if ($current_grant == 'Create View_priv') {
            $tmp_current_grant = 'CreateView_priv';
            $current_grant = 'Create_view_priv';
        } elseif ($current_grant == 'Show view_priv') {
            $tmp_current_grant = 'ShowView_priv';
            $current_grant = 'Show_view_priv';
        } else {
            $tmp_current_grant = $current_grant;
        }

        $html_output .= '<div class="item">' . "\n"
           . '<input type="checkbox"'
           . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
           . '" value="Y" '
           . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
           . 'title="';

        $html_output .= (isset($GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        (/*overload*/mb_strlen($tmp_current_grant) - 5)
                    )
                ] )
                ? $GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        (/*overload*/mb_strlen($tmp_current_grant) - 5)
                    )
                ]
                : $GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        (/*overload*/mb_strlen($tmp_current_grant) - 5)
                    ) . 'Tbl'
                ]
            )
            . '"/>' . "\n";

        $html_output .= '<label for="checkbox_' . $current_grant
            . '"><code><dfn title="'
            . (isset($GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        -5
                    )
                ])
                ? $GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        -5
                    )
                ]
                : $GLOBALS[
                    'strPrivDesc' . /*overload*/mb_substr(
                        $tmp_current_grant,
                        0,
                        -5
                    ) . 'Tbl'
                ]
            )
            . '">'
            . /*overload*/mb_strtoupper(
                /*overload*/mb_substr(
                    $current_grant,
                    0,
                    -5
                )
            )
            . '</dfn></code></label>' . "\n"
            . '</div>' . "\n";
    } // end foreach ()
    return $html_output;
}

/**
 * Get HTML for global or database specific privileges
 *
 * @param string $db    the database
 * @param string $table the table
 * @param string $row   first row from result or boolean false
 *
 * @return string $html_output
 */
function PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row)
{
    $privTable_names = array(0 => __('Data'),
        1 => __('Structure'),
        2 => __('Administration')
    );
    $privTable = array();
    // d a t a
    $privTable[0] = PMA_getDataPrivilegeTable($db);

    // s t r u c t u r e
    $privTable[1] = PMA_getStructurePrivilegeTable($table, $row);

    // a d m i n i s t r a t i o n
    $privTable[2] = PMA_getAdministrationPrivilegeTable($db);

    $html_output = '<input type="hidden" name="grant_count" value="'
        . (count($privTable[0])
            + count($privTable[1])
            + count($privTable[2])
            - (isset($row['Grant_priv']) ? 1 : 0)
        )
        . '" />';
    if ($db == '*') {
        $legend     = __('Global privileges');
        $menu_label = __('Global');
    } else if ($table == '*') {
        $legend     = __('Database-specific privileges');
        $menu_label = __('Database');
    } else {
        $legend     = __('Table-specific privileges');
        $menu_label = __('Table');
    }
    $html_output .= '<fieldset id="fieldset_user_global_rights">'
        . '<legend data-submenu-label="' . $menu_label . '">' . $legend
        . '<input type="checkbox" id="addUsersForm_checkall" '
        . 'class="checkall_box" title="' . __('Check All') . '" /> '
        . '<label for="addUsersForm_checkall">' . __('Check All') . '</label> '
        . '</legend>'
        . '<p><small><i>'
        . __('Note: MySQL privilege names are expressed in English.')
        . '</i></small></p>';

    // Output the Global privilege tables with checkboxes
    $html_output .= PMA_getHtmlForGlobalPrivTableWithCheckboxes(
        $privTable, $privTable_names, $row
    );

    // The "Resource limits" box is not displayed for db-specific privs
    if ($db == '*') {
        $html_output .= PMA_getHtmlForResourceLimits($row);
    }
    // for Safari 2.0.2
    $html_output .= '<div class="clearfloat"></div>';

    return $html_output;
}

/**
 * Get data privilege table as an array
 *
 * @param string $db the database
 *
 * @return string data privilege table
 */
function PMA_getDataPrivilegeTable($db)
{
    $data_privTable = array(
        array('Select', 'SELECT', __('Allows reading data.')),
        array('Insert', 'INSERT', __('Allows inserting and replacing data.')),
        array('Update', 'UPDATE', __('Allows changing data.')),
        array('Delete', 'DELETE', __('Allows deleting data.'))
    );
    if ($db == '*') {
        $data_privTable[]
            = array('File',
                'FILE',
                __('Allows importing data from and exporting data into files.')
            );
    }
    return $data_privTable;
}

/**
 * Get structure privilege table as an array
 *
 * @param string $table the table
 * @param array  $row   first row from result or boolean false
 *
 * @return string structure privilege table
 */
function PMA_getStructurePrivilegeTable($table, $row)
{
    $structure_privTable = array(
        array('Create',
            'CREATE',
            ($table == '*'
                ? __('Allows creating new databases and tables.')
                : __('Allows creating new tables.')
            )
        ),
        array('Alter',
            'ALTER',
            __('Allows altering the structure of existing tables.')
        ),
        array('Index', 'INDEX', __('Allows creating and dropping indexes.')),
        array('Drop',
            'DROP',
            ($table == '*'
                ? __('Allows dropping databases and tables.')
                : __('Allows dropping tables.')
            )
        ),
        array('Create_tmp_table',
            'CREATE TEMPORARY TABLES',
            __('Allows creating temporary tables.')
        ),
        array('Show_view',
            'SHOW VIEW',
            __('Allows performing SHOW CREATE VIEW queries.')
        ),
        array('Create_routine',
            'CREATE ROUTINE',
            __('Allows creating stored routines.')
        ),
        array('Alter_routine',
            'ALTER ROUTINE',
            __('Allows altering and dropping stored routines.')
        ),
        array('Execute', 'EXECUTE', __('Allows executing stored routines.')),
    );
    // this one is for a db-specific priv: Create_view_priv
    if (isset($row['Create_view_priv'])) {
        $structure_privTable[] = array('Create_view',
            'CREATE VIEW',
            __('Allows creating new views.')
        );
    }
    // this one is for a table-specific priv: Create View_priv
    if (isset($row['Create View_priv'])) {
        $structure_privTable[] = array('Create View',
            'CREATE VIEW',
            __('Allows creating new views.')
        );
    }
    if (isset($row['Event_priv'])) {
        // MySQL 5.1.6
        $structure_privTable[] = array('Event',
            'EVENT',
            __('Allows to set up events for the event scheduler.')
        );
        $structure_privTable[] = array('Trigger',
            'TRIGGER',
            __('Allows creating and dropping triggers.')
        );
    }
    return $structure_privTable;
}

/**
 * Get administration privilege table as an array
 *
 * @param string $db the table
 *
 * @return string administration privilege table
 */
function PMA_getAdministrationPrivilegeTable($db)
{
    $adminPrivTable = array(
        array('Grant',
            'GRANT',
            __(
                'Allows adding users and privileges '
                . 'without reloading the privilege tables.'
            )
        ),
    );
    if ($db == '*') {
        $adminPrivTable[] = array('Super',
            'SUPER',
            __(
                'Allows connecting, even if maximum number '
                . 'of connections is reached; required for '
                . 'most administrative operations like '
                . 'setting global variables or killing threads of other users.'
            )
        );
        $adminPrivTable[] = array('Process',
            'PROCESS',
            __('Allows viewing processes of all users.')
        );
        $adminPrivTable[] = array('Reload',
            'RELOAD',
            __('Allows reloading server settings and flushing the server\'s caches.')
        );
        $adminPrivTable[] = array('Shutdown',
            'SHUTDOWN',
            __('Allows shutting down the server.')
        );
        $adminPrivTable[] = array('Show_db',
            'SHOW DATABASES',
            __('Gives access to the complete list of databases.')
        );
    }
    $adminPrivTable[] = array('Lock_tables',
        'LOCK TABLES',
        __('Allows locking tables for the current thread.')
    );
    $adminPrivTable[] = array('References',
        'REFERENCES',
        __('Has no effect in this MySQL version.')
    );
    if ($db == '*') {
        $adminPrivTable[] = array('Repl_client',
            'REPLICATION CLIENT',
            __('Allows the user to ask where the slaves / masters are.')
        );
        $adminPrivTable[] = array('Repl_slave',
            'REPLICATION SLAVE',
            __('Needed for the replication slaves.')
        );
        $adminPrivTable[] = array('Create_user',
            'CREATE USER',
            __('Allows creating, dropping and renaming user accounts.')
        );
    }
    return $adminPrivTable;
}

/**
 * Get HTML snippet for global privileges table with check boxes
 *
 * @param array $privTable       privileges table array
 * @param array $privTable_names names of the privilege tables
 *                               (Data, Structure, Administration)
 * @param array $row             first row from result or boolean false
 *
 * @return string $html_output
 */
function PMA_getHtmlForGlobalPrivTableWithCheckboxes(
    $privTable, $privTable_names, $row
) {
    $html_output = '';
    foreach ($privTable as $i => $table) {
        $html_output .= '<fieldset>' . "\n"
            . '<legend>' . $privTable_names[$i] . '</legend>' . "\n";
        foreach ($table as $priv) {
            $html_output .= '<div class="item">' . "\n"
                . '<input type="checkbox" class="checkall"'
                . ' name="' . $priv[0] . '_priv" '
                . 'id="checkbox_' . $priv[0] . '_priv"'
                . ' value="Y" title="' . $priv[2] . '"'
                . ((isset($row[$priv[0] . '_priv'])
                    && $row[$priv[0] . '_priv'] == 'Y')
                    ?  ' checked="checked"'
                    : ''
                )
                . '/>' . "\n"
                . '<label for="checkbox_' . $priv[0] . '_priv">'
                . '<code>'
                . PMA_formatPrivilege($priv, true)
                . '</code></label>' . "\n"
                . '</div>' . "\n";
        }
        $html_output .= '</fieldset>' . "\n";
    }
    return $html_output;
}

/**
 * Displays the fields used by the "new user" form as well as the
 * "change login information / copy user" form.
 *
 * @param string $mode are we creating a new user or are we just
 *                     changing  one? (allowed values: 'new', 'change')
 *
 * @global  array      $cfg     the phpMyAdmin configuration
 * @global  resource   $user_link the database connection
 *
 * @return string $html_output  a HTML snippet
 */
function PMA_getHtmlForLoginInformationFields($mode = 'new')
{
    list($username_length, $hostname_length) = PMA_getUsernameAndHostnameLength();

    if (isset($GLOBALS['username'])
        && /*overload*/mb_strlen($GLOBALS['username']) === 0
    ) {
        $GLOBALS['pred_username'] = 'any';
    }
    $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
        . '<legend>' . __('Login Information') . '</legend>' . "\n"
        . '<div class="item">' . "\n"
        . '<label for="select_pred_username">' . "\n"
        . '    ' . __('User name:') . "\n"
        . '</label>' . "\n"
        . '<span class="options">' . "\n";

    $html_output .= '<select name="pred_username" id="select_pred_username" '
        . 'title="' . __('User name') . '"' . "\n";

    $html_output .= '        onchange="'
        . 'if (this.value == \'any\') {'
        . '    username.value = \'\'; '
        . '    user_exists_warning.style.display = \'none\'; '
        . '    username.required = false; '
        . '} else if (this.value == \'userdefined\') {'
        . '    username.focus(); username.select(); '
        . '    username.required = true; '
        . '}">' . "\n";

    $html_output .= '<option value="any"'
        . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any')
            ? ' selected="selected"'
            : '') . '>'
        . __('Any user')
        . '</option>' . "\n";

    $html_output .= '<option value="userdefined"'
        . ((! isset($GLOBALS['pred_username'])
                || $GLOBALS['pred_username'] == 'userdefined'
            )
            ? ' selected="selected"'
            : '') . '>'
        . __('Use text field')
        . ':</option>' . "\n";

    $html_output .= '</select>' . "\n"
        . '</span>' . "\n";

    $html_output .= '<input type="text" name="username" class="autofocus"'
        . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
        . (empty($GLOBALS['username'])
           ? ''
           : ' value="' . htmlspecialchars(
               isset($GLOBALS['new_username'])
               ? $GLOBALS['new_username']
               : $GLOBALS['username']
           ) . '"'
        )
        . ' onchange="pred_username.value = \'userdefined\'; this.required = true;" '
        . ((! isset($GLOBALS['pred_username'])
                || $GLOBALS['pred_username'] == 'userdefined'
            )
            ? 'required="required"'
            : '') . ' />' . "\n";

    $html_output .= '<div id="user_exists_warning"'
        . ' name="user_exists_warning" style="display:none;">'
        . PMA_Message::notice(
            __(
                'An account already exists with the same username '
                . 'but possibly a different hostname.'
            )
        )->getDisplay()
        . '</div>';
    $html_output .= '</div>';

    $html_output .= '<div class="item">' . "\n"
        . '<label for="select_pred_hostname">' . "\n"
        . '    ' . __('Host:') . "\n"
        . '</label>' . "\n";

    $html_output .= '<span class="options">' . "\n"
        . '    <select name="pred_hostname" id="select_pred_hostname" '
        . 'title="' . __('Host') . '"' . "\n";
    $_current_user = $GLOBALS['dbi']->fetchValue('SELECT USER();');
    if (! empty($_current_user)) {
        $thishost = str_replace(
            "'",
            '',
            /*overload*/mb_substr(
                $_current_user,
                (/*overload*/mb_strrpos($_current_user, '@') + 1)
            )
        );
        if ($thishost == 'localhost' || $thishost == '127.0.0.1') {
            unset($thishost);
        }
    }
    $html_output .= '    onchange="'
        . 'if (this.value == \'any\') { '
        . '     hostname.value = \'%\'; '
        . '} else if (this.value == \'localhost\') { '
        . '    hostname.value = \'localhost\'; '
        . '} '
        . (empty($thishost)
            ? ''
            : 'else if (this.value == \'thishost\') { '
            . '    hostname.value = \'' . addslashes(htmlspecialchars($thishost))
            . '\'; '
            . '} '
        )
        . 'else if (this.value == \'hosttable\') { '
        . '    hostname.value = \'\'; '
        . '    hostname.required = false; '
        . '} else if (this.value == \'userdefined\') {'
        . '    hostname.focus(); hostname.select(); '
        . '    hostname.required = true; '
        . '}">' . "\n";
    unset($_current_user);

    // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
    if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
        switch (/*overload*/mb_strtolower($GLOBALS['hostname'])) {
        case 'localhost':
        case '127.0.0.1':
            $GLOBALS['pred_hostname'] = 'localhost';
            break;
        case '%':
            $GLOBALS['pred_hostname'] = 'any';
            break;
        default:
            $GLOBALS['pred_hostname'] = 'userdefined';
            break;
        }
    }
    $html_output .=  '<option value="any"'
        . ((isset($GLOBALS['pred_hostname'])
                && $GLOBALS['pred_hostname'] == 'any'
            )
            ? ' selected="selected"'
            : '') . '>'
        . __('Any host')
        . '</option>' . "\n"
        . '<option value="localhost"'
        . ((isset($GLOBALS['pred_hostname'])
                && $GLOBALS['pred_hostname'] == 'localhost'
            )
            ? ' selected="selected"'
            : '') . '>'
        . __('Local')
        . '</option>' . "\n";
    if (! empty($thishost)) {
        $html_output .= '<option value="thishost"'
            . ((isset($GLOBALS['pred_hostname'])
                    && $GLOBALS['pred_hostname'] == 'thishost'
                )
                ? ' selected="selected"'
                : '') . '>'
            . __('This Host')
            . '</option>' . "\n";
    }
    unset($thishost);
    $html_output .= '<option value="hosttable"'
        . ((isset($GLOBALS['pred_hostname'])
                && $GLOBALS['pred_hostname'] == 'hosttable'
            )
            ? ' selected="selected"'
            : '') . '>'
        . __('Use Host Table')
        . '</option>' . "\n";

    $html_output .= '<option value="userdefined"'
        . ((isset($GLOBALS['pred_hostname'])
                && $GLOBALS['pred_hostname'] == 'userdefined'
            )
            ? ' selected="selected"'
            : '') . '>'
        . __('Use text field:') . '</option>' . "\n"
        . '</select>' . "\n"
        . '</span>' . "\n";

    $html_output .= '<input type="text" name="hostname" maxlength="'
        . $hostname_length . '" value="'
        // use default value of '%' to match with the default 'Any host'
        . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
        . '" title="' . __('Host')
        . '" onchange="pred_hostname.value = \'userdefined\'; this.required = true;" '
        . ((isset($GLOBALS['pred_hostname'])
                && $GLOBALS['pred_hostname'] == 'userdefined'
            )
            ? 'required="required"'
            : '')
        . ' />' . "\n"
        . PMA_Util::showHint(
            __(
                'When Host table is used, this field is ignored '
                . 'and values stored in Host table are used instead.'
            )
        )
        . '</div>' . "\n";

    $html_output .= '<div class="item">' . "\n"
        . '<label for="select_pred_password">' . "\n"
        . '    ' . __('Password:') . "\n"
        . '</label>' . "\n"
        . '<span class="options">' . "\n"
        . '<select name="pred_password" id="select_pred_password" title="'
        . __('Password') . '"' . "\n";

    $html_output .= '            onchange="'
        . 'if (this.value == \'none\') { '
        . '    pma_pw.value = \'\'; pma_pw2.value = \'\'; '
        . '    pma_pw.required = false; pma_pw2.required = false; '
        . '} else if (this.value == \'userdefined\') { '
        . '    pma_pw.focus(); pma_pw.select(); '
        . '    pma_pw.required = true; pma_pw2.required = true; '
        . '} else { '
        . '    pma_pw.required = false; pma_pw2.required = false; '
        . '}">' . "\n"
        . ($mode == 'change' ? '<option value="keep" selected="selected">'
            . __('Do not change the password')
            . '</option>' . "\n" : '')
        . '<option value="none"';

    if (isset($GLOBALS['username']) && $mode != 'change') {
        $html_output .= '  selected="selected"';
    }
    $html_output .= '>' . __('No Password') . '</option>' . "\n"
        . '<option value="userdefined"'
        . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
        . __('Use text field')
        . ':</option>' . "\n"
        . '</select>' . "\n"
        . '</span>' . "\n"
        . '<input type="password" id="text_pma_pw" name="pma_pw" '
        . 'title="' . __('Password') . '" '
        . 'onchange="pred_password.value = \'userdefined\'; this.required = true; pma_pw2.required = true;" '
        . (isset($GLOBALS['username']) ? '' : 'required="required"')
        . '/>' . "\n"
        . '</div>' . "\n";

    $html_output .= '<div class="item" '
        . 'id="div_element_before_generate_password">' . "\n"
        . '<label for="text_pma_pw2">' . "\n"
        . '    ' . __('Re-type:') . "\n"
        . '</label>' . "\n"
        . '<span class="options">&nbsp;</span>' . "\n"
        . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
        . 'title="' . __('Re-type') . '" '
        . 'onchange="pred_password.value = \'userdefined\'; this.required = true; pma_pw.required = true;" '
        . (isset($GLOBALS['username']) ? '' : 'required="required"')
        . '/>' . "\n"
        . '</div>' . "\n"
       // Generate password added here via jQuery
       . '</fieldset>' . "\n";

    return $html_output;
} // end of the 'PMA_displayUserAndHostFields()' function

/**
 * Get username and hostname length
 *
 * @return array username length and hostname length
 */
function PMA_getUsernameAndHostnameLength()
{
    /* Fallback values */
    $username_length = 16;
    $hostname_length = 41;

    /* Try to get real lengths from the database */
    $fields_info = $GLOBALS['dbi']->fetchResult(
        'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
        . 'FROM information_schema.columns '
        . "WHERE table_schema = 'mysql' AND table_name = 'user' "
        . "AND COLUMN_NAME IN ('User', 'Host')"
    );
    foreach ($fields_info as $val) {
        if ($val['COLUMN_NAME'] == 'User') {
            $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
        } elseif ($val['COLUMN_NAME'] == 'Host') {
            $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
        }
    }
    return array($username_length, $hostname_length);
}

/**
 * Returns all the grants for a certain user on a certain host
 * Used in the export privileges for all users section
 *
 * @param string $user User name
 * @param string $host Host name
 *
 * @return string containing all the grants text
 */
function PMA_getGrants($user, $host)
{
    $grants = $GLOBALS['dbi']->fetchResult(
        "SHOW GRANTS FOR '"
        . PMA_Util::sqlAddSlashes($user) . "'@'"
        . PMA_Util::sqlAddSlashes($host) . "'"
    );
    $response = '';
    foreach ($grants as $one_grant) {
        $response .= $one_grant . ";\n\n";
    }
    return $response;
} // end of the 'PMA_getGrants()' function

/**
 * Update password and get message for password updating
 *
 * @param string $err_url  error url
 * @param string $username username
 * @param string $hostname hostname
 *
 * @return string $message  success or error message after updating password
 */
function PMA_updatePassword($err_url, $username, $hostname)
{
    // similar logic in user_password.php
    $message = '';

    if (empty($_REQUEST['nopass'])
        && isset($_POST['pma_pw'])
        && isset($_POST['pma_pw2'])
    ) {
        if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
            $message = PMA_Message::error(__('The passwords aren\'t the same!'));
        } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
            $message = PMA_Message::error(__('The password is empty!'));
        }
    }

    // here $nopass could be == 1
    if (empty($message)) {

        $hashing_function
            = (! empty($_REQUEST['pw_hash']) && $_REQUEST['pw_hash'] == 'old'
                ? 'OLD_'
                : ''
            )
            . 'PASSWORD';

        // in $sql_query which will be displayed, hide the password
        $sql_query        = 'SET PASSWORD FOR \''
            . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
            . (($_POST['pma_pw'] == '')
                ? '\'\''
                : $hashing_function . '(\''
                . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');

        $local_query      = 'SET PASSWORD FOR \''
            . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
            . (($_POST['pma_pw'] == '') ? '\'\'' : $hashing_function
            . '(\'' . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\')');

        $GLOBALS['dbi']->tryQuery($local_query)
            or PMA_Util::mysqlDie(
                $GLOBALS['dbi']->getError(), $sql_query, false, $err_url
            );
        $message = PMA_Message::success(
            __('The password for %s was changed successfully.')
        );
        $message->addParam(
            '\'' . htmlspecialchars($username)
            . '\'@\'' . htmlspecialchars($hostname) . '\''
        );
    }
    return $message;
}

/**
 * Revokes privileges and get message and SQL query for privileges revokes
 *
 * @param string $dbname    database name
 * @param string $tablename table name
 * @param string $username  username
 * @param string $hostname  host name
 *
 * @return array ($message, $sql_query)
 */
function PMA_getMessageAndSqlQueryForPrivilegesRevoke($dbname,
    $tablename, $username, $hostname
) {
    $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);

    $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
        . ' FROM \''
        . PMA_Util::sqlAddSlashes($username) . '\'@\''
        . PMA_Util::sqlAddSlashes($hostname) . '\';';

    $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
        . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
        . PMA_Util::sqlAddSlashes($hostname) . '\';';

    $GLOBALS['dbi']->query($sql_query0);
    if (! $GLOBALS['dbi']->tryQuery($sql_query1)) {
        // this one may fail, too...
        $sql_query1 = '';
    }
    $sql_query = $sql_query0 . ' ' . $sql_query1;
    $message = PMA_Message::success(
        __('You have revoked the privileges for %s.')
    );
    $message->addParam(
        '\'' . htmlspecialchars($username)
        . '\'@\'' . htmlspecialchars($hostname) . '\''
    );

    return array($message, $sql_query);
}

/**
 * Get a WITH clause for 'update privileges' and 'add user'
 *
 * @return string $sql_query
 */
function PMA_getWithClauseForAddUserAndUpdatePrivs()
{
    $sql_query = '';
    if (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y') {
        $sql_query .= ' GRANT OPTION';
    }
    if (isset($_POST['max_questions'])) {
        $max_questions = max(0, (int)$_POST['max_questions']);
        $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
    }
    if (isset($_POST['max_connections'])) {
        $max_connections = max(0, (int)$_POST['max_connections']);
        $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
    }
    if (isset($_POST['max_updates'])) {
        $max_updates = max(0, (int)$_POST['max_updates']);
        $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
    }
    if (isset($_POST['max_user_connections'])) {
        $max_user_connections = max(0, (int)$_POST['max_user_connections']);
        $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
    }
    return ((!empty($sql_query)) ? 'WITH' . $sql_query : '');
}

/**
 * Get HTML for addUsersForm, This function call if isset($_REQUEST['adduser'])
 *
 * @param string $dbname database name
 *
 * @return string HTML for addUserForm
 */
function PMA_getHtmlForAddUser($dbname)
{
    $html_output = '<h2>' . "\n"
       . PMA_Util::getIcon('b_usradd.png') . __('Add user') . "\n"
       . '</h2>' . "\n"
       . '<form name="usersForm" id="addUsersForm"'
       . ' onsubmit="return checkAddUser(this);"'
       . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
       . PMA_URL_getHiddenInputs('', '')
       . PMA_getHtmlForLoginInformationFields('new');

    $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
        . '<legend>' . __('Database for user') . '</legend>' . "\n";

    $html_output .= PMA_Util::getCheckbox(
        'createdb-1',
        __('Create database with same name and grant all privileges.'),
        false, false
    );
    $html_output .= '<br />' . "\n";
    $html_output .= PMA_Util::getCheckbox(
        'createdb-2',
        __('Grant all privileges on wildcard name (username\\_%).'),
        false, false
    );
    $html_output .= '<br />' . "\n";

    if (! empty($dbname) ) {
        $html_output .= PMA_Util::getCheckbox(
            'createdb-3',
            sprintf(
                __('Grant all privileges on database "%s".'),
                htmlspecialchars($dbname)
            ),
            true,
            false
        );
        $html_output .= '<input type="hidden" name="dbname" value="'
            . htmlspecialchars($dbname) . '" />' . "\n";
        $html_output .= '<br />' . "\n";
    }

    $html_output .= '</fieldset>' . "\n";
    if ($GLOBALS['is_grantuser']) {
        $html_output .= PMA_getHtmlToDisplayPrivilegesTable('*', '*', false);
    }
    $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
        . "\n"
        . '<input type="hidden" name="adduser_submit" value="1" />' . "\n"
        . '<input type="submit" id="adduser_submit" value="' . __('Go') . '" />'
        . "\n"
        . '</fieldset>' . "\n"
        . '</form>' . "\n";

    return $html_output;
}

/**
 * Get the list of privileges and list of compared privileges as strings
 * and return a array that contains both strings
 *
 * @return array $list_of_privileges, $list_of_compared_privileges
 */
function PMA_getListOfPrivilegesAndComparedPrivileges()
{
    $list_of_privileges
        = '`User`, '
        . '`Host`, '
        . '`Select_priv`, '
        . '`Insert_priv`, '
        . '`Update_priv`, '
        . '`Delete_priv`, '
        . '`Create_priv`, '
        . '`Drop_priv`, '
        . '`Grant_priv`, '
        . '`Index_priv`, '
        . '`Alter_priv`, '
        . '`References_priv`, '
        . '`Create_tmp_table_priv`, '
        . '`Lock_tables_priv`, '
        . '`Create_view_priv`, '
        . '`Show_view_priv`, '
        . '`Create_routine_priv`, '
        . '`Alter_routine_priv`, '
        . '`Execute_priv`';

    $listOfComparedPrivs
        = '`Select_priv` = \'N\''
        . ' AND `Insert_priv` = \'N\''
        . ' AND `Update_priv` = \'N\''
        . ' AND `Delete_priv` = \'N\''
        . ' AND `Create_priv` = \'N\''
        . ' AND `Drop_priv` = \'N\''
        . ' AND `Grant_priv` = \'N\''
        . ' AND `References_priv` = \'N\''
        . ' AND `Create_tmp_table_priv` = \'N\''
        . ' AND `Lock_tables_priv` = \'N\''
        . ' AND `Create_view_priv` = \'N\''
        . ' AND `Show_view_priv` = \'N\''
        . ' AND `Create_routine_priv` = \'N\''
        . ' AND `Alter_routine_priv` = \'N\''
        . ' AND `Execute_priv` = \'N\'';

    $list_of_privileges .=
        ', `Event_priv`, '
        . '`Trigger_priv`';
    $listOfComparedPrivs .=
        ' AND `Event_priv` = \'N\''
        . ' AND `Trigger_priv` = \'N\'';
    return array($list_of_privileges, $listOfComparedPrivs);
}

/**
 * Get the HTML for user form and check the privileges for a particular database.
 *
 * @param string $db database name
 *
 * @return string $html_output
 */
function PMA_getHtmlForSpecificDbPrivileges($db)
{
    $html_output = '';
    if ($GLOBALS['is_superuser']) {
        // check the privileges for a particular database.
        $html_output = '<form id="usersForm" action="server_privileges.php">'
            . '<fieldset>' . "\n";
        $html_output .= '<legend>' . "\n"
            . PMA_Util::getIcon('b_usrcheck.png')
            . '    '
            . sprintf(
                __('Users having access to "%s"'),
                '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase']
                . PMA_URL_getCommon(array('db' => $db)) . '">'
                .  htmlspecialchars($db)
                . '</a>'
            )
            . "\n"
            . '</legend>' . "\n";

        $html_output .= '<table id="dbspecificuserrights" class="data">';
        $html_output .= PMA_getHtmlForPrivsTableHead();
        $privMap = PMA_getPrivMap($db);
        $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
        $html_output .= '</table>'
            . '</fieldset>'
            . '</form>' . "\n";
    } else {
        $html_output .= PMA_getHtmlForViewUsersError();
    }

    if ($GLOBALS['is_ajax_request'] == true
        && empty($_REQUEST['ajax_page_request'])
    ) {
        $message = PMA_Message::success(__('User has been added.'));
        $response = PMA_Response::getInstance();
        $response->addJSON('message', $message);
        $response->addJSON('user_form', $html_output);
        exit;
    } else {
        // Offer to create a new user for the current database
        $html_output .= PMA_getAddUserHtmlFieldset($db);
    }
    return $html_output;
}

/**
 * Get the HTML for user form and check the privileges for a particular table.
 *
 * @param string $db    database name
 * @param string $table table name
 *
 * @return string $html_output
 */
function PMA_getHtmlForSpecificTablePrivileges($db, $table)
{
    $html_output = '';
    if ($GLOBALS['is_superuser']) {
        // check the privileges for a particular table.
        $html_output  = '<form id="usersForm" action="server_privileges.php">';
        $html_output .= '<fieldset>';
        $html_output .= '<legend>'
            . PMA_Util::getIcon('b_usrcheck.png')
            . sprintf(
                __('Users having access to "%s"'),
                '<a href="' . $GLOBALS['cfg']['DefaultTabTable']
                . PMA_URL_getCommon(
                    array(
                        'db' => $db,
                        'table' => $table,
                    )
                ) . '">'
                .  htmlspecialchars($db) . '.' . htmlspecialchars($table)
                . '</a>'
            )
            . '</legend>';

        $html_output .= '<table id="tablespecificuserrights" class="data">';
        $html_output .= PMA_getHtmlForPrivsTableHead();
        $privMap = PMA_getPrivMap($db);
        $sql_query = "SELECT `User`, `Host`, `Db`,"
            . " 't' AS `Type`, `Table_name`, `Table_priv`"
            . " FROM `mysql`.`tables_priv`"
            . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
            . "     AND '" . PMA_Util::sqlAddSlashes($table) . "' LIKE `Table_name`"
            . "     AND NOT (`Table_priv` = '' AND Column_priv = '')"
            . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
        $res = $GLOBALS['dbi']->query($sql_query);
        PMA_mergePrivMapFromResult($privMap, $res);
        $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
        $html_output .= '</table>';
        $html_output .= '</fieldset>';
        $html_output .= '</form>';
    } else {
        $html_output .= PMA_getHtmlForViewUsersError();
    }
    // Offer to create a new user for the current database
    $html_output .= PMA_getAddUserHtmlFieldset($db, $table);
    return $html_output;
}

/**
 * gets privilege map
 *
 * @param string $db the database
 *
 * @return array $privMap the privilege map
 */
function PMA_getPrivMap($db)
{
    list($listOfPrivs, $listOfComparedPrivs)
        = PMA_getListOfPrivilegesAndComparedPrivileges();
    $sql_query
        = "("
        . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
        . " FROM `mysql`.`user`"
        . " WHERE NOT (" . $listOfComparedPrivs . ")"
        . ")"
        . " UNION "
        . "("
        . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
        . " FROM `mysql`.`db`"
        . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
        . "     AND NOT (" . $listOfComparedPrivs . ")"
        . ")"
        . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
    $res = $GLOBALS['dbi']->query($sql_query);
    $privMap = array();
    PMA_mergePrivMapFromResult($privMap, $res);
    return $privMap;
}

/**
 * merge privilege map and rows from resultset
 *
 * @param array  &$privMap the privilege map reference
 * @param object $result   the resultset of query
 *
 * @return void
 */
function PMA_mergePrivMapFromResult(&$privMap, $result)
{
    while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
        $user = $row['User'];
        $host = $row['Host'];
        if (! isset($privMap[$user])) {
            $privMap[$user] = array();
        }
        if (! isset($privMap[$user][$host])) {
            $privMap[$user][$host] = array();
        }
        $privMap[$user][$host][] = $row;
    }
}

/**
 * Get HTML snippet for privileges table head
 *
 * @return string $html_output
 */
function PMA_getHtmlForPrivsTableHead()
{
    return '<thead>'
        . '<tr><th>' . __('User') . '</th>'
        . '<th>' . __('Host') . '</th>'
        . '<th>' . __('Type') . '</th>'
        . '<th>' . __('Privileges') . '</th>'
        . '<th>' . __('Grant') . '</th>'
        . '<th>' . __('Action') . '</th>'
        . '</tr>'
        . '</thead>';
}

/**
 * Get HTML error for View Users form
 * For non superusers such as grant/create users
 *
 * @return string $html_output
 */
function PMA_getHtmlForViewUsersError()
{
    return PMA_Message::error(
        __('Not enough privilege to view users.')
    )->getDisplay();
}

/**
 * Get HTML snippet for table body of specific database or table privileges
 *
 * @param array  $privMap privilege map
 * @param string $db      database
 *
 * @return string $html_output
 */
function PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
{
    $html_output = '<tbody>';
    $odd_row = true;
    if (empty($privMap)) {
        $html_output .= '<tr class="odd">'
            . '<td colspan="6">'
            . __('No user found.')
            . '</td>'
            . '</tr>'
            . '</tbody>';
        return $html_output;
    }

    foreach ($privMap as $current_user => $val) {
        foreach ($val as $current_host => $current_privileges) {
            $nbPrivileges = count($current_privileges);
            $html_output .= '<tr class="noclick '
                . ($odd_row ? 'odd' : 'even') . '">';

            // user
            $html_output .= '<td';
            if ($nbPrivileges > 1) {
                $html_output .= ' rowspan="' . $nbPrivileges . '"';
            }
            $html_output .= '>';
            if (empty($current_user)) {
                $html_output .= '<span style="color: #FF0000">'
                    . __('Any') . '</span>';
            } else {
                $html_output .= htmlspecialchars($current_user);
            }
            $html_output .= '</td>';

            // host
            $html_output .= '<td';
            if ($nbPrivileges > 1) {
                $html_output .= ' rowspan="' . $nbPrivileges . '"';
            }
            $html_output .= '>';
            $html_output .= htmlspecialchars($current_host);
            $html_output .= '</td>';

            $html_output .= PMA_getHtmlListOfPrivs(
                $db, $current_privileges, $current_user,
                $current_host, $odd_row
            );

            $odd_row = ! $odd_row;
        }
    }
    $html_output .= '</tbody>';

    return $html_output;
}

/**
 * Get HTML to display privileges
 *
 * @param string  $db                 Database name
 * @param array   $current_privileges List of privileges
 * @param string  $current_user       Current user
 * @param string  $current_host       Current host
 * @param boolean $odd_row            Current row is odd
 *
 * @return string HTML to display privileges
 */
function PMA_getHtmlListOfPrivs(
    $db, $current_privileges, $current_user,
    $current_host, $odd_row
) {
    $nbPrivileges = count($current_privileges);
    $html_output = null;
    for ($i = 0; $i < $nbPrivileges; $i++) {
        $current = $current_privileges[$i];

        // type
        $html_output .= '<td>';
        if ($current['Type'] == 'g') {
            $html_output .= __('global');
        } elseif ($current['Type'] == 'd') {
            if ($current['Db'] == PMA_Util::escapeMysqlWildcards($db)) {
                $html_output .= __('database-specific');
            } else {
                $html_output .= __('wildcard') . ': '
                    . '<code>'
                    . htmlspecialchars($current['Db'])
                    . '</code>';
            }
        } elseif ($current['Type'] == 't') {
            $html_output .= __('table-specific');
        }
        $html_output .= '</td>';

        // privileges
        $html_output .= '<td>';
        if (isset($current['Table_name'])) {
            $privList = explode(',', $current['Table_priv']);
            $privs = array();
            $grantsArr = PMA_getTableGrantsArray();
            foreach ($grantsArr as $grant) {
                $privs[$grant[0]] = 'N';
                foreach ($privList as $priv) {
                    if ($grant[0] == $priv) {
                        $privs[$grant[0]] = 'Y';
                    }
                }
            }
            $html_output .= '<code>'
                . join(
                    ',',
                    PMA_extractPrivInfo($privs, true, true)
                )
                . '</code>';
        } else {
            $html_output .= '<code>'
                . join(
                    ',',
                    PMA_extractPrivInfo($current, true, false)
                )
                . '</code>';
        }
        $html_output .= '</td>';

        // grant
        $html_output .= '<td>';
        $containsGrant = false;
        if (isset($current['Table_name'])) {
            $privList = explode(',', $current['Table_priv']);
            foreach ($privList as $priv) {
                if ($priv == 'Grant') {
                    $containsGrant = true;
                }
            }
        } else {
            $containsGrant = $current['Grant_priv'] == 'Y';
        }
        $html_output .= ($containsGrant ? __('Yes') : __('No'));
        $html_output .= '</td>';

        // action
        $html_output .= '<td>';
        $specific_db = (isset($current['Db']) && $current['Db'] != '*')
            ? $current['Db'] : '';
        $specific_table = (isset($current['Table_name'])
            && $current['Table_name'] != '*')
            ? $current['Table_name'] : '';
        $html_output .= PMA_getUserLink(
            'edit',
            $current_user,
            $current_host,
            $specific_db,
            $specific_table
        );
        $html_output .= '</td>';

        $html_output .= '</tr>';
        if (($i + 1) < $nbPrivileges) {
            $html_output .= '<tr class="noclick '
                . ($odd_row ? 'odd' : 'even') . '">';
        }
    }
    return $html_output;
}

/**
 * Returns edit, revoke or export link for a user.
 *
 * @param string $linktype  The link type (edit | revoke | export)
 * @param string $username  User name
 * @param string $hostname  Host name
 * @param string $dbname    Database name
 * @param string $tablename Table name
 * @param string $initial   Initial value
 *
 * @return string HTML code with link
 */
function PMA_getUserLink(
    $linktype, $username, $hostname, $dbname = '', $tablename = '', $initial = ''
) {
    $html = '<a';
    switch($linktype) {
    case 'edit':
        $html .= ' class="edit_user_anchor"';
        break;
    case 'export':
        $html .= ' class="export_user_anchor ajax"';
        break;
    }
    $params = array(
        'username' => $username,
        'hostname' => $hostname
    );
    switch($linktype) {
    case 'edit':
        $params['dbname'] = $dbname;
        $params['tablename'] = $tablename;
        break;
    case 'revoke':
        $params['dbname'] = $dbname;
        $params['tablename'] = $tablename;
        $params['revokeall'] = 1;
        break;
    case 'export':
        $params['initial'] = $initial;
        $params['export'] = 1;
        break;
    }

    $html .= ' href="server_privileges.php'
        . PMA_URL_getCommon($params)
        . '">';

    switch($linktype) {
    case 'edit':
        $html .= PMA_Util::getIcon('b_usredit.png', __('Edit Privileges'));
        break;
    case 'revoke':
        $html .= PMA_Util::getIcon('b_usrdrop.png', __('Revoke'));
        break;
    case 'export':
        $html .= PMA_Util::getIcon('b_tblexport.png', __('Export'));
        break;
    }
    $html . '</a>';

    return $html;
}

/**
 * Returns user group edit link
 *
 * @param string $username User name
 *
 * @return HTML code with link
 */
function PMA_getUserGroupEditLink($username)
{
     return '<a class="edit_user_group_anchor ajax"'
        . ' href="server_privileges.php'
        . PMA_URL_getCommon(array('username' => $username))
        . '">'
        . PMA_Util::getIcon('b_usrlist.png', __('Edit user group'))
        . '</a>';
}

/**
 * Returns number of defined user groups
 *
 * @return integer $user_group_count
 */
function PMA_getUserGroupCount()
{
    $cfgRelation = PMA_getRelationsParam();
    $user_group_table = PMA_Util::backquote($cfgRelation['db'])
        . '.' . PMA_Util::backquote($cfgRelation['usergroups']);
    $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
    $user_group_count = $GLOBALS['dbi']->fetchValue(
        $sql_query, 0, 0, $GLOBALS['controllink']
    );

    return $user_group_count;
}

/**
 * This function return the extra data array for the ajax behavior
 *
 * @param string $password  password
 * @param string $sql_query sql query
 * @param string $hostname  hostname
 * @param string $username  username
 *
 * @return array $extra_data
 */
function PMA_getExtraDataForAjaxBehavior(
    $password, $sql_query, $hostname, $username
) {
    if (isset($GLOBALS['dbname'])) {
        //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
        if (preg_match('/(?<!\\\\)(?:_|%)/i', $GLOBALS['dbname'])) {
            $dbname_is_wildcard = true;
        } else {
            $dbname_is_wildcard = false;
        }
    }

    $user_group_count = 0;
    if ($GLOBALS['cfgRelation']['menuswork']) {
        $user_group_count = PMA_getUserGroupCount();
    }

    $extra_data = array();
    if (/*overload*/mb_strlen($sql_query)) {
        $extra_data['sql_query'] = PMA_Util::getMessage(null, $sql_query);
    }

    if (isset($_REQUEST['change_copy'])) {
        /**
         * generate html on the fly for the new user that was just created.
         */
        $new_user_string = '<tr>' . "\n"
            . '<td> <input type="checkbox" name="selected_usr[]" '
            . 'id="checkbox_sel_users_"'
            . 'value="'
            . htmlspecialchars($username)
            . '&amp;#27;' . htmlspecialchars($hostname) . '" />'
            . '</td>' . "\n"
            . '<td><label for="checkbox_sel_users_">'
            . (empty($_REQUEST['username'])
                    ? '<span style="color: #FF0000">' . __('Any') . '</span>'
                    : htmlspecialchars($username) ) . '</label></td>' . "\n"
            . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";

        $new_user_string .= '<td>';

        if (! empty($password) || isset($_POST['pma_pw'])) {
            $new_user_string .= __('Yes');
        } else {
            $new_user_string .= '<span style="color: #FF0000">'
                . __('No')
            . '</span>';
        };

        $new_user_string .= '</td>' . "\n";
        $new_user_string .= '<td>'
            . '<code>' . join(', ', PMA_extractPrivInfo(null, true)) . '</code>'
            . '</td>'; //Fill in privileges here

        // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
        // enabled
        $cfgRelation = PMA_getRelationsParam();
        if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
            $new_user_string .= '<td class="usrGroup"></td>';
        }

        $new_user_string .= '<td>';

        if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')) {
            $new_user_string .= __('Yes');
        } else {
            $new_user_string .= __('No');
        }

        $new_user_string .='</td>';

        $new_user_string .= '<td>'
            . PMA_getUserLink('edit', $username, $hostname)
            . '</td>' . "\n";

        if (isset($cfgRelation['menuswork']) && $user_group_count > 0) {
            $new_user_string .= '<td>'
                . PMA_getUserGroupEditLink($username)
                . '</td>' . "\n";
        }

        $new_user_string .= '<td>'
            . PMA_getUserLink(
                'export',
                $username,
                $hostname,
                '',
                '',
                isset($_GET['initial']) ? $_GET['initial'] : ''
            )
            . '</td>' . "\n";

        $new_user_string .= '</tr>';

        $extra_data['new_user_string'] = $new_user_string;

        /**
         * Generate the string for this alphabet's initial, to update the user
         * pagination
         */
        $new_user_initial = /*overload*/mb_strtoupper(
            /*overload*/mb_substr($username, 0, 1)
        );
        $newUserInitialString = '<a href="server_privileges.php'
            . PMA_URL_getCommon(array('initial' => $new_user_initial)) . '">'
            . $new_user_initial . '</a>';
        $extra_data['new_user_initial'] = $new_user_initial;
        $extra_data['new_user_initial_string'] = $newUserInitialString;
    }

    if (isset($_POST['update_privs'])) {
        $extra_data['db_specific_privs'] = false;
        $extra_data['db_wildcard_privs'] = false;
        if (isset($dbname_is_wildcard)) {
            $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
            $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
        }
        $new_privileges = join(', ', PMA_extractPrivInfo(null, true));

        $extra_data['new_privileges'] = $new_privileges;
    }

    if (isset($_REQUEST['validate_username'])) {
        $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
            . $_REQUEST['username'] . "';";
        $res = $GLOBALS['dbi']->query($sql_query);
        $row = $GLOBALS['dbi']->fetchRow($res);
        if (empty($row)) {
            $extra_data['user_exists'] = false;
        } else {
            $extra_data['user_exists'] = true;
        }
    }

    return $extra_data;
}

/**
 * Get the HTML snippet for change user login information
 *
 * @param string $username username
 * @param string $hostname host name
 *
 * @return string HTML snippet
 */
function PMA_getChangeLoginInformationHtmlForm($username, $hostname)
{
    $choices = array(
        '4' => __('… keep the old one.'),
        '1' => __('… delete the old one from the user tables.'),
        '2' => __(
            '… revoke all active privileges from '
            . 'the old one and delete it afterwards.'
        ),
        '3' => __(
            '… delete the old one from the user tables '
            . 'and reload the privileges afterwards.'
        )
    );

    $html_output = '<form action="server_privileges.php" '
        . 'onsubmit="return checkAddUser(this);" '
        . 'method="post" class="copyUserForm submenu-item">' . "\n"
        . PMA_URL_getHiddenInputs('', '')
        . '<input type="hidden" name="old_username" '
        . 'value="' . htmlspecialchars($username) . '" />' . "\n"
        . '<input type="hidden" name="old_hostname" '
        . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
        . '<fieldset id="fieldset_change_copy_user">' . "\n"
        . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
        . __('Change Login Information / Copy User')
        . '</legend>' . "\n"
        . PMA_getHtmlForLoginInformationFields('change');

    $html_output .= '<fieldset id="fieldset_mode">' . "\n"
        . ' <legend>'
        . __('Create a new user with the same privileges and …')
        . '</legend>' . "\n";
    $html_output .= PMA_Util::getRadioFields(
        'mode', $choices, '4', true
    );
    $html_output .= '</fieldset>' . "\n"
       . '</fieldset>' . "\n";

    $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
        . 'class="tblFooters">' . "\n"
        . '<input type="hidden" name="change_copy" value="1" />' . "\n"
        . '<input type="submit" value="' . __('Go') . '" />' . "\n"
        . '</fieldset>' . "\n"
        . '</form>' . "\n";

    return $html_output;
}

/**
 * Provide a line with links to the relevant database and table
 *
 * @param string $url_dbname url database name that urlencode() string
 * @param string $dbname     database name
 * @param string $tablename  table name
 *
 * @return string HTML snippet
 */
function PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename)
{
    $html_output = '[ ' . __('Database')
        . ' <a href="' . $GLOBALS['cfg']['DefaultTabDatabase']
        . PMA_URL_getCommon(
            array(
                'db' => $url_dbname,
                'reload' => 1
            )
        )
        . '">'
        . htmlspecialchars($dbname) . ': '
        . PMA_Util::getTitleForTarget(
            $GLOBALS['cfg']['DefaultTabDatabase']
        )
        . "</a> ]\n";

    if (/*overload*/mb_strlen($tablename)) {
        $html_output .= ' [ ' . __('Table') . ' <a href="'
            . $GLOBALS['cfg']['DefaultTabTable']
            . PMA_URL_getCommon(
                array(
                    'db' => $url_dbname,
                    'table' => $tablename,
                    'reload' => 1,
                )
            )
            . '">' . htmlspecialchars($tablename) . ': '
            . PMA_Util::getTitleForTarget(
                $GLOBALS['cfg']['DefaultTabTable']
            )
            . "</a> ]\n";
    }
    return $html_output;
}

/**
 * no db name given, so we want all privs for the given user
 * db name was given, so we want all user specific rights for this db
 * So this function returns user rights as an array
 *
 * @param array  $tables              tables
 * @param string $user_host_condition a where clause that contained user's host
 *                                    condition
 * @param string $dbname              database name
 *
 * @return array $db_rights database rights
 */
function PMA_getUserSpecificRights($tables, $user_host_condition, $dbname)
{
    if (!/*overload*/mb_strlen($dbname)) {
        $tables_to_search_for_users = array(
            'tables_priv', 'columns_priv',
        );
        $dbOrTableName = 'Db';
    } else {
        $user_host_condition .=
            ' AND `Db`'
            . ' LIKE \''
            . PMA_Util::sqlAddSlashes($dbname, true) . "'";
        $tables_to_search_for_users = array('columns_priv',);
        $dbOrTableName = 'Table_name';
    }

    $db_rights_sqls = array();
    foreach ($tables_to_search_for_users as $table_search_in) {
        if (in_array($table_search_in, $tables)) {
            $db_rights_sqls[] = '
                SELECT DISTINCT `' . $dbOrTableName . '`
                FROM `mysql`.' . PMA_Util::backquote($table_search_in)
               . $user_host_condition;
        }
    }

    $user_defaults = array(
        $dbOrTableName  => '',
        'Grant_priv'    => 'N',
        'privs'         => array('USAGE'),
        'Column_priv'   => true,
    );

    // for the rights
    $db_rights = array();

    $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
        . ' ORDER BY `' . $dbOrTableName . '` ASC';

    $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);

    while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
        $db_rights_row = array_merge($user_defaults, $db_rights_row);
        if (!/*overload*/mb_strlen($dbname)) {
            // only Db names in the table `mysql`.`db` uses wildcards
            // as we are in the db specific rights display we want
            // all db names escaped, also from other sources
            $db_rights_row['Db'] = PMA_Util::escapeMysqlWildcards(
                $db_rights_row['Db']
            );
        }
        $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
    }

    $GLOBALS['dbi']->freeResult($db_rights_result);

    if (!/*overload*/mb_strlen($dbname)) {
        $sql_query = 'SELECT * FROM `mysql`.`db`'
            . $user_host_condition . ' ORDER BY `Db` ASC';
    } else {
        $sql_query = 'SELECT `Table_name`,'
            . ' `Table_priv`,'
            . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
            . ' AS \'Column_priv\''
            . ' FROM `mysql`.`tables_priv`'
            . $user_host_condition
            . ' ORDER BY `Table_name` ASC;';
    }

    $result = $GLOBALS['dbi']->query($sql_query);

    while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
        if (isset($db_rights[$row[$dbOrTableName]])) {
            $db_rights[$row[$dbOrTableName]]
                = array_merge($db_rights[$row[$dbOrTableName]], $row);
        } else {
            $db_rights[$row[$dbOrTableName]] = $row;
        }
        if (!/*overload*/mb_strlen($dbname)) {
            // there are db specific rights for this user
            // so we can drop this db rights
            $db_rights[$row['Db']]['can_delete'] = true;
        }
    }
    $GLOBALS['dbi']->freeResult($result);
    return $db_rights;
}

/**
 * Display user rights in table rows(Table specific or database specific privs)
 *
 * @param array  $db_rights user's database rights array
 * @param string $dbname    database name
 * @param string $hostname  host name
 * @param string $username  username
 *
 * @return array $found_rows, $html_output
 */
function PMA_getHtmlForUserRights($db_rights, $dbname,
    $hostname, $username
) {
    $html_output = '';
    $found_rows = array();
    // display rows
    if (count($db_rights) < 1) {
        $html_output .= '<tr class="odd">' . "\n"
           . '<td colspan="6"><center><i>' . __('None') . '</i></center></td>' . "\n"
           . '</tr>' . "\n";
    } else {
        $odd_row = true;
        //while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
        foreach ($db_rights as $row) {
            $dbNameLength = /*overload*/mb_strlen($dbname);
            $found_rows[] = (!$dbNameLength)
                ? $row['Db']
                : $row['Table_name'];

            $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
                . '<td>'
                . htmlspecialchars(
                    (!$dbNameLength)
                    ? $row['Db']
                    : $row['Table_name']
                )
                . '</td>' . "\n"
                . '<td><code>' . "\n"
                . '        '
                . join(
                    ',' . "\n" . '            ',
                    PMA_extractPrivInfo($row, true)
                ) . "\n"
                . '</code></td>' . "\n"
                . '<td>'
                    . ((((!$dbNameLength) && $row['Grant_priv'] == 'Y')
                        || ($dbNameLength
                        && in_array('Grant', explode(',', $row['Table_priv']))))
                    ? __('Yes')
                    : __('No'))
                . '</td>' . "\n"
                . '<td>';
            if (! empty($row['Table_privs']) || ! empty ($row['Column_priv'])) {
                $html_output .= __('Yes');
            } else {
                $html_output .= __('No');
            }
            $html_output .= '</td>' . "\n"
               . '<td>';
            $html_output .= PMA_getUserLink(
                'edit',
                $username,
                $hostname,
                (!$dbNameLength) ? $row['Db'] : $dbname,
                (!$dbNameLength) ? '' : $row['Table_name']
            );
            $html_output .= '</td>' . "\n"
               . '    <td>';
            if (! empty($row['can_delete'])
                || isset($row['Table_name'])
                && /*overload*/mb_strlen($row['Table_name'])
            ) {
                $html_output .= PMA_getUserLink(
                    'revoke',
                    $username,
                    $hostname,
                    (!$dbNameLength) ? $row['Db'] : $dbname,
                    (!$dbNameLength) ? '' : $row['Table_name']
                );
            }
            $html_output .= '</td>' . "\n"
               . '</tr>' . "\n";
            $odd_row = ! $odd_row;
        } // end while
    } //end if
    return array($found_rows, $html_output);
}

/**
 * Get a HTML table for display user's tabel specific or database specific rights
 *
 * @param string $username username
 * @param string $hostname host name
 * @param string $dbname   database name
 *
 * @return array $html_output, $found_rows
 */
function PMA_getHtmlForAllTableSpecificRights(
    $username, $hostname, $dbname
) {
    // table header
    $html_output = PMA_URL_getHiddenInputs('', '')
        . '<input type="hidden" name="username" '
        . 'value="' . htmlspecialchars($username) . '" />' . "\n"
        . '<input type="hidden" name="hostname" '
        . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
        . '<fieldset>' . "\n"
        . '<legend data-submenu-label="'
        . (!/*overload*/mb_strlen($dbname)
            ? __('Database')
            : __('Table')
        )
        . '">'
        . (!/*overload*/mb_strlen($dbname)
            ? __('Database-specific privileges')
            : __('Table-specific privileges')
        )
        . '</legend>' . "\n"
        . '<table class="data">' . "\n"
        . '<thead>' . "\n"
        . '<tr><th>'
        . (!/*overload*/mb_strlen($dbname) ? __('Database') : __('Table'))
        . '</th>' . "\n"
        . '<th>' . __('Privileges') . '</th>' . "\n"
        . '<th>' . __('Grant') . '</th>' . "\n"
        . '<th>'
        . (!/*overload*/mb_strlen($dbname)
            ? __('Table-specific privileges')
            : __('Column-specific privileges')
        )
        . '</th>' . "\n"
        . '<th colspan="2">' . __('Action') . '</th>' . "\n"
        . '</tr>' . "\n"
        . '</thead>' . "\n";

    $user_host_condition = ' WHERE `User`'
        . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
        . ' AND `Host`'
        . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'";

    // table body
    // get data

    // we also want privileges for this user not in table `db` but in other table
    $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');

    /**
     * no db name given, so we want all privs for the given user
     * db name was given, so we want all user specific rights for this db
     */
    $db_rights = PMA_getUserSpecificRights($tables, $user_host_condition, $dbname);

    ksort($db_rights);

    $html_output .= '<tbody>' . "\n";
    // display rows
    list ($found_rows, $html_out) =  PMA_getHtmlForUserRights(
        $db_rights, $dbname, $hostname, $username
    );

    $html_output .= $html_out;
    $html_output .= '</tbody>' . "\n";
    $html_output .='</table>' . "\n";

    return array($html_output, $found_rows);
}

/**
 * Get HTML for display select db
 *
 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
 *
 * @return string HTML snippet
 */
function PMA_getHtmlForSelectDbInEditPrivs($found_rows)
{
    // we already have the list of databases from libraries/common.inc.php
    // via $pma = new PMA;
    $pred_db_array = $GLOBALS['pma']->databases;

    $databases_to_skip = array('information_schema', 'performance_schema');

    $html_output = '<label for="text_dbname">'
        . __('Add privileges on the following database(s):') . '</label>' . "\n";
    if (! empty($pred_db_array)) {
        $html_output .= '<select name="pred_dbname[]" multiple="multiple">' . "\n";
        foreach ($pred_db_array as $current_db) {
            if (in_array($current_db, $databases_to_skip)) {
                continue;
            }
            $current_db_show = $current_db;
            $current_db = PMA_Util::escapeMysqlWildcards($current_db);
            // cannot use array_diff() once, outside of the loop,
            // because the list of databases has special characters
            // already escaped in $found_rows,
            // contrary to the output of SHOW DATABASES
            if (empty($found_rows) || ! in_array($current_db, $found_rows)) {
                $html_output .= '<option value="'
                    . htmlspecialchars($current_db) . '">'
                    . htmlspecialchars($current_db_show) . '</option>' . "\n";
            }
        }
        $html_output .= '</select>' . "\n";
    }
    $html_output .= '<input type="text" id="text_dbname" name="dbname" />'
        . "\n"
        . PMA_Util::showHint(
            __('Wildcards % and _ should be escaped with a \ to use them literally.')
        );
    return $html_output;
}

/**
 * Get HTML for display table in edit privilege
 *
 * @param string $dbname     database naame
 * @param array  $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
 *
 * @return string HTML snippet
 */
function PMA_displayTablesInEditPrivs($dbname, $found_rows)
{
    $html_output = '<input type="hidden" name="dbname"
        ' . 'value="' . htmlspecialchars($dbname) . '"/>' . "\n";
    $html_output .= '<label for="text_tablename">'
        . __('Add privileges on the following table:') . '</label>' . "\n";

    $result = @$GLOBALS['dbi']->tryQuery(
        'SHOW TABLES FROM ' . PMA_Util::backquote(
            PMA_Util::unescapeMysqlWildcards($dbname)
        ) . ';',
        null,
        PMA_DatabaseInterface::QUERY_STORE
    );

    if ($result) {
        $pred_tbl_array = array();
        while ($row = $GLOBALS['dbi']->fetchRow($result)) {
            if (! isset($found_rows) || ! in_array($row[0], $found_rows)) {
                $pred_tbl_array[] = $row[0];
            }
        }
        $GLOBALS['dbi']->freeResult($result);

        if (! empty($pred_tbl_array)) {
            $html_output .= '<select name="pred_tablename" '
                . 'class="autosubmit">' . "\n"
                . '<option value="" selected="selected">' . __('Use text field')
                . ':</option>' . "\n";
            foreach ($pred_tbl_array as $current_table) {
                $html_output .= '<option '
                    . 'value="' . htmlspecialchars($current_table) . '">'
                    . htmlspecialchars($current_table)
                    . '</option>' . "\n";
            }
            $html_output .= '</select>' . "\n";
        }
    }
    $html_output .= '<input type="text" id="text_tablename" name="tablename" />'
        . "\n";

    return $html_output;
}

/**
 * Get HTML for display the users overview
 * (if less than 50 users, display them immediately)
 *
 * @param array  $result        ran sql query
 * @param array  $db_rights     user's database rights array
 * @param string $pmaThemeImage a image source link
 * @param string $text_dir      text directory
 *
 * @return string HTML snippet
 */
function PMA_getUsersOverview($result, $db_rights, $pmaThemeImage, $text_dir)
{
    while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
        $row['privs'] = PMA_extractPrivInfo($row, true);
        $db_rights[$row['User']][$row['Host']] = $row;
    }
    @$GLOBALS['dbi']->freeResult($result);
    $user_group_count = 0;
    if ($GLOBALS['cfgRelation']['menuswork']) {
        $user_group_count = PMA_getUserGroupCount();
    }

    $html_output
        = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
        . 'method="post">' . "\n"
        . PMA_URL_getHiddenInputs('', '')
        . '<table id="tableuserrights" class="data">' . "\n"
        . '<thead>' . "\n"
        . '<tr><th></th>' . "\n"
        . '<th>' . __('User') . '</th>' . "\n"
        . '<th>' . __('Host') . '</th>' . "\n"
        . '<th>' . __('Password') . '</th>' . "\n"
        . '<th>' . __('Global privileges') . ' '
        . PMA_Util::showHint(
            __('Note: MySQL privilege names are expressed in English.')
        )
        . '</th>' . "\n";
    if ($GLOBALS['cfgRelation']['menuswork']) {
        $html_output .= '<th>' . __('User group') . '</th>' . "\n";
    }
    $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
        . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
        . __('Action') . '</th>' . "\n"
        . '</tr>' . "\n"
        . '</thead>' . "\n";

    $html_output .= '<tbody>' . "\n";
    $html_output .= PMA_getHtmlTableBodyForUserRights($db_rights);
    $html_output .= '</tbody>'
        . '</table>' . "\n";

    $html_output .= '<div style="float:left;">'
        . '<img class="selectallarrow"'
        . ' src="' . $pmaThemeImage . 'arrow_' . $text_dir . '.png"'
        . ' width="38" height="22"'
        . ' alt="' . __('With selected:') . '" />' . "\n"
        . '<input type="checkbox" id="usersForm_checkall" class="checkall_box" '
        . 'title="' . __('Check All') . '" /> '
        . '<label for="usersForm_checkall">' . __('Check All') . '</label> '
        . '<i style="margin-left: 2em">' . __('With selected:') . '</i>' . "\n";

    $html_output .= PMA_Util::getButtonOrImage(
        'submit_mult', 'mult_submit', 'submit_mult_export',
        __('Export'), 'b_tblexport.png', 'export'
    );
    $html_output .= '<input type="hidden" name="initial" '
        . 'value="' . (isset($_GET['initial']) ? $_GET['initial'] : '') . '" />';
    $html_output .= '</div>'
        . '<div class="clear_both" style="clear:both"></div>';

    // add/delete user fieldset
    $html_output .= PMA_getFieldsetForAddDeleteUser();
    $html_output .= '</form>' . "\n";

    return $html_output;
}

/**
 * Get table body for 'tableuserrights' table in userform
 *
 * @param array $db_rights user's database rights array
 *
 * @return string HTML snippet
 */
function PMA_getHtmlTableBodyForUserRights($db_rights)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['menuswork']) {
        $users_table = PMA_Util::backquote($cfgRelation['db'])
            . "." . PMA_Util::backquote($cfgRelation['users']);
        $sql_query = 'SELECT * FROM ' . $users_table;
        $result = PMA_queryAsControlUser($sql_query, false);
        $group_assignment = array();
        if ($result) {
            while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
                $group_assignment[$row['username']] = $row['usergroup'];
            }
        }
        $GLOBALS['dbi']->freeResult($result);

        $user_group_count = PMA_getUserGroupCount();
    }

    $odd_row = true;
    $index_checkbox = 0;
    $html_output = '';
    foreach ($db_rights as $user) {
        ksort($user);
        foreach ($user as $host) {
            $index_checkbox++;
            $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">'
                . "\n";
            $html_output .= '<td>'
                . '<input type="checkbox" class="checkall" name="selected_usr[]" '
                . 'id="checkbox_sel_users_'
                . $index_checkbox . '" value="'
                . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
                . '"'
                . ' /></td>' . "\n";

            $html_output .= '<td><label '
                . 'for="checkbox_sel_users_' . $index_checkbox . '">'
                . (empty($host['User'])
                    ? '<span style="color: #FF0000">' . __('Any') . '</span>'
                    : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
                . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";

            $html_output .= '<td>';
            switch ($host['Password']) {
            case 'Y':
                $html_output .= __('Yes');
                break;
            case 'N':
                $html_output .= '<span style="color: #FF0000">' . __('No')
                    . '</span>';
                break;
            // this happens if this is a definition not coming from mysql.user
            default:
                $html_output .= '--'; // in future version, replace by "not present"
                break;
            } // end switch
            $html_output .= '</td>' . "\n";

            $html_output .= '<td><code>' . "\n"
                . '' . implode(',' . "\n" . '            ', $host['privs']) . "\n"
                . '</code></td>' . "\n";
            if ($GLOBALS['cfgRelation']['menuswork']) {
                $html_output .= '<td class="usrGroup">' . "\n"
                    . (isset($group_assignment[$host['User']])
                        ? $group_assignment[$host['User']]
                        : ''
                    )
                    . '</td>' . "\n";
            }
            $html_output .= '<td>'
                . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
                . '</td>' . "\n";

            $html_output .= '<td class="center">'
                . PMA_getUserLink(
                    'edit',
                    $host['User'],
                    $host['Host']
                )
                . '</td>';
            if ($GLOBALS['cfgRelation']['menuswork'] && $user_group_count > 0) {
                if (empty($host['User'])) {
                    $html_output .= '<td class="center"></td>';
                } else {
                    $html_output .= '<td class="center">'
                        . PMA_getUserGroupEditLink($host['User'])
                        . '</td>';
                }
            }
            $html_output .= '<td class="center">'
                . PMA_getUserLink(
                    'export',
                    $host['User'],
                    $host['Host'],
                    '',
                    '',
                    isset($_GET['initial']) ? $_GET['initial'] : ''
                )
                . '</td>';
            $html_output .= '</tr>';
            $odd_row = ! $odd_row;
        }
    }
    return $html_output;
}

/**
 * Get HTML fieldset for Add/Delete user
 *
 * @return string HTML snippet
 */
function PMA_getFieldsetForAddDeleteUser()
{
    $html_output = PMA_getAddUserHtmlFieldset();
    $html_output .= '<fieldset id="fieldset_delete_user">'
        . '<legend>' . "\n"
        . PMA_Util::getIcon('b_usrdrop.png')
        . '            ' . __('Remove selected users') . '' . "\n"
        . '</legend>' . "\n";

    $html_output .= '<input type="hidden" name="mode" value="2" />' . "\n"
        . '('
        . __(
            'Revoke all active privileges from the users '
            . 'and delete them afterwards.'
        )
        . ')'
        . '<br />' . "\n";

    $html_output .= '<input type="checkbox" '
        . 'title="'
        . __('Drop the databases that have the same names as the users.')
        . '" '
        . 'name="drop_users_db" id="checkbox_drop_users_db" />' . "\n";

    $html_output .= '<label for="checkbox_drop_users_db" '
        . 'title="'
        . __('Drop the databases that have the same names as the users.')
        . '">' . "\n"
        . '            '
        . __('Drop the databases that have the same names as the users.')
        . "\n"
        . '</label>' . "\n"
        . '</fieldset>' . "\n";

    $html_output .= '<fieldset id="fieldset_delete_user_footer" class="tblFooters">'
        . "\n";
    $html_output .= '<input type="submit" name="delete" '
        . 'value="' . __('Go') . '" id="buttonGo" '
        . 'class="ajax"/>' . "\n";

    $html_output .= '</fieldset>' . "\n";

    return $html_output;
}

/**
 * Get HTML for Displays the initials
 *
 * @param array $array_initials array for all initials, even non A-Z
 *
 * @return string HTML snippet
 */
function PMA_getHtmlForInitials($array_initials)
{
    // initialize to false the letters A-Z
    for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
        if (! isset($array_initials[/*overload*/mb_chr($letter_counter + 64)])) {
            $array_initials[/*overload*/mb_chr($letter_counter + 64)] = false;
        }
    }

    $initials = $GLOBALS['dbi']->tryQuery(
        'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY `User` ASC',
        null,
        PMA_DatabaseInterface::QUERY_STORE
    );
    while (list($tmp_initial) = $GLOBALS['dbi']->fetchRow($initials)) {
        $array_initials[$tmp_initial] = true;
    }

    // Display the initials, which can be any characters, not
    // just letters. For letters A-Z, we add the non-used letters
    // as greyed out.

    uksort($array_initials, "strnatcasecmp");

    $html_output = '<table id="initials_table" cellspacing="5">'
        . '<tr>';
    foreach ($array_initials as $tmp_initial => $initial_was_found) {
        if ($tmp_initial === null) {
            continue;
        }

        if (!$initial_was_found) {
            $html_output .= '<td>' . $tmp_initial . '</td>';
            continue;
        }

        $html_output .= '<td>'
            . '<a class="ajax'
            . ((isset($_REQUEST['initial'])
                && $_REQUEST['initial'] === $tmp_initial
                ) ? ' active' : '')
            . '" href="server_privileges.php'
            . PMA_URL_getCommon(array('initial' => $tmp_initial))
            . '">' . $tmp_initial
            . '</a>'
            . '</td>' . "\n";
    }
    $html_output .= '<td>'
        . '<a href="server_privileges.php'
        . PMA_URL_getCommon(array('showall' => 1))
        . '" class="nowrap">' . __('Show all') . '</a></td>' . "\n";
    $html_output .= '</tr></table>';

    return $html_output;
}

/**
 * Get the database rights array for Display user overview
 *
 * @return array  $db_rights    database rights array
 */
function PMA_getDbRightsForUserOverview()
{
    // we also want users not in table `user` but in other table
    $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');

    $tablesSearchForUsers = array(
        'user', 'db', 'tables_priv', 'columns_priv', 'procs_priv',
    );

    $db_rights_sqls = array();
    foreach ($tablesSearchForUsers as $table_search_in) {
        if (in_array($table_search_in, $tables)) {
            $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
                . $table_search_in . '` '
                . (isset($_GET['initial'])
                ? PMA_rangeOfUsers($_GET['initial'])
                : '');
        }
    }
    $user_defaults = array(
        'User'       => '',
        'Host'       => '%',
        'Password'   => '?',
        'Grant_priv' => 'N',
        'privs'      => array('USAGE'),
    );

    // for the rights
    $db_rights = array();

    $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
        . ' ORDER BY `User` ASC, `Host` ASC';

    $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);

    while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
        $db_rights_row = array_merge($user_defaults, $db_rights_row);
        $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
            = $db_rights_row;
    }
    $GLOBALS['dbi']->freeResult($db_rights_result);
    ksort($db_rights);

    return $db_rights;
}

/**
 * Delete user and get message and sql query for delete user in privileges
 *
 * @param array $queries queries
 *
 * @return array PMA_message
 */
function PMA_deleteUser($queries)
{
    $sql_query = '';
    if (empty($queries)) {
        $message = PMA_Message::error(__('No users selected for deleting!'));
    } else {
        if ($_REQUEST['mode'] == 3) {
            $queries[] = '# ' . __('Reloading the privileges') . ' …';
            $queries[] = 'FLUSH PRIVILEGES;';
        }
        $drop_user_error = '';
        foreach ($queries as $sql_query) {
            if ($sql_query{0} != '#') {
                if (! $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['userlink'])) {
                    $drop_user_error .= $GLOBALS['dbi']->getError() . "\n";
                }
            }
        }
        // tracking sets this, causing the deleted db to be shown in navi
        unset($GLOBALS['db']);

        $sql_query = join("\n", $queries);
        if (! empty($drop_user_error)) {
            $message = PMA_Message::rawError($drop_user_error);
        } else {
            $message = PMA_Message::success(
                __('The selected users have been deleted successfully.')
            );
        }
    }
    return array($sql_query, $message);
}

/**
 * Update the privileges and return the success or error message
 *
 * @param string $username  username
 * @param string $hostname  host name
 * @param string $tablename table name
 * @param string $dbname    database name
 *
 * @return PMA_message success message or error message for update
 */
function PMA_updatePrivileges($username, $hostname, $tablename, $dbname)
{
    $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);

    $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
        . ' FROM \'' . PMA_Util::sqlAddSlashes($username)
        . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';

    if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
        $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
            . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
            . PMA_Util::sqlAddSlashes($hostname) . '\';';
    } else {
        $sql_query1 = '';
    }

    // Should not do a GRANT USAGE for a table-specific privilege, it
    // causes problems later (cannot revoke it)
    if (! (/*overload*/mb_strlen($tablename)
        && 'USAGE' == implode('', PMA_extractPrivInfo()))
    ) {
        $sql_query2 = 'GRANT ' . join(', ', PMA_extractPrivInfo())
            . ' ON ' . $db_and_table
            . ' TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
            . PMA_Util::sqlAddSlashes($hostname) . '\'';

        if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
            || (! /*overload*/mb_strlen($dbname)
            && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
            || isset($_POST['max_updates'])
            || isset($_POST['max_user_connections'])))
        ) {
            $sql_query2 .= PMA_getWithClauseForAddUserAndUpdatePrivs();
        }
        $sql_query2 .= ';';
    }
    if (! $GLOBALS['dbi']->tryQuery($sql_query0)) {
        // This might fail when the executing user does not have
        // ALL PRIVILEGES himself.
        // See https://sourceforge.net/p/phpmyadmin/bugs/3270/
        $sql_query0 = '';
    }
    if (! empty($sql_query1) && ! $GLOBALS['dbi']->tryQuery($sql_query1)) {
        // this one may fail, too...
        $sql_query1 = '';
    }
    if (! empty($sql_query2)) {
        $GLOBALS['dbi']->query($sql_query2);
    } else {
        $sql_query2 = '';
    }
    $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
    $message = PMA_Message::success(__('You have updated the privileges for %s.'));
    $message->addParam(
        '\'' . htmlspecialchars($username)
        . '\'@\'' . htmlspecialchars($hostname) . '\''
    );

    return array($sql_query, $message);
}

/**
 * Get List of information: Changes / copies a user
 *
 * @return array
 */
function PMA_getDataForChangeOrCopyUser()
{
    $queries = null;
    $password = null;

    if (isset($_REQUEST['change_copy'])) {
        $user_host_condition = ' WHERE `User` = '
            . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
            . ' AND `Host` = '
            . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . "';";
        $row = $GLOBALS['dbi']->fetchSingleRow(
            'SELECT * FROM `mysql`.`user` ' . $user_host_condition
        );
        if (! $row) {
            $response = PMA_Response::getInstance();
            $response->addHTML(
                PMA_Message::notice(__('No user found.'))->getDisplay()
            );
            unset($_REQUEST['change_copy']);
        } else {
            extract($row, EXTR_OVERWRITE);
            // Recent MySQL versions have the field "Password" in mysql.user,
            // so the previous extract creates $Password but this script
            // uses $password
            if (! isset($password) && isset($Password)) {
                $password = $Password;
            }
            $queries = array();
        }
    }

    return array($queries, $password);
}

/**
 * Update Data for information: Deletes users
 *
 * @param array $queries queries array
 *
 * @return array
 */
function PMA_getDataForDeleteUsers($queries)
{
    if (isset($_REQUEST['change_copy'])) {
        $selected_usr = array(
            $_REQUEST['old_username'] . '&amp;#27;' . $_REQUEST['old_hostname']
        );
    } else {
        $selected_usr = $_REQUEST['selected_usr'];
        $queries = array();
    }
    foreach ($selected_usr as $each_user) {
        list($this_user, $this_host) = explode('&amp;#27;', $each_user);
        $queries[] = '# '
            . sprintf(
                __('Deleting %s'),
                '\'' . $this_user . '\'@\'' . $this_host . '\''
            )
            . ' ...';
        $queries[] = 'DROP USER \''
            . PMA_Util::sqlAddSlashes($this_user)
            . '\'@\'' . PMA_Util::sqlAddSlashes($this_host) . '\';';

        if (isset($_REQUEST['drop_users_db'])) {
            $queries[] = 'DROP DATABASE IF EXISTS '
                . PMA_Util::backquote($this_user) . ';';
            $GLOBALS['reload'] = true;
        }
    }
    return $queries;
}

/**
 * update Message For Reload
 *
 * @return array
 */
function PMA_updateMessageForReload()
{
    $message = null;
    if (isset($_REQUEST['flush_privileges'])) {
        $sql_query = 'FLUSH PRIVILEGES;';
        $GLOBALS['dbi']->query($sql_query);
        $message = PMA_Message::success(
            __('The privileges were reloaded successfully.')
        );
    }

    if (isset($_REQUEST['validate_username'])) {
        $message = PMA_Message::success();
    }

    return $message;
}

/**
 * update Data For Queries from queries_for_display
 *
 * @param array      $queries             queries array
 * @param array|null $queries_for_display queries array for display
 *
 * @return null
 */
function PMA_getDataForQueries($queries, $queries_for_display)
{
    $tmp_count = 0;
    foreach ($queries as $sql_query) {
        if ($sql_query{0} != '#') {
            $GLOBALS['dbi']->query($sql_query);
        }
        // when there is a query containing a hidden password, take it
        // instead of the real query sent
        if (isset($queries_for_display[$tmp_count])) {
            $queries[$tmp_count] = $queries_for_display[$tmp_count];
        }
        $tmp_count++;
    }

    return $queries;
}

/**
 * update Data for information: Adds a user
 *
 * @param string $dbname      db name
 * @param string $username    user name
 * @param string $hostname    host name
 * @param string $password    password
 * @param bool   $is_menuwork is_menuwork set?
 *
 * @return array
 */
function PMA_addUser(
    $dbname, $username, $hostname,
    $password, $is_menuwork
) {
    $_add_user_error = false;
    $message = null;
    $queries = null;
    $queries_for_display = null;
    $sql_query = null;

    if (isset($_REQUEST['adduser_submit']) || isset($_REQUEST['change_copy'])) {
        $sql_query = '';
        if ($_POST['pred_username'] == 'any') {
            $username = '';
        }
        switch ($_POST['pred_hostname']) {
        case 'any':
            $hostname = '%';
            break;
        case 'localhost':
            $hostname = 'localhost';
            break;
        case 'hosttable':
            $hostname = '';
            break;
        case 'thishost':
            $_user_name = $GLOBALS['dbi']->fetchValue('SELECT USER()');
            $hostname = /*overload*/mb_substr(
                $_user_name,
                (/*overload*/mb_strrpos($_user_name, '@') + 1)
            );
            unset($_user_name);
            break;
        }
        $sql = "SELECT '1' FROM `mysql`.`user`"
            . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
            . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
        if ($GLOBALS['dbi']->fetchValue($sql) == 1) {
            $message = PMA_Message::error(__('The user %s already exists!'));
            $message->addParam(
                '[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]'
            );
            $_REQUEST['adduser'] = true;
            $_add_user_error = true;
        } else {
            list($create_user_real, $create_user_show, $real_sql_query, $sql_query)
                = PMA_getSqlQueriesForDisplayAndAddUser(
                    $username, $hostname, (isset ($password) ? $password : '')
                );

            if (empty($_REQUEST['change_copy'])) {
                $_error = false;

                if (isset($create_user_real)) {
                    if (! $GLOBALS['dbi']->tryQuery($create_user_real)) {
                        $_error = true;
                    }
                    $sql_query = $create_user_show . $sql_query;
                }
                list($sql_query, $message) = PMA_addUserAndCreateDatabase(
                    $_error, $real_sql_query, $sql_query, $username, $hostname,
                    isset($dbname) ? $dbname : null
                );
                if (! empty($_REQUEST['userGroup']) && $is_menuwork) {
                    PMA_setUserGroup($GLOBALS['username'], $_REQUEST['userGroup']);
                }

            } else {
                if (isset($create_user_real)) {
                    $queries[] = $create_user_real;
                }
                $queries[] = $real_sql_query;
                // we put the query containing the hidden password in
                // $queries_for_display, at the same position occupied
                // by the real query in $queries
                $tmp_count = count($queries);
                if (isset($create_user_real)) {
                    $queries_for_display[$tmp_count - 2] = $create_user_show;
                }
                $queries_for_display[$tmp_count - 1] = $sql_query;
            }
            unset($real_sql_query);
        }
    }

    return array(
        $message, $queries, $queries_for_display, $sql_query, $_add_user_error
    );
}

/**
 * Update DB information: DB, Table, isWildcard
 *
 * @return array
 */
function PMA_getDataForDBInfo()
{
    $username = null;
    $hostname = null;
    $dbname = null;
    $tablename = null;
    $dbname_is_wildcard = null;

    if (isset ($_REQUEST['username'])) {
        $username = $_REQUEST['username'];
    }
    if (isset ($_REQUEST['hostname'])) {
        $hostname = $_REQUEST['hostname'];
    }
    /**
     * Checks if a dropdown box has been used for selecting a database / table
     */
    if (PMA_isValid($_REQUEST['pred_tablename'])) {
        $tablename = $_REQUEST['pred_tablename'];
    } elseif (PMA_isValid($_REQUEST['tablename'])) {
        $tablename = $_REQUEST['tablename'];
    } else {
        unset($tablename);
    }

    if (isset($_REQUEST['pred_dbname'])) {
        $is_valid_pred_dbname = true;
        foreach ($_REQUEST['pred_dbname'] as $key => $db_name) {
            if (! PMA_isValid($db_name)) {
                $is_valid_pred_dbname = false;
                break;
            }
        }
    }

    if (isset($_REQUEST['dbname'])) {
        $is_valid_dbname = true;
        if (is_array($_REQUEST['dbname'])) {
            foreach ($_REQUEST['dbname'] as $key => $db_name) {
                if (! PMA_isValid($db_name)) {
                    $is_valid_dbname = false;
                    break;
                }
            }
        } else {
            if (! PMA_isValid($_REQUEST['dbname'])) {
                $is_valid_dbname = false;
            }
        }
    }

    if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
        $dbname = $_REQUEST['pred_dbname'];
        // If dbname contains only one database.
        if (count($dbname) == 1) {
            $dbname = $dbname[0];
        }
    } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
        $dbname = $_REQUEST['dbname'];
    } else {
        unset($dbname);
        unset($tablename);
    }

    if (isset($dbname)) {
        if (is_array($dbname)) {
            $db_and_table = $dbname;
            foreach ($db_and_table as $key => $db_name) {
                $db_and_table[$key] .= '.';
            }
        } else {
            $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
            $db_and_table = PMA_Util::backquote($unescaped_db) . '.';
        }
        if (isset($tablename)) {
            $db_and_table .= PMA_Util::backquote($tablename);
        } else {
            if (is_array($db_and_table)) {
                foreach ($db_and_table as $key => $db_name) {
                    $db_and_table[$key] .= '*';
                }
            } else {
                $db_and_table .= '*';
            }
        }
    } else {
        $db_and_table = '*.*';
    }

    // check if given $dbname is a wildcard or not
    if (isset($dbname)) {
        //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
        if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/i', $dbname)) {
            $dbname_is_wildcard = true;
        } else {
            $dbname_is_wildcard = false;
        }
    }

    return array(
        $username, $hostname,
        isset($dbname)? $dbname : null,
        isset($tablename)? $tablename : null,
        $db_and_table,
        $dbname_is_wildcard,
    );
}

/**
 * Get title and textarea for export user definition in Privileges
 *
 * @param string $username username
 * @param string $hostname host name
 *
 * @return array ($title, $export)
 */
function PMA_getListForExportUserDefinition($username, $hostname)
{
    $export = '<textarea class="export" cols="' . $GLOBALS['cfg']['TextareaCols']
        . '" rows="' . $GLOBALS['cfg']['TextareaRows'] . '">';

    if (isset($_REQUEST['selected_usr'])) {
        // export privileges for selected users
        $title = __('Privileges');

        foreach ($_REQUEST['selected_usr'] as $export_user) {
            $export_username = /*overload*/mb_substr(
                $export_user, 0, /*overload*/mb_strpos($export_user, '&')
            );
            $export_hostname = /*overload*/mb_substr(
                $export_user, /*overload*/mb_strrpos($export_user, ';') + 1
            );
            $export .= '# '
                . sprintf(
                    __('Privileges for %s'),
                    '`' . htmlspecialchars($export_username)
                    . '`@`' . htmlspecialchars($export_hostname) . '`'
                )
                . "\n\n";
            $export .= PMA_getGrants($export_username, $export_hostname) . "\n";
        }
    } else {
        // export privileges for a single user
        $title = __('User') . ' `' . htmlspecialchars($username)
            . '`@`' . htmlspecialchars($hostname) . '`';
        $export .= PMA_getGrants($username, $hostname);
    }
    // remove trailing whitespace
    $export = trim($export);

    $export .= '</textarea>';

    return array($title, $export);
}

/**
 * Get HTML for display Add userfieldset
 *
 * @param string $db    the database
 * @param string $table the table name
 *
 * @return string html output
 */
function PMA_getAddUserHtmlFieldset($db = '', $table = '')
{
    if (!$GLOBALS['is_createuser']) {
        return '';
    }
    $rel_params = array();
    $url_params = array(
        'adduser' => 1
    );
    if (!empty($db)) {
        $url_params['dbname']
            = $rel_params['checkprivsdb']
                = $db;
    }
    if (!empty($table)) {
        $url_params['tablename']
            = $rel_params['checkprivstable']
                = $table;
    }

    return '<fieldset id="fieldset_add_user">' . "\n"
        . '<legend>' . _pgettext('Create new user', 'New') . '</legend>'
        . '<a href="server_privileges.php'
        . PMA_URL_getCommon($url_params) . '" '
        . (!empty($rel_params)
            ? ('rel="' . PMA_URL_getCommon($rel_params) . '" ')
            : '')
        . '">' . "\n"
        . PMA_Util::getIcon('b_usradd.png')
        . '            ' . __('Add user') . '</a>' . "\n"
        . '</fieldset>' . "\n";
}

/**
 * Get HTML header for display User's properties
 *
 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
 * @param string  $url_dbname         url database name that urlencode() string
 * @param string  $dbname             database name
 * @param string  $username           username
 * @param string  $hostname           host name
 * @param string  $tablename          table name
 *
 * @return string $html_output
 */
function PMA_getHtmlHeaderForUserProperties(
    $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
) {
    $html_output = '<h2>' . "\n"
       . PMA_Util::getIcon('b_usredit.png')
       . __('Edit Privileges:') . ' '
       . __('User');

    if (! empty($dbname)) {
        $html_output .= ' <i><a class="edit_user_anchor"'
            . ' href="server_privileges.php'
            . PMA_URL_getCommon(
                array(
                    'username' => $username,
                    'hostname' => $hostname,
                    'dbname' => '',
                    'tablename' => '',
                )
            )
            . '">\'' . htmlspecialchars($username)
            . '\'@\'' . htmlspecialchars($hostname)
            . '\'</a></i>' . "\n";

        $html_output .= ' - ';
        $html_output .= ($dbname_is_wildcard
            || is_array($dbname) && count($dbname) > 1)
            ? __('Databases') : __('Database');
        if (! empty($_REQUEST['tablename'])) {
            $html_output .= ' <i><a href="server_privileges.php'
                . PMA_URL_getCommon(
                    array(
                        'username' => $username,
                        'hostname' => $hostname,
                        'dbname' => $url_dbname,
                        'tablename' => '',
                    )
                )
                . '">' . htmlspecialchars($dbname)
                . '</a></i>';

            $html_output .= ' - ' . __('Table')
                . ' <i>' . htmlspecialchars($tablename) . '</i>';
        } else {
            if (! is_array($dbname)) {
                $dbname = array($dbname);
            }
            $html_output .= ' <i>'
                . htmlspecialchars(implode(', ', $dbname))
                . '</i>';
        }

    } else {
        $html_output .= ' <i>\'' . htmlspecialchars($username)
            . '\'@\'' . htmlspecialchars($hostname)
            . '\'</i>' . "\n";

    }
    $html_output .= '</h2>' . "\n";
    $cur_user = htmlspecialchars($GLOBALS['dbi']->getCurrentUser());
    $user = htmlspecialchars($username . '@' . $hostname);
    // Add a short notice for the user
    // to remind him that he is editing his own privileges
    if ($user === $cur_user) {
        $html_output .= PMA_Message::notice(
            __(
                'Note: You are attempting to edit privileges of the '
                . 'user with which you are currently logged in.'
            )
        )->getDisplay();
    }
    return $html_output;
}

/**
 * Get HTML snippet for display user overview page
 *
 * @param string $pmaThemeImage a image source link
 * @param string $text_dir      text directory
 *
 * @return string $html_output
 */
function PMA_getHtmlForUserOverview($pmaThemeImage, $text_dir)
{
    $html_output = '<h2>' . "\n"
       . PMA_Util::getIcon('b_usrlist.png')
       . __('Users overview') . "\n"
       . '</h2>' . "\n";

    // $sql_query is for the initial-filtered,
    // $sql_query_all is for counting the total no. of users

    $sql_query = $sql_query_all = 'SELECT *,' .
        "       IF(`Password` = _latin1 '', 'N', 'Y') AS 'Password'" .
        '  FROM `mysql`.`user`';

    $sql_query .= (isset($_REQUEST['initial'])
        ? PMA_rangeOfUsers($_REQUEST['initial'])
        : '');

    $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
    $sql_query_all .= ' ;';

    $res = $GLOBALS['dbi']->tryQuery(
        $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
    );
    $res_all = $GLOBALS['dbi']->tryQuery(
        $sql_query_all, null, PMA_DatabaseInterface::QUERY_STORE
    );

    if (! $res) {
        // the query failed! This may have two reasons:
        // - the user does not have enough privileges
        // - the privilege tables use a structure of an earlier version.
        // so let's try a more simple query

        $GLOBALS['dbi']->freeResult($res);
        $GLOBALS['dbi']->freeResult($res_all);
        $sql_query = 'SELECT * FROM `mysql`.`user`';
        $res = $GLOBALS['dbi']->tryQuery(
            $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
        );

        if (! $res) {
            $html_output .= PMA_getHtmlForViewUsersError();
            $html_output .= PMA_getAddUserHtmlFieldset();
        } else {
            // This message is hardcoded because I will replace it by
            // a automatic repair feature soon.
            $raw = 'Your privilege table structure seems to be older than'
                . ' this MySQL version!<br />'
                . 'Please run the <code>mysql_upgrade</code> command'
                . '(<code>mysql_fix_privilege_tables</code> on older systems)'
                . ' that should be included in your MySQL server distribution'
                . ' to solve this problem!';
            $html_output .= PMA_Message::rawError($raw)->getDisplay();
        }
        $GLOBALS['dbi']->freeResult($res);
    } else {
        $db_rights = PMA_getDbRightsForUserOverview();
        // for all initials, even non A-Z
        $array_initials = array();

        /**
         * Displays the initials
         * Also not necessary if there is less than 20 privileges
         */
        if ($GLOBALS['dbi']->numRows($res_all) > 20) {
            $html_output .= PMA_getHtmlForInitials($array_initials);
        }

        /**
        * Display the user overview
        * (if less than 50 users, display them immediately)
        */
        if (isset($_REQUEST['initial'])
            || isset($_REQUEST['showall'])
            || $GLOBALS['dbi']->numRows($res) < 50
        ) {
            $html_output .= PMA_getUsersOverview(
                $res, $db_rights, $pmaThemeImage, $text_dir
            );
        } else {
            $html_output .= PMA_getAddUserHtmlFieldset();
        } // end if (display overview)

        if (! $GLOBALS['is_ajax_request']
            || ! empty($_REQUEST['ajax_page_request'])
        ) {
            $flushnote = new PMA_Message(
                __(
                    'Note: phpMyAdmin gets the users\' privileges directly '
                    . 'from MySQL\'s privilege tables. The content of these tables '
                    . 'may differ from the privileges the server uses, '
                    . 'if they have been changed manually. In this case, '
                    . 'you should %sreload the privileges%s before you continue.'
                ),
                PMA_Message::NOTICE
            );
            $flushLink = '<a href="server_privileges.php'
                . PMA_URL_getCommon(array('flush_privileges' => 1))
                . '" id="reload_privileges_anchor">';
            $flushnote->addParam(
                $flushLink,
                false
            );
            $flushnote->addParam('</a>', false);
            $html_output .= $flushnote->getDisplay();
        }
    }

    return $html_output;
}

/**
 * Get HTML snippet for display user properties
 *
 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
 * @param string  $url_dbname         url database name that urlencode() string
 * @param string  $username           username
 * @param string  $hostname           host name
 * @param string  $dbname             database name
 * @param string  $tablename          table name
 *
 * @return string $html_output
 */
function PMA_getHtmlForUserProperties($dbname_is_wildcard,$url_dbname,
    $username, $hostname, $dbname, $tablename
) {
    $html_output  = '<div id="edit_user_dialog">';
    $html_output .= PMA_getHtmlHeaderForUserProperties(
        $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
    );

    $sql = "SELECT '1' FROM `mysql`.`user`"
        . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
        . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";

    $user_does_not_exists = (bool) ! $GLOBALS['dbi']->fetchValue($sql);

    if ($user_does_not_exists) {
        $html_output .= PMA_Message::error(
            __('The selected user was not found in the privilege table.')
        )->getDisplay();
        $html_output .= PMA_getHtmlForLoginInformationFields();
            //exit;
    }

    $_params = array(
        'username' => $username,
        'hostname' => $hostname,
    );
    if (! is_array($dbname) && /*overload*/mb_strlen($dbname)) {
        $_params['dbname'] = $dbname;
        if (/*overload*/mb_strlen($tablename)) {
            $_params['tablename'] = $tablename;
        }
    } else {
        $_params['dbname'] = $dbname;
    }

    $html_output .= '<form class="submenu-item" name="usersForm" '
        . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
    $html_output .= PMA_URL_getHiddenInputs($_params);
    $html_output .= PMA_getHtmlToDisplayPrivilegesTable(
        // If $dbname is an array, pass any one db as all have same privs.
        PMA_ifSetOr($dbname, (is_array($dbname)) ? $dbname[0] : '*', 'length'),
        PMA_ifSetOr($tablename, '*', 'length')
    );

    $html_output .= '</form>' . "\n";

    if (! is_array($dbname) && ! /*overload*/mb_strlen($tablename)
        && empty($dbname_is_wildcard)
    ) {

        // no table name was given, display all table specific rights
        // but only if $dbname contains no wildcards

        $html_output .= '<form class="submenu-item" action="server_privileges.php" '
            . 'id="db_or_table_specific_priv" method="post">' . "\n";

        // unescape wildcards in dbname at table level
        $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
        list($html_rightsTable, $found_rows)
            = PMA_getHtmlForAllTableSpecificRights(
                $username, $hostname, $unescaped_db
            );
        $html_output .= $html_rightsTable;

        if (! /*overload*/mb_strlen($dbname)) {
            // no database name was given, display select db
            $html_output .= PMA_getHtmlForSelectDbInEditPrivs($found_rows);

        } else {
            $html_output .= PMA_displayTablesInEditPrivs($dbname, $found_rows);
        }
        $html_output .= '</fieldset>' . "\n";

        $html_output .= '<fieldset class="tblFooters">' . "\n"
           . '    <input type="submit" value="' . __('Go') . '" />'
           . '</fieldset>' . "\n"
           . '</form>' . "\n";
    }

    // Provide a line with links to the relevant database and table
    if (! is_array($dbname) && /*overload*/mb_strlen($dbname)
        && empty($dbname_is_wildcard)
    ) {
        $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);

    }

    if (! is_array($dbname) && ! /*overload*/mb_strlen($dbname)
        && ! $user_does_not_exists
    ) {
        //change login information
        $html_output .= PMA_getHtmlForChangePassword($username, $hostname);
        $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
    }
    $html_output .= '</div>';

    return $html_output;
}

/**
 * Get queries for Table privileges to change or copy user
 *
 * @param string $user_host_condition user host condition to
 *                                    select relevant table privileges
 * @param array  $queries             queries array
 * @param string $username            username
 * @param string $hostname            host name
 *
 * @return array  $queries
 */
function PMA_getTablePrivsQueriesForChangeOrCopyUser($user_host_condition,
    $queries, $username, $hostname
) {
    $res = $GLOBALS['dbi']->query(
        'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
        . $user_host_condition,
        $GLOBALS['userlink'],
        PMA_DatabaseInterface::QUERY_STORE
    );
    while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {

        $res2 = $GLOBALS['dbi']->query(
            'SELECT `Column_name`, `Column_priv`'
            . ' FROM `mysql`.`columns_priv`'
            . ' WHERE `User`'
            . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
            . ' AND `Host`'
            . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . '\''
            . ' AND `Db`'
            . ' = \'' . PMA_Util::sqlAddSlashes($row['Db']) . "'"
            . ' AND `Table_name`'
            . ' = \'' . PMA_Util::sqlAddSlashes($row['Table_name']) . "'"
            . ';',
            null,
            PMA_DatabaseInterface::QUERY_STORE
        );

        $tmp_privs1 = PMA_extractPrivInfo($row);
        $tmp_privs2 = array(
            'Select' => array(),
            'Insert' => array(),
            'Update' => array(),
            'References' => array()
        );

        while ($row2 = $GLOBALS['dbi']->fetchAssoc($res2)) {
            $tmp_array = explode(',', $row2['Column_priv']);
            if (in_array('Select', $tmp_array)) {
                $tmp_privs2['Select'][] = $row2['Column_name'];
            }
            if (in_array('Insert', $tmp_array)) {
                $tmp_privs2['Insert'][] = $row2['Column_name'];
            }
            if (in_array('Update', $tmp_array)) {
                $tmp_privs2['Update'][] = $row2['Column_name'];
            }
            if (in_array('References', $tmp_array)) {
                $tmp_privs2['References'][] = $row2['Column_name'];
            }
        }
        if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
            $tmp_privs1[] = 'SELECT (`' . join('`, `', $tmp_privs2['Select']) . '`)';
        }
        if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
            $tmp_privs1[] = 'INSERT (`' . join('`, `', $tmp_privs2['Insert']) . '`)';
        }
        if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
            $tmp_privs1[] = 'UPDATE (`' . join('`, `', $tmp_privs2['Update']) . '`)';
        }
        if (count($tmp_privs2['References']) > 0
            && ! in_array('REFERENCES', $tmp_privs1)
        ) {
            $tmp_privs1[]
                = 'REFERENCES (`' . join('`, `', $tmp_privs2['References']) . '`)';
        }

        $queries[] = 'GRANT ' . join(', ', $tmp_privs1)
            . ' ON ' . PMA_Util::backquote($row['Db']) . '.'
            . PMA_Util::backquote($row['Table_name'])
            . ' TO \'' . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
            . (in_array('Grant', explode(',', $row['Table_priv']))
            ? ' WITH GRANT OPTION;'
            : ';');
    }
    return $queries;
}

/**
 * Get queries for database specific privileges for change or copy user
 *
 * @param array  $queries  queries array with string
 * @param string $username username
 * @param string $hostname host name
 *
 * @return array $queries
 */
function PMA_getDbSpecificPrivsQueriesForChangeOrCopyUser(
    $queries, $username, $hostname
) {
    $user_host_condition = ' WHERE `User`'
        . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
        . ' AND `Host`'
        . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . '\';';

    $res = $GLOBALS['dbi']->query(
        'SELECT * FROM `mysql`.`db`' . $user_host_condition
    );

    while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
        $queries[] = 'GRANT ' . join(', ', PMA_extractPrivInfo($row))
            . ' ON ' . PMA_Util::backquote($row['Db']) . '.*'
            . ' TO \'' . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
            . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
    }
    $GLOBALS['dbi']->freeResult($res);

    $queries = PMA_getTablePrivsQueriesForChangeOrCopyUser(
        $user_host_condition, $queries, $username, $hostname
    );

    return $queries;
}

/**
 * Prepares queries for adding users and
 * also create database and return query and message
 *
 * @param boolean $_error         whether user create or not
 * @param string  $real_sql_query SQL query for add a user
 * @param string  $sql_query      SQL query to be displayed
 * @param string  $username       username
 * @param string  $hostname       host name
 * @param string  $dbname         database name
 *
 * @return array  $sql_query, $message
 */
function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query,
    $username, $hostname, $dbname
) {
    if ($_error || (!empty($real_sql_query)
        && !$GLOBALS['dbi']->tryQuery($real_sql_query))
    ) {
        $_REQUEST['createdb-1'] = $_REQUEST['createdb-2']
            = $_REQUEST['createdb-3'] = null;
        $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
    } else {
        $message = PMA_Message::success(__('You have added a new user.'));
    }

    if (isset($_REQUEST['createdb-1'])) {
        // Create database with same name and grant all privileges
        $q = 'CREATE DATABASE IF NOT EXISTS '
            . PMA_Util::backquote(
                PMA_Util::sqlAddSlashes($username)
            ) . ';';
        $sql_query .= $q;
        if (! $GLOBALS['dbi']->tryQuery($q)) {
            $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
        }

        /**
         * Reload the navigation
         */
        $GLOBALS['reload'] = true;
        $GLOBALS['db'] = $username;

        $q = 'GRANT ALL PRIVILEGES ON '
            . PMA_Util::backquote(
                PMA_Util::escapeMysqlWildcards(
                    PMA_Util::sqlAddSlashes($username)
                )
            ) . '.* TO \''
            . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (! $GLOBALS['dbi']->tryQuery($q)) {
            $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
        }
    }

    if (isset($_REQUEST['createdb-2'])) {
        // Grant all privileges on wildcard name (username\_%)
        $q = 'GRANT ALL PRIVILEGES ON '
            . PMA_Util::backquote(
                PMA_Util::sqlAddSlashes($username) . '\_%'
            ) . '.* TO \''
            . PMA_Util::sqlAddSlashes($username)
            . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (! $GLOBALS['dbi']->tryQuery($q)) {
            $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
        }
    }

    if (isset($_REQUEST['createdb-3'])) {
        // Grant all privileges on the specified database to the new user
        $q = 'GRANT ALL PRIVILEGES ON '
        . PMA_Util::backquote(
            PMA_Util::sqlAddSlashes($dbname)
        ) . '.* TO \''
        . PMA_Util::sqlAddSlashes($username)
        . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (! $GLOBALS['dbi']->tryQuery($q)) {
            $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
        }
    }
    return array($sql_query, $message);
}

/**
 * Get SQL queries for Display and Add user
 *
 * @param string $username username
 * @param string $hostname host name
 * @param string $password password
 *
 * @return array ($create_user_real, $create_user_show,$real_sql_query, $sql_query)
 */
function PMA_getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
{
    $create_user_real = 'CREATE USER \''
        . PMA_Util::sqlAddSlashes($username) . '\'@\''
        . PMA_Util::sqlAddSlashes($hostname) . '\'';

    $real_sql_query = 'GRANT ' . join(', ', PMA_extractPrivInfo()) . ' ON *.* TO \''
        . PMA_Util::sqlAddSlashes($username) . '\'@\''
        . PMA_Util::sqlAddSlashes($hostname) . '\'';

    if ($_POST['pred_password'] != 'none' && $_POST['pred_password'] != 'keep') {
        $sql_query = $real_sql_query;
        // Requires SELECT privilege on mysql database
        // for using this with GRANT queries. It can be skipped.
        if ($GLOBALS['is_superuser']) {
            $sql_query .= ' IDENTIFIED BY \'***\'';
            $real_sql_query .= ' IDENTIFIED BY \''
                . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
        }
        if (isset($create_user_real)) {
            $create_user_show = $create_user_real . ' IDENTIFIED BY \'***\'';
            $create_user_real .= ' IDENTIFIED BY \''
                . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
        }
    } else {
        if ($_POST['pred_password'] == 'keep' && ! empty($password)) {
            $real_sql_query .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
            if (isset($create_user_real)) {
                $create_user_real .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
            }
        }
        $sql_query = $real_sql_query;
        if (isset($create_user_real)) {
            $create_user_show = $create_user_real;
        }
    }

    if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
        || (isset($_POST['max_questions']) || isset($_POST['max_connections'])
        || isset($_POST['max_updates']) || isset($_POST['max_user_connections']))
    ) {
        $with_clause = PMA_getWithClauseForAddUserAndUpdatePrivs();
        $real_sql_query .= ' ' . $with_clause;
        $sql_query .= ' ' . $with_clause;
    }

    if (isset($create_user_real)) {
        $create_user_real .= ';';
        $create_user_show .= ';';
    }
    $real_sql_query .= ';';
    $sql_query .= ';';
    // No Global GRANT_OPTION privilege
    if (!$GLOBALS['is_grantuser']) {
        $real_sql_query = '';
        $sql_query = '';
    }

    return array($create_user_real,
        $create_user_show,
        $real_sql_query,
        $sql_query
    );
}
?>