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

insert_edit.lib.php « libraries - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 706d1c11cd67c24a962b520df9ee3ef80ce94e81 (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
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * set of functions with the insert/edit features in pma
 *
 * @package PhpMyAdmin
 */

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

/**
 * Retrieve form parameters for insert/edit form
 *
 * @param string     $db                 name of the database
 * @param string     $table              name of the table
 * @param array|null $where_clauses      where clauses
 * @param array      $where_clause_array array of where clauses
 * @param string     $err_url            error url
 *
 * @return array $_form_params array of insert/edit form parameters
 */
function PMA_getFormParametersForInsertForm($db, $table, $where_clauses,
    $where_clause_array, $err_url
) {
    $_form_params = array(
        'db'        => $db,
        'table'     => $table,
        'goto'      => $GLOBALS['goto'],
        'err_url'   => $err_url,
        'sql_query' => $_REQUEST['sql_query'],
    );
    if (isset($where_clauses)) {
        foreach ($where_clause_array as $key_id => $where_clause) {
            $_form_params['where_clause[' . $key_id . ']'] = trim($where_clause);
        }
    }
    if (isset($_REQUEST['clause_is_unique'])) {
        $_form_params['clause_is_unique'] = $_REQUEST['clause_is_unique'];
    }
    return $_form_params;
}

/**
 * Creates array of where clauses
 *
 * @param array|string|null $where_clause where clause
 *
 * @return array whereClauseArray array of where clauses
 */
function PMA_getWhereClauseArray($where_clause)
{
    if (!isset($where_clause)) {
        return array();
    }

    if (is_array($where_clause)) {
        return $where_clause;
    }

    return array(0 => $where_clause);
}

/**
 * Analysing where clauses array
 *
 * @param array  $where_clause_array array of where clauses
 * @param string $table              name of the table
 * @param string $db                 name of the database
 *
 * @return array $where_clauses, $result, $rows
 */
function PMA_analyzeWhereClauses(
    $where_clause_array, $table, $db
) {
    $rows               = array();
    $result             = array();
    $where_clauses      = array();
    $found_unique_key   = false;
    foreach ($where_clause_array as $key_id => $where_clause) {

        $local_query     = 'SELECT * FROM '
            . PMA_Util::backquote($db) . '.'
            . PMA_Util::backquote($table)
            . ' WHERE ' . $where_clause . ';';
        $result[$key_id] = $GLOBALS['dbi']->query(
            $local_query, null, PMA_DatabaseInterface::QUERY_STORE
        );
        $rows[$key_id]   = $GLOBALS['dbi']->fetchAssoc($result[$key_id]);

        $where_clauses[$key_id] = str_replace('\\', '\\\\', $where_clause);
        $has_unique_condition   = PMA_showEmptyResultMessageOrSetUniqueCondition(
            $rows, $key_id, $where_clause_array, $local_query, $result
        );
        if ($has_unique_condition) {
            $found_unique_key = true;
        }
    }
    return array($where_clauses, $result, $rows, $found_unique_key);
}

/**
 * Show message for empty result or set the unique_condition
 *
 * @param array  $rows               MySQL returned rows
 * @param string $key_id             ID in current key
 * @param array  $where_clause_array array of where clauses
 * @param string $local_query        query performed
 * @param array  $result             MySQL result handle
 *
 * @return boolean $has_unique_condition
 */
function PMA_showEmptyResultMessageOrSetUniqueCondition($rows, $key_id,
    $where_clause_array, $local_query, $result
) {
    $has_unique_condition = false;

    // No row returned
    if (! $rows[$key_id]) {
        unset($rows[$key_id], $where_clause_array[$key_id]);
        PMA_Response::getInstance()->addHtml(
            PMA_Util::getMessage(
                __('MySQL returned an empty result set (i.e. zero rows).'),
                $local_query
            )
        );
        /**
         * @todo not sure what should be done at this point, but we must not
         * exit if we want the message to be displayed
         */
    } else {// end if (no row returned)
        $meta = $GLOBALS['dbi']->getFieldsMeta($result[$key_id]);

        list($unique_condition, $tmp_clause_is_unique)
            = PMA_Util::getUniqueCondition(
                $result[$key_id], count($meta), $meta, $rows[$key_id], true
            );

        if (! empty($unique_condition)) {
            $has_unique_condition = true;
        }
        unset($unique_condition, $tmp_clause_is_unique);
    }
    return $has_unique_condition;
}

/**
 * No primary key given, just load first row
 *
 * @param string $table name of the table
 * @param string $db    name of the database
 *
 * @return array                containing $result and $rows arrays
 */
function PMA_loadFirstRow($table, $db)
{
    $result = $GLOBALS['dbi']->query(
        'SELECT * FROM ' . PMA_Util::backquote($db)
        . '.' . PMA_Util::backquote($table) . ' LIMIT 1;',
        null,
        PMA_DatabaseInterface::QUERY_STORE
    );
    $rows = array_fill(0, $GLOBALS['cfg']['InsertRows'], false);
    return array($result, $rows);
}

/**
 * Add some url parameters
 *
 * @param array  $url_params         containing $db and $table as url parameters
 * @param array  $where_clause_array where clauses array
 * @param string $where_clause       where clause
 *
 * @return array Add some url parameters to $url_params array and return it
 */
function PMA_urlParamsInEditMode($url_params, $where_clause_array, $where_clause)
{
    if (isset($where_clause)) {
        foreach ($where_clause_array as $where_clause) {
            $url_params['where_clause'] = trim($where_clause);
        }
    }
    if (! empty($_REQUEST['sql_query'])) {
        $url_params['sql_query'] = $_REQUEST['sql_query'];
    }
    return $url_params;
}

/**
 * Show type information or function selectors in Insert/Edit
 *
 * @param string  $which      function|type
 * @param array   $url_params containing url parameters
 * @param boolean $is_show    whether to show the element in $which
 *
 * @return string an HTML snippet
 */
function PMA_showTypeOrFunction($which, $url_params, $is_show)
{
    $params = array();

    switch($which) {
    case 'function':
        $params['ShowFunctionFields'] = ($is_show ? 0 : 1);
        $params['ShowFieldTypesInDataEditView']
            = $GLOBALS['cfg']['ShowFieldTypesInDataEditView'];
        break;
    case 'type':
        $params['ShowFieldTypesInDataEditView'] = ($is_show ? 0 : 1);
        $params['ShowFunctionFields']
            = $GLOBALS['cfg']['ShowFunctionFields'];
        break;
    }

    $params['goto'] = 'sql.php';
    $this_url_params = array_merge($url_params, $params);

    if (! $is_show) {
        return ' : <a href="tbl_change.php'
            . PMA_URL_getCommon($this_url_params) . '">'
            . PMA_showTypeOrFunctionLabel($which)
            . '</a>';
    }
    return '<th><a href="tbl_change.php'
        . PMA_URL_getCommon($this_url_params)
        . '" title="' . __('Hide') . '">'
        . PMA_showTypeOrFunctionLabel($which)
        . '</a></th>';
}

/**
 * Show type information or function selectors labels in Insert/Edit
 *
 * @param string $which function|type
 *
 * @return string an HTML snippet
 */
function PMA_showTypeOrFunctionLabel($which)
{
    switch($which) {
    case 'function':
        return __('Function');
    case 'type':
        return __('Type');
    }

    return null;
}

 /**
  * Analyze the table column array
  *
  * @param array   $column         description of column in given table
  * @param array   $comments_map   comments for every column that has a comment
  * @param boolean $timestamp_seen whether a timestamp has been seen
  *
  * @return array                   description of column in given table
  */
function PMA_analyzeTableColumnsArray($column, $comments_map, $timestamp_seen)
{
    $column['Field_html']    = htmlspecialchars($column['Field']);
    $column['Field_md5']     = md5($column['Field']);
    // True_Type contains only the type (stops at first bracket)
    $column['True_Type']     = preg_replace('@\(.*@s', '', $column['Type']);
    $column['len'] = preg_match('@float|double@', $column['Type']) ? 100 : -1;
    $column['Field_title']   = PMA_getColumnTitle($column, $comments_map);
    $column['is_binary']     = PMA_isColumn(
        $column,
        array('binary', 'varbinary')
    );
    $column['is_blob']       = PMA_isColumn(
        $column,
        array('blob', 'tinyblob', 'mediumblob', 'longblob')
    );
    $column['is_char']       = PMA_isColumn(
        $column,
        array('char', 'varchar')
    );

    list($column['pma_type'], $column['wrap'], $column['first_timestamp'])
        = PMA_getEnumSetAndTimestampColumns($column, $timestamp_seen);

    return $column;
}

 /**
  * Retrieve the column title
  *
  * @param array $column       description of column in given table
  * @param array $comments_map comments for every column that has a comment
  *
  * @return string              column title
  */
function PMA_getColumnTitle($column, $comments_map)
{
    if (isset($comments_map[$column['Field']])) {
        return '<span style="border-bottom: 1px dashed black;" title="'
            . htmlspecialchars($comments_map[$column['Field']]) . '">'
            . $column['Field_html'] . '</span>';
    } else {
            return $column['Field_html'];
    }
}

 /**
  * check whether the column is of a certain type
  * the goal is to ensure that types such as "enum('one','two','binary',..)"
  * or "enum('one','two','varbinary',..)" are not categorized as binary
  *
  * @param array $column description of column in given table
  * @param array $types  the types to verify
  *
  * @return boolean whether the column's type if one of the $types
  */
function PMA_isColumn($column, $types)
{
    foreach ($types as $one_type) {
        if (/*overload*/mb_stripos($column['Type'], $one_type) === 0) {
            return true;
        }
    }
    return false;
}

/**
 * Retrieve set, enum, timestamp table columns
 *
 * @param array   $column         description of column in given table
 * @param boolean $timestamp_seen whether a timestamp has been seen
 *
 * @return array $column['pma_type'], $column['wrap'], $column['first_timestamp']
 */
function PMA_getEnumSetAndTimestampColumns($column, $timestamp_seen)
{
    $column['first_timestamp'] = false;
    switch ($column['True_Type']) {
    case 'set':
        $column['pma_type'] = 'set';
        $column['wrap']  = '';
        break;
    case 'enum':
        $column['pma_type'] = 'enum';
        $column['wrap']  = '';
        break;
    case 'timestamp':
        if (! $timestamp_seen) {   // can only occur once per table
            $column['first_timestamp'] = true;
        }
        $column['pma_type'] = $column['Type'];
        $column['wrap']  = ' nowrap';
        break;

    default:
        $column['pma_type'] = $column['Type'];
        $column['wrap']  = ' nowrap';
        break;
    }
    return array($column['pma_type'], $column['wrap'], $column['first_timestamp']);
}

/**
 * The function column
 * We don't want binary data to be destroyed
 * Note: from the MySQL manual: "BINARY doesn't affect how the column is
 *       stored or retrieved" so it does not mean that the contents is binary
 *
 * @param array   $column                description of column in given table
 * @param boolean $is_upload             upload or no
 * @param string  $column_name_appendix  the name attribute
 * @param string  $unnullify_trigger     validation string
 * @param array   $no_support_types      list of datatypes that are not (yet)
 *                                       handled by PMA
 * @param integer $tabindex_for_function +3000
 * @param integer $tabindex              tab index
 * @param integer $idindex               id index
 * @param boolean $insert_mode           insert mode or edit mode
 *
 * @return string                           an html snippet
 */
function PMA_getFunctionColumn($column, $is_upload, $column_name_appendix,
    $unnullify_trigger, $no_support_types, $tabindex_for_function,
    $tabindex, $idindex, $insert_mode
) {
    $html_output = '';
    if (($GLOBALS['cfg']['ProtectBinary'] === 'blob'
        && $column['is_blob'] && !$is_upload)
        || ($GLOBALS['cfg']['ProtectBinary'] === 'all'
        && $column['is_binary'])
        || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob'
        && $column['is_binary'])
    ) {
        $html_output .= '<td class="center">' . __('Binary') . '</td>' . "\n";
    } elseif (/*overload*/mb_strstr($column['True_Type'], 'enum')
        || /*overload*/mb_strstr($column['True_Type'], 'set')
        || in_array($column['pma_type'], $no_support_types)
    ) {
        $html_output .= '<td class="center">--</td>' . "\n";
    } else {
        $html_output .= '<td>' . "\n";

        $html_output .= '<select name="funcs' . $column_name_appendix . '"'
            . ' ' . $unnullify_trigger
            . ' tabindex="' . ($tabindex + $tabindex_for_function) . '"'
            . ' id="field_' . $idindex . '_1">';
        $html_output .= PMA_Util::getFunctionsForField($column, $insert_mode) . "\n";

        $html_output .= '</select>' .  "\n";
        $html_output .= '</td>' .  "\n";
    }
    return $html_output;
}

/**
 * The null column
 *
 * @param array   $column               description of column in given table
 * @param string  $column_name_appendix the name attribute
 * @param boolean $real_null_value      is column value null or not null
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_null    +6000
 * @param integer $idindex              id index
 * @param string  $vkey                 [multi_edit]['row_id']
 * @param array   $foreigners           keys into foreign fields
 * @param array   $foreignData          data about the foreign keys
 *
 * @return string                       an html snippet
 */
function PMA_getNullColumn($column, $column_name_appendix, $real_null_value,
    $tabindex, $tabindex_for_null, $idindex, $vkey, $foreigners, $foreignData
) {
    if ($column['Null'] != 'YES') {
        return "<td></td>\n";
    }
    $html_output = '';
    $html_output .= '<td>' . "\n";
    $html_output .= '<input type="hidden" name="fields_null_prev'
        . $column_name_appendix . '"';
    if ($real_null_value && !$column['first_timestamp']) {
        $html_output .= ' value="on"';
    }
    $html_output .= ' />' . "\n";

    $html_output .= '<input type="checkbox" class="checkbox_null" tabindex="'
        . ($tabindex + $tabindex_for_null) . '"'
        . ' name="fields_null' . $column_name_appendix . '"';
    if ($real_null_value) {
        $html_output .= ' checked="checked"';
    }
    $html_output .= ' id="field_' . ($idindex) . '_2" />';

    // nullify_code is needed by the js nullify() function
    $nullify_code = PMA_getNullifyCodeForNullColumn(
        $column, $foreigners, $foreignData
    );
    // to be able to generate calls to nullify() in jQuery
    $html_output .= '<input type="hidden" class="nullify_code" name="nullify_code'
        . $column_name_appendix . '" value="' . $nullify_code . '" />';
    $html_output .= '<input type="hidden" class="hashed_field" name="hashed_field'
        . $column_name_appendix . '" value="' .  $column['Field_md5'] . '" />';
    $html_output .= '<input type="hidden" class="multi_edit" name="multi_edit'
        . $column_name_appendix . '" value="' . PMA_escapeJsString($vkey) . '" />';
    $html_output .= '</td>' . "\n";

    return $html_output;
}

/**
 * Retrieve the nullify code for the null column
 *
 * @param array $column      description of column in given table
 * @param array $foreigners  keys into foreign fields
 * @param array $foreignData data about the foreign keys
 *
 * @return integer              $nullify_code
 */
function PMA_getNullifyCodeForNullColumn($column, $foreigners, $foreignData)
{
    $foreigner = PMA_searchColumnInForeigners($foreigners, $column['Field']);
    if (/*overload*/mb_strstr($column['True_Type'], 'enum')) {
        if (/*overload*/mb_strlen($column['Type']) > 20) {
            $nullify_code = '1';
        } else {
            $nullify_code = '2';
        }
    } elseif (/*overload*/mb_strstr($column['True_Type'], 'set')) {
        $nullify_code = '3';
    } elseif ($foreigners
        && $foreigner
        && $foreignData['foreign_link'] == false
    ) {
        // foreign key in a drop-down
        $nullify_code = '4';
    } elseif ($foreigners
        && $foreigner
        && $foreignData['foreign_link'] == true
    ) {
        // foreign key with a browsing icon
        $nullify_code = '6';
    } else {
        $nullify_code = '5';
    }
    return $nullify_code;
}

/**
 * Get the HTML elements for value column in insert form
 * (here, "column" is used in the sense of HTML column in HTML table)
 *
 * @param array   $column                description of column in given table
 * @param string  $backup_field          hidden input field
 * @param string  $column_name_appendix  the name attribute
 * @param string  $unnullify_trigger     validation string
 * @param integer $tabindex              tab index
 * @param integer $tabindex_for_value    offset for the values tabindex
 * @param integer $idindex               id index
 * @param string  $data                  description of the column field
 * @param string  $special_chars         special characters
 * @param array   $foreignData           data about the foreign keys
 * @param boolean $odd_row               whether row is odd
 * @param array   $paramTableDbArray     array containing $table and $db
 * @param integer $rownumber             the row number
 * @param array   $titles                An HTML IMG tag for a particular icon from
 *                                       a theme, which may be an actual file or
 *                                       an icon from a sprite
 * @param string  $text_dir              text direction
 * @param string  $special_chars_encoded replaced char if the string starts
 *                                       with a \r\n pair (0x0d0a) add an extra \n
 * @param string  $vkey                  [multi_edit]['row_id']
 * @param boolean $is_upload             is upload or not
 * @param integer $biggest_max_file_size 0 integer
 * @param string  $default_char_editing  default char editing mode which is stored
 *                                       in the config.inc.php script
 * @param array   $no_support_types      list of datatypes that are not (yet)
 *                                       handled by PMA
 * @param array   $gis_data_types        list of GIS data types
 * @param array   $extracted_columnspec  associative array containing type,
 *                                       spec_in_brackets and possibly
 *                                       enum_set_values (another array)
 *
 * @return string an html snippet
 */
function PMA_getValueColumn($column, $backup_field, $column_name_appendix,
    $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data,
    $special_chars, $foreignData, $odd_row, $paramTableDbArray, $rownumber,
    $titles, $text_dir, $special_chars_encoded, $vkey,
    $is_upload, $biggest_max_file_size,
    $default_char_editing, $no_support_types, $gis_data_types, $extracted_columnspec
) {
    // HTML5 data-* attribute data-type
    $data_type = $GLOBALS['PMA_Types']->getTypeClass($column['True_Type']);
    $html_output = '';

    if ($foreignData['foreign_link'] == true) {
        $html_output .= PMA_getForeignLink(
            $column, $backup_field, $column_name_appendix,
            $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data,
            $paramTableDbArray, $rownumber, $titles
        );

    } elseif (is_array($foreignData['disp_row'])) {
        $html_output .= PMA_dispRowForeignData(
            $backup_field, $column_name_appendix,
            $unnullify_trigger, $tabindex, $tabindex_for_value,
            $idindex, $data, $foreignData
        );

    } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea']
        && /*overload*/mb_strstr($column['pma_type'], 'longtext')
    ) {
        $html_output = '&nbsp;</td>';
        $html_output .= '</tr>';
        $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">'
            . '<td colspan="5" class="right">';
        $html_output .= PMA_getTextarea(
            $column, $backup_field, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $text_dir,
            $special_chars_encoded, $data_type
        );

    } elseif (/*overload*/mb_strstr($column['pma_type'], 'text')) {

        $html_output .= PMA_getTextarea(
            $column, $backup_field, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $text_dir,
            $special_chars_encoded, $data_type
        );
        $html_output .= "\n";
        if (/*overload*/mb_strlen($special_chars) > 32000) {
            $html_output .= "</td>\n";
            $html_output .= '<td>' . __(
                'Because of its length,<br /> this column might not be editable.'
            );
        }

    } elseif ($column['pma_type'] == 'enum') {
        $html_output .= PMA_getPmaTypeEnum(
            $column, $backup_field, $column_name_appendix, $extracted_columnspec,
            $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data
        );

    } elseif ($column['pma_type'] == 'set') {
        $html_output .= PMA_getPmaTypeSet(
            $column, $extracted_columnspec, $backup_field,
            $column_name_appendix, $unnullify_trigger, $tabindex,
            $tabindex_for_value, $idindex, $data
        );

    } elseif ($column['is_binary'] || $column['is_blob']) {
        $html_output .= PMA_getBinaryAndBlobColumn(
            $column, $data, $special_chars, $biggest_max_file_size,
            $backup_field, $column_name_appendix, $unnullify_trigger, $tabindex,
            $tabindex_for_value, $idindex, $text_dir, $special_chars_encoded,
            $vkey, $is_upload
        );

    } elseif (! in_array($column['pma_type'], $no_support_types)) {
        $html_output .= PMA_getValueColumnForOtherDatatypes(
            $column, $default_char_editing, $backup_field,
            $column_name_appendix, $unnullify_trigger, $tabindex, $special_chars,
            $tabindex_for_value, $idindex, $text_dir, $special_chars_encoded,
            $data, $extracted_columnspec
        );
    }

    if (in_array($column['pma_type'], $gis_data_types)) {
        $html_output .= PMA_getHTMLforGisDataTypes();
    }

    return $html_output;
}

/**
 * Get HTML for foreign link in insert form
 *
 * @param array   $column               description of column in given table
 * @param string  $backup_field         hidden input field
 * @param string  $column_name_appendix the name attribute
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data                 data to edit
 * @param array   $paramTableDbArray    array containing $table and $db
 * @param integer $rownumber            the row number
 * @param array   $titles               An HTML IMG tag for a particular icon from
 *                                      a theme, which may be an actual file or
 *                                      an icon from a sprite
 *
 * @return string                       an html snippet
 */
function PMA_getForeignLink($column, $backup_field, $column_name_appendix,
    $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data,
    $paramTableDbArray, $rownumber, $titles
) {
    list($table, $db) = $paramTableDbArray;
    $html_output = '';
    $html_output .= $backup_field . "\n";

    $html_output .= '<input type="hidden" name="fields_type'
        . $column_name_appendix . '" value="foreign" />';

    $html_output .= '<input type="text" name="fields' . $column_name_appendix . '" '
        . 'class="textfield" '
        . $unnullify_trigger . ' '
        . 'tabindex="' . ($tabindex + $tabindex_for_value) . '" '
        . 'id="field_' . ($idindex) . '_3" '
        . 'value="' . htmlspecialchars($data) . '" />';

    $html_output .= '<a class="ajax browse_foreign" href="browse_foreigners.php'
        . PMA_URL_getCommon(
            array(
                'db' => $db,
                'table' => $table,
                'field' => $column['Field'],
                'rownumber' => $rownumber,
                'data'      => $data
            )
        ) . '">'
        . str_replace("'", "\'", $titles['Browse']) . '</a>';
    return $html_output;
}

/**
 * Get HTML to display foreign data
 *
 * @param string  $backup_field         hidden input field
 * @param string  $column_name_appendix the name attribute
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data                 data to edit
 * @param array   $foreignData          data about the foreign keys
 *
 * @return string                       an html snippet
 */
function PMA_dispRowForeignData($backup_field, $column_name_appendix,
    $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data,
    $foreignData
) {
    $html_output = '';
    $html_output .= $backup_field . "\n";
    $html_output .= '<input type="hidden"'
        . ' name="fields_type' . $column_name_appendix . '"'
        . ' value="foreign" />';

    $html_output .= '<select name="fields' . $column_name_appendix . '"'
        . ' ' . $unnullify_trigger
        . ' class="textfield"'
        . ' tabindex="' . ($tabindex + $tabindex_for_value) . '"'
        . ' id="field_' . $idindex . '_3">';
    $html_output .= PMA_foreignDropdown(
        $foreignData['disp_row'], $foreignData['foreign_field'],
        $foreignData['foreign_display'], $data,
        $GLOBALS['cfg']['ForeignKeyMaxLimit']
    );
    $html_output .= '</select>';

    return $html_output;
}

/**
 * Get HTML textarea for insert form
 *
 * @param array   $column                column information
 * @param string  $backup_field          hidden input field
 * @param string  $column_name_appendix  the name attribute
 * @param string  $unnullify_trigger     validation string
 * @param integer $tabindex              tab index
 * @param integer $tabindex_for_value    offset for the values tabindex
 * @param integer $idindex               id index
 * @param string  $text_dir              text direction
 * @param string  $special_chars_encoded replaced char if the string starts
 *                                       with a \r\n pair (0x0d0a) add an extra \n
 * @param string  $data_type             the html5 data-* attribute type
 *
 * @return string                       an html snippet
 */
function PMA_getTextarea($column, $backup_field, $column_name_appendix,
    $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex,
    $text_dir, $special_chars_encoded, $data_type
) {
    $the_class = '';
    $textAreaRows = $GLOBALS['cfg']['TextareaRows'];
    $textareaCols = $GLOBALS['cfg']['TextareaCols'];

    if ($column['is_char']) {
        /**
         * @todo clarify the meaning of the "textfield" class and explain
         *       why character columns have the "char" class instead
         */
        $the_class = 'char';
        $textAreaRows = $GLOBALS['cfg']['CharTextareaRows'];
        $textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
        $extracted_columnspec = PMA_Util::extractColumnSpec($column['Type']);
        $maxlength = $extracted_columnspec['spec_in_brackets'];
    } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea']
        && /*overload*/mb_strstr($column['pma_type'], 'longtext')
    ) {
        $textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
        $textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
    }
    $html_output = $backup_field . "\n"
        . '<textarea name="fields' . $column_name_appendix . '"'
        . ' class="' . $the_class . '"'
        . (isset($maxlength) ? ' data-maxlength="' . $maxlength . '"' : '')
        . ' rows="' . $textAreaRows . '"'
        . ' cols="' . $textareaCols . '"'
        . ' dir="' . $text_dir . '"'
        . ' id="field_' . ($idindex) . '_3"'
        . ' ' . $unnullify_trigger
        . ' tabindex="' . ($tabindex + $tabindex_for_value) . '"'
        . ' data-type="' . $data_type . '">'
        . $special_chars_encoded
        . '</textarea>';

    return $html_output;
}

/**
 * Get HTML for enum type
 *
 * @param array   $column               description of column in given table
 * @param string  $backup_field         hidden input field
 * @param string  $column_name_appendix the name attribute
 * @param array   $extracted_columnspec associative array containing type,
 *                                      spec_in_brackets and possibly
 *                                      enum_set_values (another array)
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param mixed   $data                 data to edit
 *
 * @return string an html snippet
 */
function PMA_getPmaTypeEnum($column, $backup_field, $column_name_appendix,
    $extracted_columnspec, $unnullify_trigger, $tabindex, $tabindex_for_value,
    $idindex, $data
) {
    $html_output = '';
    if (! isset($column['values'])) {
        $column['values'] = PMA_getColumnEnumValues(
            $column, $extracted_columnspec
        );
    }
    $column_enum_values = $column['values'];
    $html_output .= '<input type="hidden" name="fields_type'
        . $column_name_appendix . '" value="enum" />';
    $html_output .= '<input type="hidden" name="fields'
        . $column_name_appendix . '" value="" />';
    $html_output .= "\n" . '            ' . $backup_field . "\n";
    if (/*overload*/mb_strlen($column['Type']) > 20) {
        $html_output .= PMA_getDropDownDependingOnLength(
            $column, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $data, $column_enum_values
        );
    } else {
        $html_output .= PMA_getRadioButtonDependingOnLength(
            $column_name_appendix, $unnullify_trigger,
            $tabindex, $column, $tabindex_for_value,
            $idindex, $data, $column_enum_values
        );
    }
    return $html_output;
}

/**
 * Get column values
 *
 * @param array $column               description of column in given table
 * @param array $extracted_columnspec associative array containing type,
 *                                    spec_in_brackets and possibly enum_set_values
 *                                    (another array)
 *
 * @return array column values as an associative array
 */
function PMA_getColumnEnumValues($column, $extracted_columnspec)
{
    $column['values'] = array();
    foreach ($extracted_columnspec['enum_set_values'] as $val) {
        $column['values'][] = array(
            'plain' => $val,
            'html'  => htmlspecialchars($val),
        );
    }
    return $column['values'];
}

/**
 * Get HTML drop down for more than 20 string length
 *
 * @param array   $column               description of column in given table
 * @param string  $column_name_appendix the name attribute
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data                 data to edit
 * @param array   $column_enum_values   $column['values']
 *
 * @return string                       an html snippet
 */
function PMA_getDropDownDependingOnLength(
    $column, $column_name_appendix, $unnullify_trigger,
    $tabindex, $tabindex_for_value, $idindex, $data, $column_enum_values
) {
    $html_output = '<select name="fields' . $column_name_appendix . '"'
        . ' ' . $unnullify_trigger
        . ' class="textfield"'
        . ' tabindex="' . ($tabindex + $tabindex_for_value) . '"'
        . ' id="field_' . ($idindex) . '_3">';
    $html_output .= '<option value="">&nbsp;</option>' . "\n";

    foreach ($column_enum_values as $enum_value) {
        $html_output .= '<option value="' . $enum_value['html'] . '"';
        if ($data == $enum_value['plain']
            || ($data == ''
            && (! isset($_REQUEST['where_clause']) || $column['Null'] != 'YES')
            && isset($column['Default'])
            && $enum_value['plain'] == $column['Default'])
        ) {
            $html_output .= ' selected="selected"';
        }
        $html_output .= '>' . $enum_value['html'] . '</option>' . "\n";
    }
    $html_output .= '</select>';
    return $html_output;
}

/**
 * Get HTML radio button for less than 20 string length
 *
 * @param string  $column_name_appendix the name attribute
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param array   $column               description of column in given table
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data                 data to edit
 * @param array   $column_enum_values   $column['values']
 *
 * @return string                       an html snippet
 */
function PMA_getRadioButtonDependingOnLength(
    $column_name_appendix, $unnullify_trigger,
    $tabindex, $column, $tabindex_for_value, $idindex, $data, $column_enum_values
) {
    $j = 0;
    $html_output = '';
    foreach ($column_enum_values as $enum_value) {
        $html_output .= '            '
            . '<input type="radio" name="fields' . $column_name_appendix . '"'
            . ' class="textfield"'
            . ' value="' . $enum_value['html'] . '"'
            . ' id="field_' . ($idindex) . '_3_'  . $j . '"'
            . ' ' . $unnullify_trigger;
        if ($data == $enum_value['plain']
            || ($data == ''
            && (! isset($_REQUEST['where_clause']) || $column['Null'] != 'YES')
            && isset($column['Default'])
            && $enum_value['plain'] == $column['Default'])
        ) {
            $html_output .= ' checked="checked"';
        }
        $html_output .= ' tabindex="' . ($tabindex + $tabindex_for_value) . '" />';
        $html_output .= '<label for="field_' . $idindex . '_3_' . $j . '">'
            . $enum_value['html'] . '</label>' . "\n";
        $j++;
    }
    return $html_output;
}

/**
 * Get the HTML for 'set' pma type
 *
 * @param array   $column               description of column in given table
 * @param array   $extracted_columnspec associative array containing type,
 *                                      spec_in_brackets and possibly
 *                                      enum_set_values (another array)
 * @param string  $backup_field         hidden input field
 * @param string  $column_name_appendix the name attribute
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data                 description of the column field
 *
 * @return string                       an html snippet
 */
function PMA_getPmaTypeSet(
    $column, $extracted_columnspec, $backup_field,
    $column_name_appendix, $unnullify_trigger, $tabindex,
    $tabindex_for_value, $idindex, $data
) {
    list($column_set_values, $select_size) = PMA_getColumnSetValueAndSelectSize(
        $column, $extracted_columnspec
    );
    $vset = array_flip(explode(',', $data));
    $html_output = $backup_field . "\n";
    $html_output .= '<input type="hidden" name="fields_type'
        . $column_name_appendix . '" value="set" />';
    $html_output .= '<select name="fields' . $column_name_appendix . '[]' . '"'
        . ' class="textfield"'
        . ' size="' . $select_size . '"'
        . ' multiple="multiple"'
        . ' ' . $unnullify_trigger
        . ' tabindex="' . ($tabindex + $tabindex_for_value) . '"'
        . ' id="field_' . ($idindex) . '_3">';
    foreach ($column_set_values as $column_set_value) {
        $html_output .= '<option value="' . $column_set_value['html'] . '"';
        if (isset($vset[$column_set_value['plain']])) {
            $html_output .= ' selected="selected"';
        }
        $html_output .= '>' . $column_set_value['html'] . '</option>' . "\n";
    }
    $html_output .= '</select>';
    return $html_output;
}

/**
 * Retrieve column 'set' value and select size
 *
 * @param array $column               description of column in given table
 * @param array $extracted_columnspec associative array containing type,
 *                                    spec_in_brackets and possibly enum_set_values
 *                                    (another array)
 *
 * @return array $column['values'], $column['select_size']
 */
function PMA_getColumnSetValueAndSelectSize($column, $extracted_columnspec)
{
    if (! isset($column['values'])) {
        $column['values'] = array();
        foreach ($extracted_columnspec['enum_set_values'] as $val) {
            $column['values'][] = array(
                'plain' => $val,
                'html'  => htmlspecialchars($val),
            );
        }
        $column['select_size'] = min(4, count($column['values']));
    }
    return array($column['values'], $column['select_size']);
}

/**
 * Get HTML for binary and blob column
 *
 * @param array   $column                description of column in given table
 * @param string  $data                  data to edit
 * @param string  $special_chars         special characters
 * @param integer $biggest_max_file_size biggest max file size for uploading
 * @param string  $backup_field          hidden input field
 * @param string  $column_name_appendix  the name attribute
 * @param string  $unnullify_trigger     validation string
 * @param integer $tabindex              tab index
 * @param integer $tabindex_for_value    offset for the values tabindex
 * @param integer $idindex               id index
 * @param string  $text_dir              text direction
 * @param string  $special_chars_encoded replaced char if the string starts
 *                                       with a \r\n pair (0x0d0a) add an extra \n
 * @param string  $vkey                  [multi_edit]['row_id']
 * @param boolean $is_upload             is upload or not
 *
 * @return string                           an html snippet
 */
function PMA_getBinaryAndBlobColumn(
    $column, $data, $special_chars, $biggest_max_file_size,
    $backup_field, $column_name_appendix, $unnullify_trigger, $tabindex,
    $tabindex_for_value, $idindex, $text_dir, $special_chars_encoded,
    $vkey, $is_upload
) {
    $html_output = '';
    // Add field type : Protected or Hexadecimal
    $fields_type_html = '<input type="hidden" name="fields_type'
        . $column_name_appendix . '" value="%s" />';
    // Default value : hex
    $fields_type_val = 'hex';
    if (($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'])
        || ($GLOBALS['cfg']['ProtectBinary'] === 'all')
        || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && !$column['is_blob'])
    ) {
        $html_output .= __('Binary - do not edit');
        if (isset($data)) {
            $data_size = PMA_Util::formatByteDown(
                /*overload*/mb_strlen(stripslashes($data)), 3, 1
            );
            $html_output .= ' (' . $data_size[0] . ' ' . $data_size[1] . ')';
            unset($data_size);
        }
        $fields_type_val = 'protected';
        $html_output .= '<input type="hidden" name="fields'
            . $column_name_appendix . '" value="" />';
    } elseif ($column['is_blob']
        || ($column['len'] > $GLOBALS['cfg']['LimitChars'])
    ) {
        $html_output .= "\n" . PMA_getTextarea(
            $column, $backup_field, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $text_dir,
            $special_chars_encoded, 'HEX'
        );
    } else {
        // field size should be at least 4 and max $GLOBALS['cfg']['LimitChars']
        $fieldsize = min(max($column['len'], 4), $GLOBALS['cfg']['LimitChars']);
        $html_output .= "\n" . $backup_field . "\n" . PMA_getHTMLinput(
            $column, $column_name_appendix, $special_chars, $fieldsize,
            $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, 'HEX'
        );
    }
    $html_output .= sprintf($fields_type_html, $fields_type_val);

    if ($is_upload && $column['is_blob']) {
        $html_output .= '<br />'
            . '<input type="file"'
            . ' name="fields_upload' . $vkey . '[' . $column['Field_md5'] . ']"'
            . ' class="textfield" id="field_' . $idindex . '_3" size="10"'
            . ' ' . $unnullify_trigger . '/>&nbsp;';
        list($html_out,) = PMA_getMaxUploadSize(
            $column, $biggest_max_file_size
        );
        $html_output .= $html_out;
    }

    if (!empty($GLOBALS['cfg']['UploadDir'])) {
        $html_output .= PMA_getSelectOptionForUpload($vkey, $column);
    }

    return $html_output;
}

/**
 * Get HTML input type
 *
 * @param array   $column               description of column in given table
 * @param string  $column_name_appendix the name attribute
 * @param string  $special_chars        special characters
 * @param integer $fieldsize            html field size
 * @param string  $unnullify_trigger    validation string
 * @param integer $tabindex             tab index
 * @param integer $tabindex_for_value   offset for the values tabindex
 * @param integer $idindex              id index
 * @param string  $data_type            the html5 data-* attribute type
 *
 * @return string                       an html snippet
 */
function PMA_getHTMLinput(
    $column, $column_name_appendix, $special_chars, $fieldsize, $unnullify_trigger,
    $tabindex, $tabindex_for_value, $idindex, $data_type
) {
    $input_type = 'text';
    // do not use the 'date' or 'time' types here; they have no effect on some
    // browsers and create side effects (see bug #4218)

    $the_class = 'textfield';
    // verify True_Type which does not contain the parentheses and length
    if ($column['True_Type'] === 'date') {
        $the_class .= ' datefield';
    } else if ($column['True_Type'] === 'time') {
        $the_class .= ' timefield';
    } else if ($column['True_Type'] === 'datetime'
        || $column['True_Type'] === 'timestamp'
    ) {
        $the_class .= ' datetimefield';
    }
    $input_min_max = false;
    if (in_array($column['True_Type'], $GLOBALS['PMA_Types']->getIntegerTypes())) {
        $extracted_columnspec = PMA_Util::extractColumnSpec($column['Type']);
        $is_unsigned = $extracted_columnspec['unsigned'];
        $min_max_values = $GLOBALS['PMA_Types']->getIntegerRange(
            $column['True_Type'], ! $is_unsigned
        );
        $input_min_max = 'min="' . $min_max_values[0] . '" '
            . 'max="' . $min_max_values[1] . '"';
        $data_type = 'INT';
    }
    return '<input type="' . $input_type . '"'
        . ' name="fields' . $column_name_appendix . '"'
        . ' value="' . $special_chars . '" size="' . $fieldsize . '"'
        . ((isset($column['is_char']) && $column['is_char'])
        ? ' data-maxlength="' . $fieldsize . '"'
        : '')
        . ($input_min_max !== false ? ' ' . $input_min_max : '')
        . ' data-type="' . $data_type . '"'
        . ($input_type === 'time' ? ' step="1"' : '')
        . ' class="' . $the_class . '" ' . $unnullify_trigger
        . ' tabindex="' . ($tabindex + $tabindex_for_value) . '"'
        . ' id="field_' . ($idindex) . '_3" />';
}

/**
 * Get HTML select option for upload
 *
 * @param string $vkey   [multi_edit]['row_id']
 * @param array  $column description of column in given table
 *
 * @return string|void an html snippet
 */
function PMA_getSelectOptionForUpload($vkey, $column)
{
    $files = PMA_getFileSelectOptions(
        PMA_Util::userDir($GLOBALS['cfg']['UploadDir'])
    );

    if ($files === false) {
        return '<font color="red">' . __('Error') . '</font><br />' . "\n"
            .  __('The directory you set for upload work cannot be reached.') . "\n";
    } elseif (!empty($files)) {
        return "<br />\n"
            . '<i>' . __('Or') . '</i>' . ' '
            . __('web server upload directory:') . '<br />' . "\n"
            . '<select size="1" name="fields_uploadlocal'
            . $vkey . '[' . $column['Field_md5'] . ']">' . "\n"
            . '<option value="" selected="selected"></option>' . "\n"
            . $files
            . '</select>' . "\n";
    }

    return null;
}

/**
 * Retrieve the maximum upload file size
 *
 * @param array   $column                description of column in given table
 * @param integer $biggest_max_file_size biggest max file size for uploading
 *
 * @return array an html snippet and $biggest_max_file_size
 */
function PMA_getMaxUploadSize($column, $biggest_max_file_size)
{
    // find maximum upload size, based on field type
    /**
     * @todo with functions this is not so easy, as you can basically
     * process any data with function like MD5
     */
    global $max_upload_size;
    $max_field_sizes = array(
        'tinyblob'   =>        '256',
        'blob'       =>      '65536',
        'mediumblob' =>   '16777216',
        'longblob'   => '4294967296' // yeah, really
    );

    $this_field_max_size = $max_upload_size; // from PHP max
    if ($this_field_max_size > $max_field_sizes[$column['pma_type']]) {
        $this_field_max_size = $max_field_sizes[$column['pma_type']];
    }
    $html_output
        = PMA_Util::getFormattedMaximumUploadSize(
            $this_field_max_size
        ) . "\n";
    // do not generate here the MAX_FILE_SIZE, because we should
    // put only one in the form to accommodate the biggest field
    if ($this_field_max_size > $biggest_max_file_size) {
        $biggest_max_file_size = $this_field_max_size;
    }
    return array($html_output, $biggest_max_file_size);
}

/**
 * Get HTML for the Value column of other datatypes
 * (here, "column" is used in the sense of HTML column in HTML table)
 *
 * @param array   $column                description of column in given table
 * @param string  $default_char_editing  default char editing mode which is stored
 *                                       in the config.inc.php script
 * @param string  $backup_field          hidden input field
 * @param string  $column_name_appendix  the name attribute
 * @param string  $unnullify_trigger     validation string
 * @param integer $tabindex              tab index
 * @param string  $special_chars         special characters
 * @param integer $tabindex_for_value    offset for the values tabindex
 * @param integer $idindex               id index
 * @param string  $text_dir              text direction
 * @param string  $special_chars_encoded replaced char if the string starts
 *                                       with a \r\n pair (0x0d0a) add an extra \n
 * @param string  $data                  data to edit
 * @param array   $extracted_columnspec  associative array containing type,
 *                                       spec_in_brackets and possibly
 *                                       enum_set_values (another array)
 *
 * @return string an html snippet
 */
function PMA_getValueColumnForOtherDatatypes($column, $default_char_editing,
    $backup_field,
    $column_name_appendix, $unnullify_trigger, $tabindex, $special_chars,
    $tabindex_for_value, $idindex, $text_dir, $special_chars_encoded, $data,
    $extracted_columnspec
) {
    // HTML5 data-* attribute data-type
    $data_type = $GLOBALS['PMA_Types']->getTypeClass($column['True_Type']);
    $fieldsize = PMA_getColumnSize($column, $extracted_columnspec);
    $html_output = $backup_field . "\n";
    if ($column['is_char']
        && ($GLOBALS['cfg']['CharEditing'] == 'textarea'
        || /*overload*/mb_strpos($data, "\n") !== false)
    ) {
        $html_output .= "\n";
        $GLOBALS['cfg']['CharEditing'] = $default_char_editing;
        $html_output .= PMA_getTextarea(
            $column, $backup_field, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $text_dir,
            $special_chars_encoded, $data_type
        );
    } else {
        $html_output .= PMA_getHTMLinput(
            $column, $column_name_appendix, $special_chars, $fieldsize,
            $unnullify_trigger, $tabindex, $tabindex_for_value, $idindex, $data_type
        );

        if ($column['Extra'] == 'auto_increment') {
            $html_output .= '<input type="hidden" name="auto_increment'
                . $column_name_appendix . '" value="1" />';
        }
        if (substr($column['pma_type'], 0, 9) == 'timestamp') {
            $html_output .= '<input type="hidden" name="fields_type'
                . $column_name_appendix . '" value="timestamp" />';
        }
        if (substr($column['pma_type'], 0, 8) == 'datetime') {
            $html_output .= '<input type="hidden" name="fields_type'
                . $column_name_appendix . '" value="datetime" />';
        }
        if ($column['True_Type'] == 'bit') {
            $html_output .= '<input type="hidden" name="fields_type'
                . $column_name_appendix . '" value="bit" />';
        }
        if ($column['pma_type'] == 'date'
            || $column['pma_type'] == 'datetime'
            || substr($column['pma_type'], 0, 9) == 'timestamp'
        ) {
            // the _3 suffix points to the date field
            // the _2 suffix points to the corresponding NULL checkbox
            // in dateFormat, 'yy' means the year with 4 digits
        }
    }
    return $html_output;
}

/**
 * Get the field size
 *
 * @param array $column               description of column in given table
 * @param array $extracted_columnspec associative array containing type,
 *                                    spec_in_brackets and possibly enum_set_values
 *                                    (another array)
 *
 * @return integer      field size
 */
function PMA_getColumnSize($column, $extracted_columnspec)
{
    if ($column['is_char']) {
        $fieldsize = $extracted_columnspec['spec_in_brackets'];
        if ($fieldsize > $GLOBALS['cfg']['MaxSizeForInputField']) {
            /**
             * This case happens for CHAR or VARCHAR columns which have
             * a size larger than the maximum size for input field.
             */
            $GLOBALS['cfg']['CharEditing'] = 'textarea';
        }
    } else {
        /**
         * This case happens for example for INT or DATE columns;
         * in these situations, the value returned in $column['len']
         * seems appropriate.
         */
        $fieldsize = $column['len'];
    }
    return min(
        max($fieldsize, $GLOBALS['cfg']['MinSizeForInputField']),
        $GLOBALS['cfg']['MaxSizeForInputField']
    );
}

/**
 * Get HTML for gis data types
 *
 * @return string an html snippet
 */
function PMA_getHTMLforGisDataTypes()
{
    $edit_str = PMA_Util::getIcon('b_edit.png', __('Edit/Insert'));
    return '<span class="open_gis_editor">'
        . PMA_Util::linkOrButton(
            '#', $edit_str, array(), false, false, '_blank'
        )
        . '</span>';
}

/**
 * get html for continue insertion form
 *
 * @param string $table              name of the table
 * @param string $db                 name of the database
 * @param array  $where_clause_array array of where clauses
 * @param string $err_url            error url
 *
 * @return string                   an html snippet
 */
function PMA_getContinueInsertionForm($table, $db, $where_clause_array, $err_url)
{
    $html_output = '<form id="continueForm" method="post"'
        . ' action="tbl_replace.php" name="continueForm">'
        . PMA_URL_getHiddenInputs($db, $table)
        . '<input type="hidden" name="goto"'
        . ' value="' . htmlspecialchars($GLOBALS['goto']) . '" />'
        . '<input type="hidden" name="err_url"'
        . ' value="' . htmlspecialchars($err_url) . '" />'
        . '<input type="hidden" name="sql_query"'
        . ' value="' . htmlspecialchars($_REQUEST['sql_query']) . '" />';

    if (isset($_REQUEST['where_clause'])) {
        foreach ($where_clause_array as $key_id => $where_clause) {

            $html_output .= '<input type="hidden"'
                . ' name="where_clause[' . $key_id . ']"'
                . ' value="' . htmlspecialchars(trim($where_clause)) . '" />' . "\n";
        }
    }
    $tmp = '<select name="insert_rows" id="insert_rows">' . "\n";
    $option_values = array(1, 2, 5, 10, 15, 20, 30, 40);

    foreach ($option_values as $value) {
        $tmp .= '<option value="' . $value . '"';
        if ($value == $GLOBALS['cfg']['InsertRows']) {
            $tmp .= ' selected="selected"';
        }
        $tmp .= '>' . $value . '</option>' . "\n";
    }

    $tmp .= '</select>' . "\n";
    $html_output .= "\n" . sprintf(__('Continue insertion with %s rows'), $tmp);
    unset($tmp);
    $html_output .= '</form>' . "\n";
    return $html_output;
}

/**
 * Get action panel
 *
 * @param array   $where_clause       where clause
 * @param string  $after_insert       insert mode, e.g. new_insert, same_insert
 * @param integer $tabindex           tab index
 * @param integer $tabindex_for_value offset for the values tabindex
 * @param boolean $found_unique_key   boolean variable for unique key
 *
 * @return string an html snippet
 */
function PMA_getActionsPanel($where_clause, $after_insert, $tabindex,
    $tabindex_for_value, $found_unique_key
) {
    $html_output = '<fieldset id="actions_panel">'
        . '<table cellpadding="5" cellspacing="0">'
        . '<tr>'
        . '<td class="nowrap vmiddle">'
        . PMA_getSubmitTypeDropDown($where_clause, $tabindex, $tabindex_for_value)
        . "\n";

    $html_output .= '</td>'
        . '<td class="vmiddle">'
        . '&nbsp;&nbsp;&nbsp;<strong>'
        . __('and then') . '</strong>&nbsp;&nbsp;&nbsp;'
        . '</td>'
        . '<td class="nowrap vmiddle">'
        . PMA_getAfterInsertDropDown(
            $where_clause, $after_insert, $found_unique_key
        )
        . '</td>'
        . '</tr>';
    $html_output .='<tr>'
        . PMA_getSubmitAndResetButtonForActionsPanel($tabindex, $tabindex_for_value)
        . '</tr>'
        . '</table>'
        . '</fieldset>';
    return $html_output;
}

/**
 * Get a HTML drop down for submit types
 *
 * @param array   $where_clause       where clause
 * @param integer $tabindex           tab index
 * @param integer $tabindex_for_value offset for the values tabindex
 *
 * @return string                       an html snippet
 */
function PMA_getSubmitTypeDropDown($where_clause, $tabindex, $tabindex_for_value)
{
    $html_output = '<select name="submit_type" class="control_at_footer" tabindex="'
        . ($tabindex + $tabindex_for_value + 1) . '">';
    if (isset($where_clause)) {
        $html_output .= '<option value="save">' . __('Save') . '</option>';
    }
    $html_output .= '<option value="insert">'
        . __('Insert as new row')
        . '</option>'
        . '<option value="insertignore">'
        . __('Insert as new row and ignore errors')
        . '</option>'
        . '<option value="showinsert">'
        . __('Show insert query')
        . '</option>'
        . '</select>';
    return $html_output;
}

/**
 * Get HTML drop down for after insert
 *
 * @param array   $where_clause     where clause
 * @param string  $after_insert     insert mode, e.g. new_insert, same_insert
 * @param boolean $found_unique_key boolean variable for unique key
 *
 * @return string                   an html snippet
 */
function PMA_getAfterInsertDropDown($where_clause, $after_insert, $found_unique_key)
{
    $html_output = '<select name="after_insert" class="control_at_footer">'
        . '<option value="back" '
        . ($after_insert == 'back' ? 'selected="selected"' : '') . '>'
        . __('Go back to previous page') . '</option>'
        . '<option value="new_insert" '
        . ($after_insert == 'new_insert' ? 'selected="selected"' : '') . '>'
        . __('Insert another new row') . '</option>';

    if (isset($where_clause)) {
        $html_output .= '<option value="same_insert" '
            . ($after_insert == 'same_insert' ? 'selected="selected"' : '') . '>'
            . __('Go back to this page') . '</option>';

        // If we have just numeric primary key, we can also edit next
        // in 2.8.2, we were looking for `field_name` = numeric_value
        //if (preg_match('@^[\s]*`[^`]*` = [0-9]+@', $where_clause)) {
        // in 2.9.0, we are looking for `table_name`.`field_name` = numeric_value
        $is_numeric = false;
        if (! is_array($where_clause)) {
            $where_clause = array($where_clause);
        }
        for ($i = 0, $nb = count($where_clause); $i < $nb; $i++) {
            $is_numeric = preg_match(
                '@^[\s]*`[^`]*`[\.]`[^`]*` = [0-9]+@',
                $where_clause[$i]
            );
            if ($is_numeric == true) {
                break;
            }
        }
        if ($found_unique_key && $is_numeric) {
            $html_output .= '<option value="edit_next" '
                . ($after_insert == 'edit_next' ? 'selected="selected"' : '') . '>'
                . __('Edit next row') . '</option>';

        }
    }
    $html_output .= '</select>';
    return $html_output;

}

/**
 * get Submit button and Reset button for action panel
 *
 * @param integer $tabindex           tab index
 * @param integer $tabindex_for_value offset for the values tabindex
 *
 * @return string an html snippet
 */
function PMA_getSubmitAndResetButtonForActionsPanel($tabindex, $tabindex_for_value)
{
    return '<td>'
    . PMA_Util::showHint(
        __(
            'Use TAB key to move from value to value,'
            . ' or CTRL+arrows to move anywhere'
        )
    )
    . '</td>'
    . '<td colspan="3" class="right vmiddle">'
    . '<input type="submit" class="control_at_footer" value="' . __('Go') . '"'
    . ' tabindex="' . ($tabindex + $tabindex_for_value + 6) . '" id="buttonYes" />'
    . '<input type="button" class="preview_sql" value="' . __('Preview SQL') . '"'
    . ' tabindex="' . ($tabindex + $tabindex_for_value + 7) . '" />'
    . '<input type="reset" class="control_at_footer" value="' . __('Reset') . '"'
    . ' tabindex="' . ($tabindex + $tabindex_for_value + 8) . '" />'
    . '</td>';
}

/**
 * Get table head and table foot for insert row table
 *
 * @param array $url_params url parameters
 *
 * @return string           an html snippet
 */
function PMA_getHeadAndFootOfInsertRowTable($url_params)
{
    $html_output = '<table class="insertRowTable topmargin">'
        . '<thead>'
        . '<tr>'
        . '<th>' . __('Column') . '</th>';

    if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
        $html_output .= PMA_showTypeOrFunction('type', $url_params, true);
    }
    if ($GLOBALS['cfg']['ShowFunctionFields']) {
        $html_output .= PMA_showTypeOrFunction('function', $url_params, true);
    }

    $html_output .= '<th>' . __('Null') . '</th>'
        . '<th>' . __('Value') . '</th>'
        . '</tr>'
        . '</thead>'
        . ' <tfoot>'
        . '<tr>'
        . '<th colspan="5" class="tblFooters right">'
        . '<input type="submit" value="' . __('Go') . '" />'
        . '</th>'
        . '</tr>'
        . '</tfoot>';
    return $html_output;
}

/**
 * Prepares the field value and retrieve special chars, backup field and data array
 *
 * @param array   $current_row          a row of the table
 * @param array   $column               description of column in given table
 * @param array   $extracted_columnspec associative array containing type,
 *                                      spec_in_brackets and possibly
 *                                      enum_set_values (another array)
 * @param boolean $real_null_value      whether column value null or not null
 * @param array   $gis_data_types       list of GIS data types
 * @param string  $column_name_appendix string to append to column name in input
 * @param bool    $as_is                use the data as is, used in repopulating
 *
 * @return array $real_null_value, $data, $special_chars, $backup_field,
 *               $special_chars_encoded
 */
function PMA_getSpecialCharsAndBackupFieldForExistingRow(
    $current_row, $column, $extracted_columnspec,
    $real_null_value, $gis_data_types, $column_name_appendix, $as_is
) {
    $special_chars_encoded = '';
    $data = null;
    // (we are editing)
    if (!isset($current_row[$column['Field']])) {
        $real_null_value = true;
        $current_row[$column['Field']] = '';
        $special_chars = '';
        $data = $current_row[$column['Field']];
    } elseif ($column['True_Type'] == 'bit') {
        $special_chars = $as_is
            ? $current_row[$column['Field']]
            : PMA_Util::printableBitValue(
                $current_row[$column['Field']],
                $extracted_columnspec['spec_in_brackets']
            );
    } elseif ((substr($column['True_Type'], 0, 9) == 'timestamp'
        || $column['True_Type'] == 'datetime'
        || $column['True_Type'] == 'time')
        && (/*overload*/mb_strpos($current_row[$column['Field']], ".") !== false)
    ) {
        $current_row[$column['Field']] = $as_is
            ? $current_row[$column['Field']]
            : PMA_Util::addMicroseconds(
                $current_row[$column['Field']]
            );
        $special_chars = htmlspecialchars($current_row[$column['Field']]);
    } elseif (in_array($column['True_Type'], $gis_data_types)) {
        // Convert gis data to Well Know Text format
        $current_row[$column['Field']] = $as_is
            ? $current_row[$column['Field']]
            : PMA_Util::asWKT(
                $current_row[$column['Field']], true
            );
        $special_chars = htmlspecialchars($current_row[$column['Field']]);
    } else {
        // special binary "characters"
        if ($column['is_binary']
            || ($column['is_blob'] && $GLOBALS['cfg']['ProtectBinary'] !== 'all')
        ) {
            $current_row[$column['Field']] = $as_is
                ? $current_row[$column['Field']]
                : bin2hex(
                    $current_row[$column['Field']]
                );
        } // end if
        $special_chars = htmlspecialchars($current_row[$column['Field']]);

        //We need to duplicate the first \n or otherwise we will lose
        //the first newline entered in a VARCHAR or TEXT column
        $special_chars_encoded
            = PMA_Util::duplicateFirstNewline($special_chars);

        $data = $current_row[$column['Field']];
    } // end if... else...

    //when copying row, it is useful to empty auto-increment column
    // to prevent duplicate key error
    if (isset($_REQUEST['default_action'])
        && $_REQUEST['default_action'] === 'insert'
    ) {
        if ($column['Key'] === 'PRI'
            && /*overload*/mb_strpos($column['Extra'], 'auto_increment') !== false
        ) {
            $data = $special_chars_encoded = $special_chars = null;
        }
    }
    // If a timestamp field value is not included in an update
    // statement MySQL auto-update it to the current timestamp;
    // however, things have changed since MySQL 4.1, so
    // it's better to set a fields_prev in this situation
    $backup_field = '<input type="hidden" name="fields_prev'
        . $column_name_appendix . '" value="'
        . htmlspecialchars($current_row[$column['Field']]) . '" />';

    return array(
        $real_null_value,
        $special_chars_encoded,
        $special_chars,
        $data,
        $backup_field
    );
}

/**
 * display default values
 *
 * @param array   $column          description of column in given table
 * @param boolean $real_null_value whether column value null or not null
 *
 * @return array $real_null_value, $data, $special_chars,
 *               $backup_field, $special_chars_encoded
 */
function PMA_getSpecialCharsAndBackupFieldForInsertingMode(
    $column, $real_null_value
) {
    if (! isset($column['Default'])) {
        $column['Default']    = '';
        $real_null_value          = true;
        $data                     = '';
    } else {
        $data                     = $column['Default'];
    }

    $trueType = $column['True_Type'];

    if ($trueType == 'bit') {
        $special_chars = PMA_Util::convertBitDefaultValue($column['Default']);
    } elseif (substr($trueType, 0, 9) == 'timestamp'
        || $trueType == 'datetime'
        || $trueType == 'time'
    ) {
        $special_chars = PMA_Util::addMicroseconds($column['Default']);
    } else {
        $special_chars = htmlspecialchars($column['Default']);
    }
    $backup_field = '';
    $special_chars_encoded = PMA_Util::duplicateFirstNewline($special_chars);
    return array(
        $real_null_value, $data, $special_chars,
        $backup_field, $special_chars_encoded
    );
}

/**
 * Prepares the update/insert of a row
 *
 * @return array     $loop_array, $using_key, $is_insert, $is_insertignore
 */
function PMA_getParamsForUpdateOrInsert()
{
    if (isset($_REQUEST['where_clause'])) {
        // we were editing something => use the WHERE clause
        $loop_array = is_array($_REQUEST['where_clause'])
            ? $_REQUEST['where_clause']
            : array($_REQUEST['where_clause']);
        $using_key  = true;
        $is_insert  = $_REQUEST['submit_type'] == 'insert'
                      || $_REQUEST['submit_type'] == 'showinsert'
                      || $_REQUEST['submit_type'] == 'insertignore';
    } else {
        // new row => use indexes
        $loop_array = array();
        if (! empty($_REQUEST['fields'])) {
            foreach ($_REQUEST['fields']['multi_edit'] as $key => $dummy) {
                $loop_array[] = $key;
            }
        }
        $using_key  = false;
        $is_insert  = true;
    }
    $is_insertignore  = $_REQUEST['submit_type'] == 'insertignore';
    return array($loop_array, $using_key, $is_insert, $is_insertignore);
}

/**
 * Check wether insert row mode and if so include tbl_changen script and set
 * global variables.
 *
 * @return void
 */
function PMA_isInsertRow()
{
    if (isset($_REQUEST['insert_rows'])
        && is_numeric($_REQUEST['insert_rows'])
        && $_REQUEST['insert_rows'] != $GLOBALS['cfg']['InsertRows']
    ) {
        $GLOBALS['cfg']['InsertRows'] = $_REQUEST['insert_rows'];
        $response = PMA_Response::getInstance();
        $header = $response->getHeader();
        $scripts = $header->getScripts();
        $scripts->addFile('tbl_change.js');
        if (!defined('TESTSUITE')) {
            include 'tbl_change.php';
            exit;
        }
    }
}

/**
 * set $_SESSION for edit_next
 *
 * @param string $one_where_clause one where clause from where clauses array
 *
 * @return void
 */
function PMA_setSessionForEditNext($one_where_clause)
{
    $local_query = 'SELECT * FROM ' . PMA_Util::backquote($GLOBALS['db'])
        . '.' . PMA_Util::backquote($GLOBALS['table']) . ' WHERE '
        . str_replace('` =', '` >', $one_where_clause) . ' LIMIT 1;';

    $res            = $GLOBALS['dbi']->query($local_query);
    $row            = $GLOBALS['dbi']->fetchRow($res);
    $meta           = $GLOBALS['dbi']->getFieldsMeta($res);
    // must find a unique condition based on unique key,
    // not a combination of all fields
    list($unique_condition, $clause_is_unique)
        = PMA_Util::getUniqueCondition(
            $res, count($meta), $meta, $row, true
        );
    if (! empty($unique_condition)) {
        $_SESSION['edit_next'] = $unique_condition;
    }
    unset($unique_condition, $clause_is_unique);
}

/**
 * set $goto_include variable for different cases and retrieve like,
 * if $GLOBALS['goto'] empty, if $goto_include previously not defined
 * and new_insert, same_insert, edit_next
 *
 * @param string $goto_include store some script for include, otherwise it is
 *                             boolean false
 *
 * @return string               $goto_include
 */
function PMA_getGotoInclude($goto_include)
{
    $valid_options = array('new_insert', 'same_insert', 'edit_next');
    if (isset($_REQUEST['after_insert'])
        && in_array($_REQUEST['after_insert'], $valid_options)
    ) {
        $goto_include = 'tbl_change.php';
    } elseif (! empty($GLOBALS['goto'])) {
        if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
            // this should NOT happen
            //$GLOBALS['goto'] = false;
            $goto_include = false;
        } else {
            $goto_include = $GLOBALS['goto'];
        }
        if ($GLOBALS['goto'] == 'db_sql.php'
            && /*overload*/mb_strlen($GLOBALS['table'])
        ) {
            $GLOBALS['table'] = '';
        }
    }
    if (! $goto_include) {
        if (! /*overload*/mb_strlen($GLOBALS['table'])) {
            $goto_include = 'db_sql.php';
        } else {
            $goto_include = 'tbl_sql.php';
        }
    }
    return $goto_include;
}

/**
 * Defines the url to return in case of failure of the query
 *
 * @param array $url_params url parameters
 *
 * @return string           error url for query failure
 */
function PMA_getErrorUrl($url_params)
{
    if (isset($_REQUEST['err_url'])) {
        return $_REQUEST['err_url'];
    } else {
        return 'tbl_change.php' . PMA_URL_getCommon($url_params);
    }
}

/**
 * Builds the sql query
 *
 * @param boolean $is_insertignore $_REQUEST['submit_type'] == 'insertignore'
 * @param array   $query_fields    column names array
 * @param array   $value_sets      array of query values
 *
 * @return array of query
 */
function PMA_buildSqlQuery($is_insertignore, $query_fields, $value_sets)
{
    if ($is_insertignore) {
        $insert_command = 'INSERT IGNORE ';
    } else {
        $insert_command = 'INSERT ';
    }
    $query = array(
        $insert_command . 'INTO '
        . PMA_Util::backquote($GLOBALS['db']) . '.'
        . PMA_Util::backquote($GLOBALS['table'])
        . ' (' . implode(', ', $query_fields) . ') VALUES ('
        . implode('), (', $value_sets) . ')'
    );
    unset($insert_command, $query_fields);
    return $query;
}

/**
 * Executes the sql query and get the result, then move back to the calling page
 *
 * @param array $url_params url parameters array
 * @param array $query      built query from PMA_buildSqlQuery()
 *
 * @return array            $url_params, $total_affected_rows, $last_messages
 *                          $warning_messages, $error_messages, $return_to_sql_query
 */
function PMA_executeSqlQuery($url_params, $query)
{
    $return_to_sql_query = '';
    if (! empty($GLOBALS['sql_query'])) {
        $url_params['sql_query'] = $GLOBALS['sql_query'];
        $return_to_sql_query = $GLOBALS['sql_query'];
    }
    $GLOBALS['sql_query'] = implode('; ', $query) . ';';
    // to ensure that the query is displayed in case of
    // "insert as new row" and then "insert another new row"
    $GLOBALS['display_query'] = $GLOBALS['sql_query'];

    $total_affected_rows = 0;
    $last_messages = array();
    $warning_messages = array();
    $error_messages = array();

    foreach ($query as $single_query) {
        if ($_REQUEST['submit_type'] == 'showinsert') {
            $last_messages[] = PMA_Message::notice(__('Showing SQL query'));
            continue;
        }
        if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
            $result = $GLOBALS['dbi']->tryQuery($single_query);
        } else {
            $result = $GLOBALS['dbi']->query($single_query);
        }
        if (! $result) {
            $error_messages[] = PMA_Message::sanitize($GLOBALS['dbi']->getError());
        } else {
            // The next line contains a real assignment, it's not a typo
            if ($tmp = @$GLOBALS['dbi']->affectedRows()) {
                $total_affected_rows += $tmp;
            }
            unset($tmp);

            $insert_id = $GLOBALS['dbi']->insertId();
            if ($insert_id != 0) {
                // insert_id is id of FIRST record inserted in one insert, so if we
                // inserted multiple rows, we had to increment this

                if ($total_affected_rows > 0) {
                    $insert_id = $insert_id + $total_affected_rows - 1;
                }
                $last_message = PMA_Message::notice(__('Inserted row id: %1$d'));
                $last_message->addParam($insert_id);
                $last_messages[] = $last_message;
            }
            $GLOBALS['dbi']->freeResult($result);
        }
        $warning_messages = PMA_getWarningMessages();
    }
    return array(
        $url_params,
        $total_affected_rows,
        $last_messages,
        $warning_messages,
        $error_messages,
        $return_to_sql_query
    );
}

/**
 * get the warning messages array
 *
 * @return array  $warning_essages
 */
function PMA_getWarningMessages()
{
    $warning_essages = array();
    foreach ($GLOBALS['dbi']->getWarnings() as $warning) {
        $warning_essages[] = PMA_Message::sanitize(
            $warning['Level'] . ': #' . $warning['Code'] . ' ' . $warning['Message']
        );
    }
    return $warning_essages;
}

/**
 * Column to display from the foreign table?
 *
 * @param string $where_comparison string that contain relation field value
 * @param array  $map              all Relations to foreign tables for a given
 *                                 table or optionally a given column in a table
 * @param string $relation_field   relation field
 *
 * @return string $dispval display value from the foreign table
 */
function PMA_getDisplayValueForForeignTableColumn($where_comparison,
    $map, $relation_field
) {
    $foreigner = PMA_searchColumnInForeigners($map, $relation_field);
    $display_field = PMA_getDisplayField(
        $foreigner['foreign_db'],
        $foreigner['foreign_table']
    );
    // Field to display from the foreign table?
    if (isset($display_field) && /*overload*/mb_strlen($display_field)) {
        $dispsql = 'SELECT ' . PMA_Util::backquote($display_field)
            . ' FROM ' . PMA_Util::backquote($foreigner['foreign_db'])
            . '.' . PMA_Util::backquote($foreigner['foreign_table'])
            . ' WHERE ' . PMA_Util::backquote($foreigner['foreign_field'])
            . $where_comparison;
        $dispresult  = $GLOBALS['dbi']->tryQuery(
            $dispsql, null, PMA_DatabaseInterface::QUERY_STORE
        );
        if ($dispresult && $GLOBALS['dbi']->numRows($dispresult) > 0) {
            list($dispval) = $GLOBALS['dbi']->fetchRow($dispresult, 0);
        } else {
            $dispval = '';
        }
        @$GLOBALS['dbi']->freeResult($dispresult);
        return $dispval;
    }
    return '';
}

/**
 * Display option in the cell according to user choices
 *
 * @param array  $map                  all Relations to foreign tables for a given
 *                                     table or optionally a given column in a table
 * @param string $relation_field       relation field
 * @param string $where_comparison     string that contain relation field value
 * @param string $dispval              display value from the foreign table
 * @param string $relation_field_value relation field value
 *
 * @return string $output HTML <a> tag
 */
function PMA_getLinkForRelationalDisplayField($map, $relation_field,
    $where_comparison, $dispval, $relation_field_value
) {
    $foreigner = PMA_searchColumnInForeigners($map, $relation_field);
    if ('K' == $_SESSION['tmpval']['relational_display']) {
        // user chose "relational key" in the display options, so
        // the title contains the display field
        $title = (! empty($dispval))
            ? ' title="' . htmlspecialchars($dispval) . '"'
            : '';
    } else {
        $title = ' title="' . htmlspecialchars($relation_field_value) . '"';
    }
    $_url_params = array(
        'db'    => $foreigner['foreign_db'],
        'table' => $foreigner['foreign_table'],
        'pos'   => '0',
        'sql_query' => 'SELECT * FROM '
            . PMA_Util::backquote($foreigner['foreign_db'])
            . '.' . PMA_Util::backquote($foreigner['foreign_table'])
            . ' WHERE ' . PMA_Util::backquote($foreigner['foreign_field'])
            . $where_comparison
    );
    $output = '<a href="sql.php'
        . PMA_URL_getCommon($_url_params) . '"' . $title . '>';

    if ('D' == $_SESSION['tmpval']['relational_display']) {
        // user chose "relational display field" in the
        // display options, so show display field in the cell
        $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
    } else {
        // otherwise display data in the cell
        $output .= htmlspecialchars($relation_field_value);
    }
    $output .= '</a>';
    return $output;
}

/**
 * Transform edited values
 *
 * @param string $db             db name
 * @param string $table          table name
 * @param array  $transformation mimetypes for all columns of a table
 *                               [field_name][field_key]
 * @param array  &$edited_values transform columns list and new values
 * @param string $file           file containing the transformation plugin
 * @param string $column_name    column name
 * @param array  $extra_data     extra data array
 * @param string $type           the type of transformation
 *
 * @return array $extra_data
 */
function PMA_transformEditedValues($db, $table,
    $transformation, &$edited_values, $file, $column_name, $extra_data, $type
) {
    $include_file = 'libraries/plugins/transformations/' . $file;
    if (is_file($include_file)) {
        include_once $include_file;
        $_url_params = array(
            'db'            => $db,
            'table'         => $table,
            'where_clause'  => $_REQUEST['where_clause'],
            'transform_key' => $column_name
        );
        $transform_options  = PMA_Transformation_getOptions(
            isset($transformation[$type . '_options'])
            ? $transformation[$type . '_options']
            : ''
        );
        $transform_options['wrapper_link']
            = PMA_URL_getCommon($_url_params);
        $class_name = PMA_getTransformationClassName($file);
        $transformation_plugin = new $class_name();

        foreach ($edited_values as $cell_index => $curr_cell_edited_values) {
            if (isset($curr_cell_edited_values[$column_name])) {
                $edited_values[$cell_index][$column_name]
                    = $extra_data['transformations'][$cell_index]
                        = $transformation_plugin->applyTransformation(
                            $curr_cell_edited_values[$column_name],
                            $transform_options,
                            ''
                        );
            }
        }   // end of loop for each transformation cell
    }
    return $extra_data;
}

/**
 * Get current value in multi edit mode
 *
 * @param array  $multi_edit_funcs        multiple edit functions array
 * @param array  $multi_edit_salt         multiple edit array with encryption salt
 * @param array  $gis_from_text_functions array that contains gis from text functions
 * @param string $current_value           current value in the column
 * @param array  $gis_from_wkb_functions  initially $val is $multi_edit_columns[$key]
 * @param array  $func_optional_param     array('RAND','UNIX_TIMESTAMP')
 * @param array  $func_no_param           array of set of string
 * @param string $key                     an md5 of the column name
 *
 * @return array $cur_value
 */
function PMA_getCurrentValueAsAnArrayForMultipleEdit( $multi_edit_funcs,
    $multi_edit_salt,
    $gis_from_text_functions, $current_value, $gis_from_wkb_functions,
    $func_optional_param, $func_no_param, $key
) {
    if (empty($multi_edit_funcs[$key])) {
        return $current_value;
    } elseif ('UUID' === $multi_edit_funcs[$key]) {
        /* This way user will know what UUID new row has */
        $uuid = $GLOBALS['dbi']->fetchValue('SELECT UUID()');
        return "'" . $uuid . "'";
    } elseif ((in_array($multi_edit_funcs[$key], $gis_from_text_functions)
        && substr($current_value, 0, 3) == "'''")
        || in_array($multi_edit_funcs[$key], $gis_from_wkb_functions)
    ) {
        // Remove enclosing apostrophes
        $current_value = /*overload*/mb_substr($current_value, 1, -1);
        // Remove escaping apostrophes
        $current_value = str_replace("''", "'", $current_value);
        return $multi_edit_funcs[$key] . '(' . $current_value . ')';
    } elseif (! in_array($multi_edit_funcs[$key], $func_no_param)
        || ($current_value != "''"
        && in_array($multi_edit_funcs[$key], $func_optional_param))
    ) {
        if (isset($multi_edit_salt[$key])
            && ($multi_edit_funcs[$key] == "AES_ENCRYPT"
            || $multi_edit_funcs[$key] == "AES_DECRYPT")
        ) {
            return $multi_edit_funcs[$key] . '(' . $current_value . ",'"
                   . PMA_Util::sqlAddSlashes($multi_edit_salt[$key]) . "')";
        } else {
            return $multi_edit_funcs[$key] . '(' . $current_value . ')';
        }
    } else {
        return $multi_edit_funcs[$key] . '()';
    }
}

/**
 * Get query values array and query fields array for insert and update in multi edit
 *
 * @param array   $multi_edit_columns_name      multiple edit columns name array
 * @param array   $multi_edit_columns_null      multiple edit columns null array
 * @param string  $current_value                current value in the column in loop
 * @param array   $multi_edit_columns_prev      multiple edit previous columns array
 * @param array   $multi_edit_funcs             multiple edit functions array
 * @param boolean $is_insert                    boolean value whether insert or not
 * @param array   $query_values                 SET part of the sql query
 * @param array   $query_fields                 array of query fields
 * @param string  $current_value_as_an_array    current value in the column
 *                                              as an array
 * @param array   $value_sets                   array of valu sets
 * @param string  $key                          an md5 of the column name
 * @param array   $multi_edit_columns_null_prev array of multiple edit columns
 *                                              null previous
 *
 * @return array ($query_values, $query_fields)
 */
function PMA_getQueryValuesForInsertAndUpdateInMultipleEdit($multi_edit_columns_name,
    $multi_edit_columns_null, $current_value, $multi_edit_columns_prev,
    $multi_edit_funcs,$is_insert, $query_values, $query_fields,
    $current_value_as_an_array, $value_sets, $key, $multi_edit_columns_null_prev
) {
    //  i n s e r t
    if ($is_insert) {
        // no need to add column into the valuelist
        if (/*overload*/mb_strlen($current_value_as_an_array)) {
            $query_values[] = $current_value_as_an_array;
            // first inserted row so prepare the list of fields
            if (empty($value_sets)) {
                $query_fields[] = PMA_Util::backquote(
                    $multi_edit_columns_name[$key]
                );
            }
        }

    } elseif (! empty($multi_edit_columns_null_prev[$key])
        && ! isset($multi_edit_columns_null[$key])
    ) {
        //  u p d a t e

        // field had the null checkbox before the update
        // field no longer has the null checkbox
        $query_values[]
            = PMA_Util::backquote($multi_edit_columns_name[$key])
            . ' = ' . $current_value_as_an_array;
    } elseif (empty($multi_edit_funcs[$key])
        && isset($multi_edit_columns_prev[$key])
        && (("'" . PMA_Util::sqlAddSlashes($multi_edit_columns_prev[$key]) . "'" === $current_value)
        || ('0x' . $multi_edit_columns_prev[$key] === $current_value))
    ) {
        // No change for this column and no MySQL function is used -> next column
    } elseif (! empty($current_value)) {
        // avoid setting a field to NULL when it's already NULL
        // (field had the null checkbox before the update
        //  field still has the null checkbox)
        if (empty($multi_edit_columns_null_prev[$key])
            || empty($multi_edit_columns_null[$key])
        ) {
             $query_values[]
                 = PMA_Util::backquote($multi_edit_columns_name[$key])
                . ' = ' . $current_value_as_an_array;
        }
    }
    return array($query_values, $query_fields);
}

/**
 * Get the current column value in the form for different data types
 *
 * @param string|false $possibly_uploaded_val        uploaded file content
 * @param string       $key                          an md5 of the column name
 * @param array        $multi_edit_columns_type      array of multi edit column types
 * @param string       $current_value                current column value in the form
 * @param array        $multi_edit_auto_increment    multi edit auto increment
 * @param integer      $rownumber                    index of where clause array
 * @param array        $multi_edit_columns_name      multi edit column names array
 * @param array        $multi_edit_columns_null      multi edit columns null array
 * @param array        $multi_edit_columns_null_prev multi edit columns previous null
 * @param boolean      $is_insert                    whether insert or not
 * @param boolean      $using_key                    whether editing or new row
 * @param string       $where_clause                 where clause
 * @param string       $table                        table name
 *
 * @return string $current_value  current column value in the form
 */
function PMA_getCurrentValueForDifferentTypes($possibly_uploaded_val, $key,
    $multi_edit_columns_type, $current_value, $multi_edit_auto_increment,
    $rownumber, $multi_edit_columns_name, $multi_edit_columns_null,
    $multi_edit_columns_null_prev, $is_insert, $using_key, $where_clause, $table
) {
    // Fetch the current values of a row to use in case we have a protected field
    if ($is_insert
        && $using_key && isset($multi_edit_columns_type)
        && is_array($multi_edit_columns_type) && !empty($where_clause)
    ) {
        $protected_row = $GLOBALS['dbi']->fetchSingleRow(
            'SELECT * FROM ' . PMA_Util::backquote($table)
            . ' WHERE ' . $where_clause . ';'
        );
    }

    if (false !== $possibly_uploaded_val) {
        $current_value = $possibly_uploaded_val;
    } else {
        // c o l u m n    v a l u e    i n    t h e    f o r m
        if (isset($multi_edit_columns_type[$key])) {
            $type = $multi_edit_columns_type[$key];
        } else {
            $type = '';
        }

        if ($type != 'protected' && $type != 'set'
            && 0 === /*overload*/mb_strlen($current_value)
        ) {
            // best way to avoid problems in strict mode
            // (works also in non-strict mode)
            if (isset($multi_edit_auto_increment)
                && isset($multi_edit_auto_increment[$key])
            ) {
                $current_value = 'NULL';
            } else {
                $current_value = "''";
            }
        } elseif ($type == 'set') {
            if (! empty($_REQUEST['fields']['multi_edit'][$rownumber][$key])) {
                $current_value = implode(
                    ',', $_REQUEST['fields']['multi_edit'][$rownumber][$key]
                );
                $current_value = "'" . PMA_Util::sqlAddSlashes($current_value) . "'";
            } else {
                 $current_value = "''";
            }
        } elseif ($type == 'protected') {
            // here we are in protected mode (asked in the config)
            // so tbl_change has put this special value in the
            // columns array, so we do not change the column value
            // but we can still handle column upload

            // when in UPDATE mode, do not alter field's contents. When in INSERT
            // mode, insert empty field because no values were submitted.
            // If protected blobs where set, insert original fields content.
            if (! empty($protected_row[$multi_edit_columns_name[$key]])) {
                $current_value = '0x'
                    . bin2hex($protected_row[$multi_edit_columns_name[$key]]);
            } else {
                $current_value = '';
            }
        } elseif ($type === 'hex') {
            $current_value = '0x' . $current_value;
        } elseif ($type == 'bit') {
            $current_value = preg_replace('/[^01]/', '0', $current_value);
            $current_value = "b'" . PMA_Util::sqlAddSlashes($current_value) . "'";
        } elseif (! ($type == 'datetime' || $type == 'timestamp')
            || $current_value != 'CURRENT_TIMESTAMP'
        ) {
            $current_value = "'" . PMA_Util::sqlAddSlashes($current_value) . "'";
        }

        // Was the Null checkbox checked for this field?
        // (if there is a value, we ignore the Null checkbox: this could
        // be possible if Javascript is disabled in the browser)
        if (! empty($multi_edit_columns_null[$key])
            && ($current_value == "''" || $current_value == '')
        ) {
            $current_value = 'NULL';
        }

        // The Null checkbox was unchecked for this field
        if (empty($current_value)
            && ! empty($multi_edit_columns_null_prev[$key])
            && ! isset($multi_edit_columns_null[$key])
        ) {
            $current_value = "''";
        }
    }  // end else (column value in the form)
    return $current_value;
}


/**
 * Check whether inline edited value can be truncated or not,
 * and add additional parameters for extra_data array  if needed
 *
 * @param string $db          Database name
 * @param string $table       Table name
 * @param string $column_name Column name
 * @param array  &$extra_data Extra data for ajax response
 *
 * @return void
 */
function PMA_verifyWhetherValueCanBeTruncatedAndAppendExtraData(
    $db, $table, $column_name, &$extra_data
) {

    $extra_data['isNeedToRecheck'] = false;

    $sql_for_real_value = 'SELECT ' . PMA_Util::backquote($table) . '.'
        . PMA_Util::backquote($column_name)
        . ' FROM ' . PMA_Util::backquote($db) . '.'
        . PMA_Util::backquote($table)
        . ' WHERE ' . $_REQUEST['where_clause'][0];

    $result = $GLOBALS['dbi']->tryQuery($sql_for_real_value);
    $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
    $meta = $fields_meta[0];
    if ($row = $GLOBALS['dbi']->fetchRow($result)) {
        $new_value = $row[0];
        if ((substr($meta->type, 0, 9) == 'timestamp')
            || ($meta->type == 'datetime')
            || ($meta->type == 'time')
        ) {
            $new_value = PMA_Util::addMicroseconds($new_value);
        }
        $extra_data['isNeedToRecheck'] = true;
        $extra_data['truncatableFieldValue'] = $new_value;
    }
    $GLOBALS['dbi']->freeResult($result);
}

/**
 * Function to get the columns of a table
 *
 * @param string $db    current db
 * @param string $table current table
 *
 * @return array
 */
function PMA_getTableColumns($db, $table)
{
    $GLOBALS['dbi']->selectDb($db);
    return array_values($GLOBALS['dbi']->getColumns($db, $table));

}

/**
 * Function to determine Insert/Edit rows
 *
 * @param string $where_clause where clause
 * @param string $db           current database
 * @param string $table        current table
 *
 * @return mixed
 */
function PMA_determineInsertOrEdit($where_clause, $db, $table)
{
    if (isset($_REQUEST['where_clause'])) {
        $where_clause = $_REQUEST['where_clause'];
    }
    if (isset($_SESSION['edit_next'])) {
        $where_clause = $_SESSION['edit_next'];
        unset($_SESSION['edit_next']);
        $after_insert = 'edit_next';
    }
    if (isset($_REQUEST['ShowFunctionFields'])) {
        $GLOBALS['cfg']['ShowFunctionFields'] = $_REQUEST['ShowFunctionFields'];
    }
    if (isset($_REQUEST['ShowFieldTypesInDataEditView'])) {
        $GLOBALS['cfg']['ShowFieldTypesInDataEditView']
            = $_REQUEST['ShowFieldTypesInDataEditView'];
    }
    if (isset($_REQUEST['after_insert'])) {
        $after_insert = $_REQUEST['after_insert'];
    }

    if (isset($where_clause)) {
        // we are editing
        $insert_mode = false;
        $where_clause_array = PMA_getWhereClauseArray($where_clause);
        list($where_clauses, $result, $rows, $found_unique_key)
            = PMA_analyzeWhereClauses(
                $where_clause_array, $table, $db
            );
    } else {
        // we are inserting
        $insert_mode = true;
        $where_clause = null;
        list($result, $rows) = PMA_loadFirstRow($table, $db);
        $where_clauses = null;
        $where_clause_array = array();
        $found_unique_key = false;
    }

    // Copying a row - fetched data will be inserted as a new row,
    // therefore the where clause is needless.
    if (isset($_REQUEST['default_action'])
        && $_REQUEST['default_action'] === 'insert'
    ) {
        $where_clause = $where_clauses = null;
    }

    return array(
        $insert_mode, $where_clause, $where_clause_array, $where_clauses,
        $result, $rows, $found_unique_key,
        isset($after_insert) ? $after_insert : null
    );
}

/**
 * Function to get comments for the table columns
 *
 * @param string $db    current database
 * @param string $table current table
 *
 * @return array $comments_map comments for columns
 */
function PMA_getCommentsMap($db, $table)
{
    /**
     * get table information
     * @todo should be done by a Table object
     */
    include 'libraries/tbl_info.inc.php';

    /**
     * Get comments for table fields/columns
     */
    $comments_map = array();

    if ($GLOBALS['cfg']['ShowPropertyComments']) {
        $comments_map = PMA_getComments($db, $table);
    }

    return $comments_map;
}

/**
 * Function to get URL parameters
 *
 * @param string $db    current database
 * @param string $table current table
 *
 * @return array $url_params url parameters
 */
function PMA_getUrlParameters($db, $table)
{
    /**
     * @todo check if we could replace by "db_|tbl_" - please clarify!?
     */
    $url_params = array(
        'db' => $db,
        'sql_query' => $_REQUEST['sql_query']
    );

    if (preg_match('@^tbl_@', $GLOBALS['goto'])) {
        $url_params['table'] = $table;
    }

    return $url_params;
}

/**
 * Function to get html for the gis editor div
 *
 * @return string
 */
function PMA_getHtmlForGisEditor()
{
    return '<div id="gis_editor"></div>'
        . '<div id="popup_background"></div>'
        . '<br />';
}

/**
 * Function to get html for the ignore option in insert mode
 *
 * @param int  $row_id  row id
 * @param bool $checked ignore option is checked or not
 *
 * @return string
 */
function PMA_getHtmlForIgnoreOption($row_id, $checked = true)
{
    return '<input type="checkbox"'
            . ($checked ? ' checked="checked"' : '')
            . ' name="insert_ignore_' . $row_id . '"'
            . ' id="insert_ignore_' . $row_id . '" />'
            . '<label for="insert_ignore_' . $row_id . '">'
            . __('Ignore')
            . '</label><br />' . "\n";
}

/**
 * Function to get html for the function option
 *
 * @param bool   $odd_row              whether odd row or not
 * @param array  $column               column
 * @param string $column_name_appendix column name appendix
 *
 * @return String
 */
function PMA_getHtmlForFunctionOption($odd_row, $column, $column_name_appendix)
{
    $longDoubleTextArea = $GLOBALS['cfg']['LongtextDoubleTextarea'];
    return '<tr class="noclick ' . ($odd_row ? 'odd' : 'even' ) . '">'
        . '<td '
        . ($longDoubleTextArea
            && /*overload*/mb_strstr($column['True_Type'], 'longtext')
            ? 'rowspan="2"'
            : ''
        )
        . 'class="center">'
        . $column['Field_title']
        . '<input type="hidden" name="fields_name' . $column_name_appendix
        . '" value="' . $column['Field_html'] . '"/>'
        . '</td>';

}

/**
 * Function to get html for the column type
 *
 * @param array $column column
 *
 * @return string
 */
function PMA_getHtmlForInsertEditColumnType($column)
{
    return '<td class="center' . $column['wrap'] . '">'
        . '<span class="column_type">' . $column['pma_type'] . '</span>'
        . '</td>';

}

/**
 * Function to get html for the insert edit form header
 *
 * @param bool $has_blob_field whether has blob field
 * @param bool $is_upload      whether is upload
 *
 * @return string
 */
function PMA_getHtmlForInsertEditFormHeader($has_blob_field, $is_upload)
{
    $html_output ='<form id="insertForm" class="lock-page ';
    if ($has_blob_field && $is_upload) {
        $html_output .='disableAjax';
    }
    $html_output .='" method="post" action="tbl_replace.php" name="insertForm" ';
    if ($is_upload) {
        $html_output .= ' enctype="multipart/form-data"';
    }
    $html_output .= '>';

    return $html_output;
}

/**
 * Function to get html for each insert/edit column
 *
 * @param array  $table_columns         table columns
 * @param int    $i                     row counter
 * @param array  $column                column
 * @param array  $comments_map          comments map
 * @param bool   $timestamp_seen        whether timestamp seen
 * @param array  $current_result        current result
 * @param string $chg_evt_handler       javascript change event handler
 * @param string $jsvkey                javascript validation key
 * @param string $vkey                  validation key
 * @param bool   $insert_mode           whether insert mode
 * @param array  $current_row           current row
 * @param bool   $odd_row               whether odd row
 * @param int    &$o_rows               row offset
 * @param int    &$tabindex             tab index
 * @param int    $columns_cnt           columns count
 * @param bool   $is_upload             whether upload
 * @param int    $tabindex_for_function tab index offset for function
 * @param array  $foreigners            foreigners
 * @param int    $tabindex_for_null     tab index offset for null
 * @param int    $tabindex_for_value    tab index offset for value
 * @param string $table                 table
 * @param string $db                    database
 * @param int    $row_id                row id
 * @param array  $titles                titles
 * @param int    $biggest_max_file_size biggest max file size
 * @param string $default_char_editing  default char editing mode which is stored
 *                                      in the config.inc.php script
 * @param string $text_dir              text direction
 * @param array  $repopulate            the data to be repopulated
 * @param array  $column_mime           the mime information of column
 * @param string $where_clause          the where clause
 *
 * @return string
 */
function PMA_getHtmlForInsertEditFormColumn($table_columns, $i, $column,
    $comments_map, $timestamp_seen, $current_result, $chg_evt_handler,
    $jsvkey, $vkey, $insert_mode, $current_row, $odd_row, &$o_rows,
    &$tabindex, $columns_cnt, $is_upload, $tabindex_for_function,
    $foreigners, $tabindex_for_null, $tabindex_for_value, $table, $db,
    $row_id, $titles, $biggest_max_file_size, $default_char_editing,
    $text_dir, $repopulate, $column_mime, $where_clause
) {
    if (! isset($table_columns[$i]['processed'])) {
        $column = $table_columns[$i];
        $column = PMA_analyzeTableColumnsArray(
            $column, $comments_map, $timestamp_seen
        );
    }
    $as_is = false;
    if (!empty($repopulate) && !empty($current_row)) {
        $current_row[$column['Field']] = $repopulate[$column['Field_md5']];
        $as_is = true;
    }

    $extracted_columnspec
        = PMA_Util::extractColumnSpec($column['Type']);

    if (-1 === $column['len']) {
        $column['len'] = $GLOBALS['dbi']->fieldLen($current_result, $i);
        // length is unknown for geometry fields,
        // make enough space to edit very simple WKTs
        if (-1 === $column['len']) {
            $column['len'] = 30;
        }
    }
    //Call validation when the form submitted...
    $unnullify_trigger = $chg_evt_handler
        . "=\"return verificationsAfterFieldChange('"
        . PMA_escapeJsString($column['Field_md5']) . "', '"
        . PMA_escapeJsString($jsvkey) . "','" . $column['pma_type'] . "')\"";

    // Use an MD5 as an array index to avoid having special characters
    // in the name attribute (see bug #1746964 )
    $column_name_appendix = $vkey . '[' . $column['Field_md5'] . ']';

    if ($column['Type'] === 'datetime'
        && ! isset($column['Default'])
        && ! is_null($column['Default'])
        && $insert_mode
    ) {
        $column['Default'] = date('Y-m-d H:i:s', time());
    }

    $html_output = PMA_getHtmlForFunctionOption(
        $odd_row, $column, $column_name_appendix
    );

    if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
        $html_output .= PMA_getHtmlForInsertEditColumnType($column);
    } //End if

    // Get a list of GIS data types.
    $gis_data_types = PMA_Util::getGISDatatypes();

    // Prepares the field value
    $real_null_value = false;
    $special_chars_encoded = '';
    if (!empty($current_row)) {
        // (we are editing)
        list(
            $real_null_value, $special_chars_encoded, $special_chars,
            $data, $backup_field
        )
            = PMA_getSpecialCharsAndBackupFieldForExistingRow(
                $current_row, $column, $extracted_columnspec,
                $real_null_value, $gis_data_types, $column_name_appendix, $as_is
            );
    } else {
        // (we are inserting)
        // display default values
        $tmp = $column;
        if (isset($repopulate[$column['Field_md5']])) {
            $tmp['Default'] = $repopulate[$column['Field_md5']];
        }
        list($real_null_value, $data, $special_chars, $backup_field,
            $special_chars_encoded
        )
            = PMA_getSpecialCharsAndBackupFieldForInsertingMode(
                $tmp, $real_null_value
            );
        unset($tmp);
    }

    $idindex = ($o_rows * $columns_cnt) + $i + 1;
    $tabindex = $idindex;

    // Get a list of data types that are not yet supported.
    $no_support_types = PMA_Util::unsupportedDatatypes();

    // The function column
    // -------------------
    if ($GLOBALS['cfg']['ShowFunctionFields']) {
        $html_output .= PMA_getFunctionColumn(
            $column, $is_upload, $column_name_appendix,
            $unnullify_trigger, $no_support_types, $tabindex_for_function,
            $tabindex, $idindex, $insert_mode
        );
    }

    // The null column
    // ---------------
    $foreignData = PMA_getForeignData(
        $foreigners, $column['Field'], false, '', ''
    );
    $html_output .= PMA_getNullColumn(
        $column, $column_name_appendix, $real_null_value,
        $tabindex, $tabindex_for_null, $idindex, $vkey, $foreigners,
        $foreignData
    );

    // The value column (depends on type)
    // ----------------
    // See bug #1667887 for the reason why we don't use the maxlength
    // HTML attribute

    //add data attributes "no of decimals" and "data type"
    $no_decimals=0;
    $type = current(explode("(", $column['pma_type']));
    if (preg_match('/\(([^()]+)\)/', $column['pma_type'], $match)) {
        $match[0] = trim($match[0], '()');
        $no_decimals=$match[0];
    }
    $html_output .= '<td' . ' data-type="' . $type . '"' . ' data-decimals="'
        . $no_decimals . '">' . "\n";
    // Will be used by js/tbl_change.js to set the default value
    // for the "Continue insertion" feature
    $html_output .= '<span class="default_value hide">'
        . $special_chars . '</span>';

    // Check input transformation of column
    $transformed_html = '';
    if (!empty($column_mime['input_transformation'])) {
        $file = $column_mime['input_transformation'];
        $include_file = 'libraries/plugins/transformations/' . $file;
        if (is_file($include_file)) {
            include_once $include_file;
            $class_name = PMA_getTransformationClassName($file);
            $transformation_plugin = new $class_name();
            $transformation_options = PMA_Transformation_getOptions(
                $column_mime['input_transformation_options']
            );
            $_url_params = array(
                'db'            => $db,
                'table'         => $table,
                'transform_key' => $column['Field'],
                'where_clause'  => $where_clause
            );
            $transformation_options['wrapper_link']
                = PMA_URL_getCommon($_url_params);
            $current_value = '';
            if (isset($current_row[$column['Field']])) {
                $current_value = $current_row[$column['Field']];
            }
            if (method_exists($transformation_plugin, 'getInputHtml')) {
                $transformed_html = $transformation_plugin->getInputHtml(
                    $column, $row_id, $column_name_appendix,
                    $transformation_options, $current_value
                );
            }
            if (method_exists($transformation_plugin, 'getScripts')) {
                $GLOBALS['plugin_scripts'] = array_merge(
                    $GLOBALS['plugin_scripts'], $transformation_plugin->getScripts()
                );
            }
        }
    }
    if (!empty($transformed_html)) {
        $html_output .= $transformed_html;
    } else {
        $html_output .= PMA_getValueColumn(
            $column, $backup_field, $column_name_appendix, $unnullify_trigger,
            $tabindex, $tabindex_for_value, $idindex, $data, $special_chars,
            $foreignData, $odd_row, array($table, $db), $row_id, $titles,
            $text_dir, $special_chars_encoded, $vkey, $is_upload,
            $biggest_max_file_size, $default_char_editing,
            $no_support_types, $gis_data_types, $extracted_columnspec
        );
    }
    $html_output .= '</td>'
        . '</tr>';

    return $html_output;
}

/**
 * Function to get html for each insert/edit row
 *
 * @param array  $url_params            url parameters
 * @param array  $table_columns         table columns
 * @param array  $column                column
 * @param array  $comments_map          comments map
 * @param bool   $timestamp_seen        whether timestamp seen
 * @param array  $current_result        current result
 * @param string $chg_evt_handler       javascript change event handler
 * @param string $jsvkey                javascript validation key
 * @param string $vkey                  validation key
 * @param bool   $insert_mode           whether insert mode
 * @param array  $current_row           current row
 * @param int    &$o_rows               row offset
 * @param int    &$tabindex             tab index
 * @param int    $columns_cnt           columns count
 * @param bool   $is_upload             whether upload
 * @param int    $tabindex_for_function tab index offset for function
 * @param array  $foreigners            foreigners
 * @param int    $tabindex_for_null     tab index offset for null
 * @param int    $tabindex_for_value    tab index offset for value
 * @param string $table                 table
 * @param string $db                    database
 * @param int    $row_id                row id
 * @param array  $titles                titles
 * @param int    $biggest_max_file_size biggest max file size
 * @param string $text_dir              text direction
 * @param array  $repopulate            the data to be repopulated
 * @param array  $where_clause_array    the array of where clauses
 *
 * @return string
 */
function PMA_getHtmlForInsertEditRow($url_params, $table_columns,
    $column, $comments_map, $timestamp_seen, $current_result, $chg_evt_handler,
    $jsvkey, $vkey, $insert_mode, $current_row, &$o_rows, &$tabindex, $columns_cnt,
    $is_upload, $tabindex_for_function, $foreigners, $tabindex_for_null,
    $tabindex_for_value, $table, $db, $row_id, $titles,
    $biggest_max_file_size, $text_dir, $repopulate, $where_clause_array
) {
    $html_output = PMA_getHeadAndFootOfInsertRowTable($url_params)
        . '<tbody>';

    //store the default value for CharEditing
    $default_char_editing  = $GLOBALS['cfg']['CharEditing'];
    $mime_map = PMA_getMIME($db, $table);
    $odd_row = true;
    $where_clause = '';
    if (isset($where_clause_array[$row_id])) {
        $where_clause = $where_clause_array[$row_id];
    }
    for ($i = 0; $i < $columns_cnt; $i++) {
        $column_mime = array();
        if (isset($mime_map[$table_columns[$i]['Field']])) {
            $column_mime = $mime_map[$table_columns[$i]['Field']];
        }
        $html_output .= PMA_getHtmlForInsertEditFormColumn(
            $table_columns, $i, $column, $comments_map, $timestamp_seen,
            $current_result, $chg_evt_handler, $jsvkey, $vkey, $insert_mode,
            $current_row, $odd_row, $o_rows, $tabindex, $columns_cnt, $is_upload,
            $tabindex_for_function, $foreigners, $tabindex_for_null,
            $tabindex_for_value, $table, $db, $row_id, $titles,
            $biggest_max_file_size, $default_char_editing, $text_dir, $repopulate,
            $column_mime, $where_clause
        );
        $odd_row = !$odd_row;
    } // end for
    $o_rows++;
    $html_output .= '  </tbody>'
        . '</table><br />'
        . '<div class="clearfloat"></div>';

    return $html_output;
}
?>