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

import.lib.php « libraries - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 355dbd1c8b47ab8fbfa28ee7592485b299d6608c (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
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Library that provides common import functions that are used by import plugins
 *
 * @package PhpMyAdmin-Import
 */
if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * We need to know something about user
 */
require_once './libraries/check_user_privileges.lib.php';

/**
 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
 */
define('PMA_CHK_DROP', 1);

/**
 * Checks whether timeout is getting close
 *
 * @return boolean true if timeout is close
 * @access public
 */
function PMA_checkTimeout()
{
    global $timestamp, $maximum_time, $timeout_passed;
    if ($maximum_time == 0) {
        return false;
    } elseif ($timeout_passed) {
        return true;
        /* 5 in next row might be too much */
    } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
        $timeout_passed = true;
        return true;
    } else {
        return false;
    }
}

/**
 * Detects what compression the file uses
 *
 * @param string $filepath filename to check
 *
 * @return string MIME type of compression, none for none
 * @access public
 */
function PMA_detectCompression($filepath)
{
    $file = @fopen($filepath, 'rb');
    if (! $file) {
        return false;
    }
    return PMA_Util::getCompressionMimeType($file);
}

/**
 * Runs query inside import buffer. This is needed to allow displaying
 * of last SELECT, SHOW or HANDLER results and similar nice stuff.
 *
 * @param string $sql         query to run
 * @param string $full        query to display, this might be commented
 * @param bool   $controluser whether to use control user for queries
 * @param array  &$sql_data   SQL parse data storage
 *
 * @return void
 * @access public
 */
function PMA_importRunQuery($sql = '', $full = '', $controluser = false,
    &$sql_data = array()
) {
    global $import_run_buffer, $go_sql, $complete_query, $display_query,
        $sql_query, $my_die, $error, $reload,
        $last_query_with_results, $result, $msg,
        $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
        $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
    $read_multiply = 1;
    if (!isset($import_run_buffer)) {
        // Do we have something to push into buffer?
        $import_run_buffer = PMA_ImportRunQuery_post(
            $import_run_buffer, $sql, $full
        );
        return;
    }

    // Should we skip something?
    if ($skip_queries > 0) {
        $skip_queries--;
        // Do we have something to push into buffer?
        $import_run_buffer = PMA_ImportRunQuery_post(
            $import_run_buffer, $sql, $full
        );
        return;
    }

    if (! empty($import_run_buffer['sql'])
        && trim($import_run_buffer['sql']) != ''
    ) {

        // USE query changes the database, son need to track
        // while running multiple queries
        $is_use_query
            = (/*overload*/mb_stripos($import_run_buffer['sql'], "use ") !== false)
                ? true
                : false;

        $max_sql_len = max(
            $max_sql_len,
            /*overload*/mb_strlen($import_run_buffer['sql'])
        );
        if (! $sql_query_disabled) {
            $sql_query .= $import_run_buffer['full'];
        }
        $pattern = '@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?'
            . 'DATABASE @i';
        if (! $cfg['AllowUserDropDatabase']
            && ! $is_superuser
            && preg_match($pattern, $import_run_buffer['sql'])
        ) {
            $GLOBALS['message'] = PMA_Message::error(
                __('"DROP DATABASE" statements are disabled.')
            );
            $error = true;
        } else {
            $executed_queries++;

            $pattern = '/^[\s]*(SELECT|SHOW|HANDLER)/i';
            if ($run_query
                && $GLOBALS['finished']
                && empty($sql)
                && ! $error
                && ((! empty($import_run_buffer['sql'])
                && preg_match($pattern, $import_run_buffer['sql']))
                || ($executed_queries == 1))
            ) {
                $go_sql = true;
                if (! $sql_query_disabled) {
                    $complete_query = $sql_query;
                    $display_query = $sql_query;
                } else {
                    $complete_query = '';
                    $display_query = '';
                }
                $sql_query = $import_run_buffer['sql'];
                $sql_data['valid_sql'][] = $import_run_buffer['sql'];
                if (! isset($sql_data['valid_queries'])) {
                    $sql_data['valid_queries'] = 0;
                }
                $sql_data['valid_queries']++;

                // If a 'USE <db>' SQL-clause was found,
                // set our current $db to the new one
                list($db, $reload) = PMA_lookForUse(
                    $import_run_buffer['sql'],
                    $db,
                    $reload
                );
            } elseif ($run_query) {

                if ($controluser) {
                    $result = PMA_queryAsControlUser(
                        $import_run_buffer['sql']
                    );
                } else {
                    $result = $GLOBALS['dbi']
                        ->tryQuery($import_run_buffer['sql']);
                }

                $msg = '# ';
                if ($result === false) { // execution failed
                    if (! isset($my_die)) {
                        $my_die = array();
                    }
                    $my_die[] = array(
                        'sql' => $import_run_buffer['full'],
                        'error' => $GLOBALS['dbi']->getError()
                    );

                    $msg .= __('Error');

                    if (! $cfg['IgnoreMultiSubmitErrors']) {
                        $error = true;
                        return;
                    }
                } else {
                    $a_num_rows = (int)@$GLOBALS['dbi']->numRows($result);
                    $a_aff_rows = (int)@$GLOBALS['dbi']->affectedRows();
                    if ($a_num_rows > 0) {
                        $msg .= __('Rows') . ': ' . $a_num_rows;
                        $last_query_with_results = $import_run_buffer['sql'];
                    } elseif ($a_aff_rows > 0) {
                        $message = PMA_Message::getMessageForAffectedRows(
                            $a_aff_rows
                        );
                        $msg .= $message->getMessage();
                    } else {
                        $msg .= __(
                            'MySQL returned an empty result set (i.e. zero '
                            . 'rows).'
                        );
                    }

                    $sql_data = updateSqlData(
                        $sql_data, $a_num_rows, $is_use_query, $import_run_buffer
                    );
                }
                if (! $sql_query_disabled) {
                    $sql_query .= $msg . "\n";
                }

                // If a 'USE <db>' SQL-clause was found and the query
                // succeeded, set our current $db to the new one
                if ($result != false) {
                    list($db, $reload) = PMA_lookForUse(
                        $import_run_buffer['sql'],
                        $db,
                        $reload
                    );
                }

                $pattern = '@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)'
                    . '?(TABLE|DATABASE)[[:space:]]+(.+)@im';
                if ($result != false
                    && preg_match($pattern, $import_run_buffer['sql'])
                ) {
                    $reload = true;
                }
            } // end run query
        } // end if not DROP DATABASE
        // end non empty query
    } elseif (! empty($import_run_buffer['full'])) {
        if ($go_sql) {
            $complete_query .= $import_run_buffer['full'];
            $display_query .= $import_run_buffer['full'];
        } else {
            if (! $sql_query_disabled) {
                $sql_query .= $import_run_buffer['full'];
            }
        }
    }
    // check length of query unless we decided to pass it to sql.php
    // (if $run_query is false, we are just displaying so show
    // the complete query in the textarea)
    if (! $go_sql && $run_query) {
        if (! empty($sql_query)) {
            if (/*overload*/mb_strlen($sql_query) > 50000
                || $executed_queries > 50
                || $max_sql_len > 1000
            ) {
                $sql_query = '';
                $sql_query_disabled = true;
            }
        }
    }

    // Do we have something to push into buffer?
    $import_run_buffer = PMA_ImportRunQuery_post($import_run_buffer, $sql, $full);

    // In case of ROLLBACK, notify the user.
    if (isset($_REQUEST['rollback_query'])) {
        $msg .= __('[ROLLBACK occurred.]');
    }
}

/**
 * Update $sql_data
 *
 * @param array $sql_data          SQL data
 * @param int   $a_num_rows        Number of rows
 * @param bool  $is_use_query      Query is used
 * @param array $import_run_buffer Import buffer
 *
 * @return array
 */
function updateSqlData($sql_data, $a_num_rows, $is_use_query, $import_run_buffer)
{
    if (($a_num_rows > 0) || $is_use_query) {
        $sql_data['valid_sql'][] = $import_run_buffer['sql'];
        if (!isset($sql_data['valid_queries'])) {
            $sql_data['valid_queries'] = 0;
        }
        $sql_data['valid_queries']++;
    }
    return $sql_data;
}

/**
 * Return import run buffer
 *
 * @param array  $import_run_buffer Buffer of queries for import
 * @param string $sql               SQL query
 * @param string $full              Query to display
 *
 * @return array Buffer of queries for import
 */
function PMA_ImportRunQuery_post($import_run_buffer, $sql, $full)
{
    if (!empty($sql) || !empty($full)) {
        $import_run_buffer = array('sql' => $sql, 'full' => $full);
        return $import_run_buffer;
    } else {
        unset($GLOBALS['import_run_buffer']);
        return $import_run_buffer;
    }
}

/**
 * Looks for the presence of USE to possibly change current db
 *
 * @param string $buffer buffer to examine
 * @param string $db     current db
 * @param bool   $reload reload
 *
 * @return array (current or new db, whether to reload)
 * @access public
 */
function PMA_lookForUse($buffer, $db, $reload)
{
    if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', $buffer, $match)) {
        $db = trim($match[1]);
        $db = trim($db, ';'); // for example, USE abc;

        // $db must not contain the escape characters generated by backquote()
        // ( used in PMA_buildSQL() as: backquote($db_name), and then called
        // in PMA_importRunQuery() which in turn calls PMA_lookForUse() )
        $db = PMA_Util::unQuote($db);

        $reload = true;
    }
    return(array($db, $reload));
}


/**
 * Returns next part of imported file/buffer
 *
 * @param int $size size of buffer to read
 *                  (this is maximal size function will return)
 *
 * @return string part of file/buffer
 * @access public
 */
function PMA_importGetNextChunk($size = 32768)
{
    global $compression, $import_handle, $charset_conversion, $charset_of_file,
        $read_multiply;

    // Add some progression while reading large amount of data
    if ($read_multiply <= 8) {
        $size *= $read_multiply;
    } else {
        $size *= 8;
    }
    $read_multiply++;

    // We can not read too much
    if ($size > $GLOBALS['read_limit']) {
        $size = $GLOBALS['read_limit'];
    }

    if (PMA_checkTimeout()) {
        return false;
    }
    if ($GLOBALS['finished']) {
        return true;
    }

    if ($GLOBALS['import_file'] == 'none') {
        // Well this is not yet supported and tested,
        // but should return content of textarea
        if (/*overload*/mb_strlen($GLOBALS['import_text']) < $size) {
            $GLOBALS['finished'] = true;
            return $GLOBALS['import_text'];
        } else {
            $r = /*overload*/mb_substr($GLOBALS['import_text'], 0, $size);
            $GLOBALS['offset'] += $size;
            $GLOBALS['import_text'] = /*overload*/
                mb_substr($GLOBALS['import_text'], $size);
            return $r;
        }
    }

    switch ($compression) {
    case 'application/bzip2':
        $result = bzread($import_handle, $size);
        $GLOBALS['finished'] = feof($import_handle);
        break;
    case 'application/gzip':
        $result = gzread($import_handle, $size);
        $GLOBALS['finished'] = feof($import_handle);
        break;
    case 'application/zip':
        $result = /*overload*/mb_substr($GLOBALS['import_text'], 0, $size);
        $GLOBALS['import_text'] = /*overload*/mb_substr(
            $GLOBALS['import_text'],
            $size
        );
        $GLOBALS['finished'] = empty($GLOBALS['import_text']);
        break;
    case 'none':
        $result = fread($import_handle, $size);
        $GLOBALS['finished'] = feof($import_handle);
        break;
    }
    $GLOBALS['offset'] += $size;

    if ($charset_conversion) {
        return PMA_convertString($charset_of_file, 'utf-8', $result);
    }

    /**
     * Skip possible byte order marks (I do not think we need more
     * charsets, but feel free to add more, you can use wikipedia for
     * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
     *
     * @todo BOM could be used for charset autodetection
     */
    if ($GLOBALS['offset'] == $size) {
        // UTF-8
        if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
            $result = /*overload*/mb_substr($result, 3);
            // UTF-16 BE, LE
        } elseif (strncmp($result, "\xFE\xFF", 2) == 0
            || strncmp($result, "\xFF\xFE", 2) == 0
        ) {
            $result = /*overload*/mb_substr($result, 2);
        }
    }
    return $result;
}

/**
 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
 *
 * This functions uses recursion to build the Excel column name.
 *
 * The column number (1-26) is converted to the responding
 * ASCII character (A-Z) and returned.
 *
 * If the column number is bigger than 26 (= num of letters in alphabet),
 * an extra character needs to be added. To find this extra character,
 * the number is divided by 26 and this value is passed to another instance
 * of the same function (hence recursion). In that new instance the number is
 * evaluated again, and if it is still bigger than 26, it is divided again
 * and passed to another instance of the same function. This continues until
 * the number is smaller than 26. Then the last called function returns
 * the corresponding ASCII character to the function that called it.
 * Each time a called function ends an extra character is added to the column name.
 * When the first function is reached, the last character is added and the complete
 * column name is returned.
 *
 * @param int $num the column number
 *
 * @return string The column's "Excel" name
 * @access  public
 */
function PMA_getColumnAlphaName($num)
{
    $A = 65; // ASCII value for capital "A"
    $col_name = "";

    if ($num > 26) {
        $div = (int)($num / 26);
        $remain = (int)($num % 26);

        // subtract 1 of divided value in case the modulus is 0,
        // this is necessary because A-Z has no 'zero'
        if ($remain == 0) {
            $div--;
        }

        // recursive function call
        $col_name = PMA_getColumnAlphaName($div);
        // use modulus as new column number
        $num = $remain;
    }

    if ($num == 0) {
        // use 'Z' if column number is 0,
        // this is necessary because A-Z has no 'zero'
        $col_name .= /*overload*/mb_chr(($A + 26) - 1);
    } else {
        // convert column number to ASCII character
        $col_name .= /*overload*/mb_chr(($A + $num) - 1);
    }

    return $col_name;
}

/**
 * Returns the column number based on the Excel name.
 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
 *
 * Basically this is a base26 (A-Z) to base10 (0-9) conversion.
 * It iterates through all characters in the column name and
 * calculates the corresponding value, based on character value
 * (A = 1, ..., Z = 26) and position in the string.
 *
 * @param string $name column name(i.e. "A", or "BC", etc.)
 *
 * @return int The column number
 * @access  public
 */
function PMA_getColumnNumberFromName($name)
{
    if (empty($name)) {
        return 0;
    }

    $name = /*overload*/mb_strtoupper($name);
    $num_chars = /*overload*/mb_strlen($name);
    $column_number = 0;
    for ($i = 0; $i < $num_chars; ++$i) {
        // read string from back to front
        $char_pos = ($num_chars - 1) - $i;

        // convert capital character to ASCII value
        // and subtract 64 to get corresponding decimal value
        // ASCII value of "A" is 65, "B" is 66, etc.
        // Decimal equivalent of "A" is 1, "B" is 2, etc.
        $number = (int)(/*overload*/mb_ord($name[$char_pos]) - 64);

        // base26 to base10 conversion : multiply each number
        // with corresponding value of the position, in this case
        // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
        $column_number += $number * PMA_Util::pow(26, $i);
    }
    return $column_number;
}

/**
 * Constants definitions
 */

/* MySQL type defs */
define("NONE",      0);
define("VARCHAR",   1);
define("INT",       2);
define("DECIMAL",   3);
define("BIGINT",    4);
define("GEOMETRY",  5);

/* Decimal size defs */
define("M",         0);
define("D",         1);
define("FULL",      2);

/* Table array defs */
define("TBL_NAME",  0);
define("COL_NAMES", 1);
define("ROWS",      2);

/* Analysis array defs */
define("TYPES",        0);
define("SIZES",        1);
define("FORMATTEDSQL", 2);

/**
 * Obtains the precision (total # of digits) from a size of type decimal
 *
 * @param string $last_cumulative_size Size of type decimal
 *
 * @return int Precision of the given decimal size notation
 * @access  public
 */
function PMA_getDecimalPrecision($last_cumulative_size)
{
    return (int)substr(
        $last_cumulative_size,
        0,
        strpos($last_cumulative_size, ",")
    );
}

/**
 * Obtains the scale (# of digits to the right of the decimal point)
 * from a size of type decimal
 *
 * @param string $last_cumulative_size Size of type decimal
 *
 * @return int Scale of the given decimal size notation
 * @access  public
 */
function PMA_getDecimalScale($last_cumulative_size)
{
    return (int)substr(
        $last_cumulative_size,
        (strpos($last_cumulative_size, ",") + 1),
        (strlen($last_cumulative_size) - strpos($last_cumulative_size, ","))
    );
}

/**
 * Obtains the decimal size of a given cell
 *
 * @param string $cell cell content
 *
 * @return array Contains the precision, scale, and full size
 *                representation of the given decimal cell
 * @access  public
 */
function PMA_getDecimalSize($cell)
{
    $curr_size = /*overload*/mb_strlen((string)$cell);
    $decPos = /*overload*/mb_strpos($cell, ".");
    $decPrecision = ($curr_size - 1) - $decPos;

    $m = $curr_size - 1;
    $d = $decPrecision;

    return array($m, $d, ($m . "," . $d));
}

/**
 * Obtains the size of the given cell
 *
 * @param string $last_cumulative_size Last cumulative column size
 * @param int    $last_cumulative_type Last cumulative column type
 *                                     (NONE or VARCHAR or DECIMAL or INT or BIGINT)
 * @param int    $curr_type            Type of the current cell
 *                                     (NONE or VARCHAR or DECIMAL or INT or BIGINT)
 * @param string $cell                 The current cell
 *
 * @return string  Size of the given cell in the type-appropriate format
 * @access  public
 *
 * @todo    Handle the error cases more elegantly
 */
function PMA_detectSize($last_cumulative_size, $last_cumulative_type,
    $curr_type, $cell
) {
    $curr_size = /*overload*/mb_strlen((string)$cell);

    /**
     * If the cell is NULL, don't treat it as a varchar
     */
    if (! strcmp('NULL', $cell)) {
        return $last_cumulative_size;
    } elseif ($curr_type == VARCHAR) {
        /**
         * What to do if the current cell is of type VARCHAR
         */
        /**
         * The last cumulative type was VARCHAR
         */
        if ($last_cumulative_type == VARCHAR) {
            if ($curr_size >= $last_cumulative_size) {
                return $curr_size;
            } else {
                return $last_cumulative_size;
            }
        } elseif ($last_cumulative_type == DECIMAL) {
            /**
             * The last cumulative type was DECIMAL
             */
            $oldM = PMA_getDecimalPrecision($last_cumulative_size);

            if ($curr_size >= $oldM) {
                return $curr_size;
            } else {
                return $oldM;
            }
        } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
            /**
             * The last cumulative type was BIGINT or INT
             */
            if ($curr_size >= $last_cumulative_size) {
                return $curr_size;
            } else {
                return $last_cumulative_size;
            }
        } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
            /**
             * This is the first row to be analyzed
             */
            return $curr_size;
        } else {
            /**
             * An error has DEFINITELY occurred
             */
            /**
             * TODO: Handle this MUCH more elegantly
             */

            return -1;
        }
    } elseif ($curr_type == DECIMAL) {
        /**
         * What to do if the current cell is of type DECIMAL
         */
        /**
         * The last cumulative type was VARCHAR
         */
        if ($last_cumulative_type == VARCHAR) {
            /* Convert $last_cumulative_size from varchar to decimal format */
            $size = PMA_getDecimalSize($cell);

            if ($size[M] >= $last_cumulative_size) {
                return $size[M];
            } else {
                return $last_cumulative_size;
            }
        } elseif ($last_cumulative_type == DECIMAL) {
            /**
             * The last cumulative type was DECIMAL
             */
            $size = PMA_getDecimalSize($cell);

            $oldM = PMA_getDecimalPrecision($last_cumulative_size);
            $oldD = PMA_getDecimalScale($last_cumulative_size);

            /* New val if M or D is greater than current largest */
            if ($size[M] > $oldM || $size[D] > $oldD) {
                /* Take the largest of both types */
                return (string) ((($size[M] > $oldM) ? $size[M] : $oldM)
                    . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
            } else {
                return $last_cumulative_size;
            }
        } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
            /**
             * The last cumulative type was BIGINT or INT
             */
            /* Convert $last_cumulative_size from int to decimal format */
            $size = PMA_getDecimalSize($cell);

            if ($size[M] >= $last_cumulative_size) {
                return $size[FULL];
            } else {
                return ($last_cumulative_size . "," . $size[D]);
            }
        } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
            /**
             * This is the first row to be analyzed
             */
            /* First row of the column */
            $size = PMA_getDecimalSize($cell);

            return $size[FULL];
        } else {
            /**
             * An error has DEFINITELY occurred
             */
            /**
             * TODO: Handle this MUCH more elegantly
             */

            return -1;
        }
    } elseif ($curr_type == BIGINT || $curr_type == INT) {
        /**
         * What to do if the current cell is of type BIGINT or INT
         */
        /**
         * The last cumulative type was VARCHAR
         */
        if ($last_cumulative_type == VARCHAR) {
            if ($curr_size >= $last_cumulative_size) {
                return $curr_size;
            } else {
                return $last_cumulative_size;
            }
        } elseif ($last_cumulative_type == DECIMAL) {
            /**
             * The last cumulative type was DECIMAL
             */
            $oldM = PMA_getDecimalPrecision($last_cumulative_size);
            $oldD = PMA_getDecimalScale($last_cumulative_size);
            $oldInt = $oldM - $oldD;
            $newInt = /*overload*/mb_strlen((string)$cell);

            /* See which has the larger integer length */
            if ($oldInt >= $newInt) {
                /* Use old decimal size */
                return $last_cumulative_size;
            } else {
                /* Use $newInt + $oldD as new M */
                return (($newInt + $oldD) . "," . $oldD);
            }
        } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
            /**
             * The last cumulative type was BIGINT or INT
             */
            if ($curr_size >= $last_cumulative_size) {
                return $curr_size;
            } else {
                return $last_cumulative_size;
            }
        } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
            /**
             * This is the first row to be analyzed
             */
            return $curr_size;
        } else {
            /**
             * An error has DEFINITELY occurred
             */
            /**
             * TODO: Handle this MUCH more elegantly
             */

            return -1;
        }
    } else {
        /**
         * An error has DEFINITELY occurred
         */
        /**
         * TODO: Handle this MUCH more elegantly
         */

        return -1;
    }
}

/**
 * Determines what MySQL type a cell is
 *
 * @param int    $last_cumulative_type Last cumulative column type
 *                                     (VARCHAR or INT or BIGINT or DECIMAL or NONE)
 * @param string $cell                 String representation of the cell for which
 *                                     a best-fit type is to be determined
 *
 * @return int  The MySQL type representation
 *               (VARCHAR or INT or BIGINT or DECIMAL or NONE)
 * @access  public
 */
function PMA_detectType($last_cumulative_type, $cell)
{
    /**
     * If numeric, determine if decimal, int or bigint
     * Else, we call it varchar for simplicity
     */

    if (! strcmp('NULL', $cell)) {
        if ($last_cumulative_type === null || $last_cumulative_type == NONE) {
            return NONE;
        }

        return $last_cumulative_type;
    }

    if (!is_numeric($cell)) {
        return VARCHAR;
    }

    if ($cell == (string)(float)$cell
        && /*overload*/mb_strpos($cell, ".") !== false
        && /*overload*/mb_substr_count($cell, ".") == 1
    ) {
        return DECIMAL;
    }

    if (abs($cell) > 2147483647) {
        return BIGINT;
    }

    return INT;
}

/**
 * Determines if the column types are int, decimal, or string
 *
 * @param array &$table array(string $table_name, array $col_names, array $rows)
 *
 * @return array    array(array $types, array $sizes)
 * @access  public
 *
 * @link http://wiki.phpmyadmin.net/pma/Import
 *
 * @todo    Handle the error case more elegantly
 */
function PMA_analyzeTable(&$table)
{
    /* Get number of rows in table */
    $numRows = count($table[ROWS]);
    /* Get number of columns */
    $numCols = count($table[COL_NAMES]);
    /* Current type for each column */
    $types = array();
    $sizes = array();

    /* Initialize $sizes to all 0's */
    for ($i = 0; $i < $numCols; ++$i) {
        $sizes[$i] = 0;
    }

    /* Initialize $types to NONE */
    for ($i = 0; $i < $numCols; ++$i) {
        $types[$i] = NONE;
    }

    /* Temp vars */
    $curr_type = NONE;

    /* If the passed array is not of the correct form, do not process it */
    if (!is_array($table)
        || is_array($table[TBL_NAME])
        || !is_array($table[COL_NAMES])
        || !is_array($table[ROWS])
    ) {
        /**
         * TODO: Handle this better
         */

        return false;
    }

    /* Analyze each column */
    for ($i = 0; $i < $numCols; ++$i) {
        /* Analyze the column in each row */
        for ($j = 0; $j < $numRows; ++$j) {
            /* Determine type of the current cell */
            $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
            /* Determine size of the current cell */
            $sizes[$i] = PMA_detectSize(
                $sizes[$i],
                $types[$i],
                $curr_type,
                $table[ROWS][$j][$i]
            );

            /**
             * If a type for this column has already been declared,
             * only alter it if it was a number and a varchar was found
             */
            if ($curr_type != NONE) {
                if ($curr_type == VARCHAR) {
                    $types[$i] = VARCHAR;
                } else if ($curr_type == DECIMAL) {
                    if ($types[$i] != VARCHAR) {
                        $types[$i] = DECIMAL;
                    }
                } else if ($curr_type == BIGINT) {
                    if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
                        $types[$i] = BIGINT;
                    }
                } else if ($curr_type == INT) {
                    if ($types[$i] != VARCHAR
                        && $types[$i] != DECIMAL
                        && $types[$i] != BIGINT
                    ) {
                        $types[$i] = INT;
                    }
                }
            }
        }
    }

    /* Check to ensure that all types are valid */
    $len = count($types);
    for ($n = 0; $n < $len; ++$n) {
        if (! strcmp(NONE, $types[$n])) {
            $types[$n] = VARCHAR;
            $sizes[$n] = '10';
        }
    }

    return array($types, $sizes);
}

/* Needed to quell the beast that is PMA_Message */
$import_notice = null;

/**
 * Builds and executes SQL statements to create the database and tables
 * as necessary, as well as insert all the data.
 *
 * @param string $db_name         Name of the database
 * @param array  &$tables         Array of tables for the specified database
 * @param array  &$analyses       Analyses of the tables
 * @param array  &$additional_sql Additional SQL statements to be executed
 * @param array  $options         Associative array of options
 *
 * @return void
 * @access  public
 *
 * @link http://wiki.phpmyadmin.net/pma/Import
 */
function PMA_buildSQL($db_name, &$tables, &$analyses = null,
    &$additional_sql = null, $options = null
) {
    /* Take care of the options */
    if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
        $collation = $options['db_collation'];
    } else {
        $collation = "utf8_general_ci";
    }

    if (isset($options['db_charset']) && ! is_null($options['db_charset'])) {
        $charset = $options['db_charset'];
    } else {
        $charset = "utf8";
    }

    if (isset($options['create_db'])) {
        $create_db = $options['create_db'];
    } else {
        $create_db = true;
    }

    /* Create SQL code to handle the database */
    $sql = array();

    if ($create_db) {
        if (PMA_DRIZZLE) {
            $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
                . " COLLATE " . $collation;
        } else {
            $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
                . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
        }
    }

    /**
     * The calling plug-in should include this statement,
     * if necessary, in the $additional_sql parameter
     *
     * $sql[] = "USE " . backquote($db_name);
     */

    /* Execute the SQL statements create above */
    $sql_len = count($sql);
    for ($i = 0; $i < $sql_len; ++$i) {
        PMA_importRunQuery($sql[$i], $sql[$i]);
    }

    /* No longer needed */
    unset($sql);

    /* Run the $additional_sql statements supplied by the caller plug-in */
    if ($additional_sql != null) {
        /* Clean the SQL first */
        $additional_sql_len = count($additional_sql);

        /**
         * Only match tables for now, because CREATE IF NOT EXISTS
         * syntax is lacking or nonexisting for views, triggers,
         * functions, and procedures.
         *
         * See: http://bugs.mysql.com/bug.php?id=15287
         *
         * To the best of my knowledge this is still an issue.
         *
         * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
         */
        $pattern = '/CREATE [^`]*(TABLE)/';
        $replacement = 'CREATE \\1 IF NOT EXISTS';

        /* Change CREATE statements to CREATE IF NOT EXISTS to support
         * inserting into existing structures
         */
        for ($i = 0; $i < $additional_sql_len; ++$i) {
            $additional_sql[$i] = preg_replace(
                $pattern,
                $replacement,
                $additional_sql[$i]
            );
            /* Execute the resulting statements */
            PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
        }
    }

    if ($analyses != null) {
        $type_array = array(
            NONE => "NULL",
            VARCHAR => "varchar",
            INT => "int",
            DECIMAL => "decimal",
            BIGINT => "bigint",
            GEOMETRY => 'geometry'
        );

        /* TODO: Do more checking here to make sure they really are matched */
        if (count($tables) != count($analyses)) {
            exit();
        }

        /* Create SQL code to create the tables */
        $num_tables = count($tables);
        for ($i = 0; $i < $num_tables; ++$i) {
            $num_cols = count($tables[$i][COL_NAMES]);
            $tempSQLStr = "CREATE TABLE IF NOT EXISTS "
            . PMA_Util::backquote($db_name)
            . '.' . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";
            for ($j = 0; $j < $num_cols; ++$j) {
                $size = $analyses[$i][SIZES][$j];
                if ((int)$size == 0) {
                    $size = 10;
                }

                $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$j]) . " "
                    . $type_array[$analyses[$i][TYPES][$j]];
                if ($analyses[$i][TYPES][$j] != GEOMETRY) {
                    $tempSQLStr .= "(" . $size . ")";
                }

                if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
                    $tempSQLStr .= ", ";
                }
            }
            $tempSQLStr .= ")"
                . (PMA_DRIZZLE ? "" : " DEFAULT CHARACTER SET " . $charset)
                . " COLLATE " . $collation . ";";

            /**
             * Each SQL statement is executed immediately
             * after it is formed so that we don't have
             * to store them in a (possibly large) buffer
             */
            PMA_importRunQuery($tempSQLStr, $tempSQLStr);
        }
    }

    /**
     * Create the SQL statements to insert all the data
     *
     * Only one insert query is formed for each table
     */
    $tempSQLStr = "";
    $col_count = 0;
    $num_tables = count($tables);
    for ($i = 0; $i < $num_tables; ++$i) {
        $num_cols = count($tables[$i][COL_NAMES]);
        $num_rows = count($tables[$i][ROWS]);

        $tempSQLStr = "INSERT INTO " . PMA_Util::backquote($db_name) . '.'
            . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";

        for ($m = 0; $m < $num_cols; ++$m) {
            $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$m]);

            if ($m != ($num_cols - 1)) {
                $tempSQLStr .= ", ";
            }
        }

        $tempSQLStr .= ") VALUES ";

        for ($j = 0; $j < $num_rows; ++$j) {
            $tempSQLStr .= "(";

            for ($k = 0; $k < $num_cols; ++$k) {
                // If fully formatted SQL, no need to enclose
                // with apostrophes, add slashes etc.
                if ($analyses != null
                    && isset($analyses[$i][FORMATTEDSQL][$col_count])
                    && $analyses[$i][FORMATTEDSQL][$col_count] == true
                ) {
                    $tempSQLStr .= (string) $tables[$i][ROWS][$j][$k];
                } else {
                    if ($analyses != null) {
                        $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
                    } else {
                        $is_varchar = ! is_numeric($tables[$i][ROWS][$j][$k]);
                    }

                    /* Don't put quotes around NULL fields */
                    if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
                        $is_varchar = false;
                    }

                    $tempSQLStr .= (($is_varchar) ? "'" : "");
                    $tempSQLStr .= PMA_Util::sqlAddSlashes(
                        (string) $tables[$i][ROWS][$j][$k]
                    );
                    $tempSQLStr .= (($is_varchar) ? "'" : "");
                }

                if ($k != ($num_cols - 1)) {
                    $tempSQLStr .= ", ";
                }

                if ($col_count == ($num_cols - 1)) {
                    $col_count = 0;
                } else {
                    $col_count++;
                }

                /* Delete the cell after we are done with it */
                unset($tables[$i][ROWS][$j][$k]);
            }

            $tempSQLStr .= ")";

            if ($j != ($num_rows - 1)) {
                $tempSQLStr .= ",\n ";
            }

            $col_count = 0;
            /* Delete the row after we are done with it */
            unset($tables[$i][ROWS][$j]);
        }

        $tempSQLStr .= ";";

        /**
         * Each SQL statement is executed immediately
         * after it is formed so that we don't have
         * to store them in a (possibly large) buffer
         */
        PMA_importRunQuery($tempSQLStr, $tempSQLStr);
    }

    /* No longer needed */
    unset($tempSQLStr);

    /**
     * A work in progress
     */

    /* Add the viewable structures from $additional_sql
     * to $tables so they are also displayed
     */
    $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
    $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
    /* Check a third pattern to make sure its not a "USE `db_name`;" statement */

    $regs = array();

    $inTables = false;

    $additional_sql_len = count($additional_sql);
    for ($i = 0; $i < $additional_sql_len; ++$i) {
        preg_match($view_pattern, $additional_sql[$i], $regs);

        if (count($regs) == 0) {
            preg_match($table_pattern, $additional_sql[$i], $regs);
        }

        if (count($regs)) {
            for ($n = 0; $n < $num_tables; ++$n) {
                if (! strcmp($regs[1], $tables[$n][TBL_NAME])) {
                    $inTables = true;
                    break;
                }
            }

            if (! $inTables) {
                $tables[] = array(TBL_NAME => $regs[1]);
            }
        }

        /* Reset the array */
        $regs = array();
        $inTables = false;
    }

    $params = array('db' => (string)$db_name);
    $db_url = 'db_structure.php' . PMA_URL_getCommon($params);
    $db_ops_url = 'db_operations.php' . PMA_URL_getCommon($params);

    $message = '<br /><br />';
    $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
    $message .= '<ul><li>' . __("View a structure's contents by clicking on its name.") . '</li>';
    $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link.') . '</li>';
    $message .= '<li>' . __('Edit structure by following the "Structure" link.') . '</li>';
    $message .= sprintf(
        '<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">'
        . __('Options') . '</a>)</li>',
        $db_url,
        sprintf(
            __('Go to database: %s'),
            htmlspecialchars(PMA_Util::backquote($db_name))
        ),
        htmlspecialchars($db_name),
        $db_ops_url,
        sprintf(
            __('Edit settings for %s'),
            htmlspecialchars(PMA_Util::backquote($db_name))
        )
    );

    $message .= '<ul>';

    unset($params);

    $num_tables = count($tables);
    for ($i = 0; $i < $num_tables; ++$i) {
        $params = array(
             'db' => (string) $db_name,
             'table' => (string) $tables[$i][TBL_NAME]
        );
        $tbl_url = 'sql.php' . PMA_URL_getCommon($params);
        $tbl_struct_url = 'tbl_structure.php' . PMA_URL_getCommon($params);
        $tbl_ops_url = 'tbl_operations.php' . PMA_URL_getCommon($params);

        unset($params);

        if (! PMA_Table::isView($db_name, $tables[$i][TBL_NAME])) {
            $message .= sprintf(
                '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
                $tbl_url,
                sprintf(
                    __('Go to table: %s'),
                    htmlspecialchars(
                        PMA_Util::backquote($tables[$i][TBL_NAME])
                    )
                ),
                htmlspecialchars($tables[$i][TBL_NAME]),
                $tbl_struct_url,
                sprintf(
                    __('Structure of %s'),
                    htmlspecialchars(
                        PMA_Util::backquote($tables[$i][TBL_NAME])
                    )
                ),
                $tbl_ops_url,
                sprintf(
                    __('Edit settings for %s'),
                    htmlspecialchars(
                        PMA_Util::backquote($tables[$i][TBL_NAME])
                    )
                )
            );
        } else {
            $message .= sprintf(
                '<li><a href="%s" title="%s">%s</a></li>',
                $tbl_url,
                sprintf(
                    __('Go to view: %s'),
                    htmlspecialchars(
                        PMA_Util::backquote($tables[$i][TBL_NAME])
                    )
                ),
                htmlspecialchars($tables[$i][TBL_NAME])
            );
        }
    }

    $message .= '</ul></ul>';

    global $import_notice;
    $import_notice = $message;

    unset($tables);
}


/**
 * Stops the import on (mostly upload/file related) error
 *
 * @param PMA_Message $error_message The error message
 *
 * @return void
 * @access  public
 *
 */
function PMA_stopImport( PMA_Message $error_message )
{
    global $import_handle, $file_to_unlink;

    // Close open handles
    if ($import_handle !== false && $import_handle !== null) {
        fclose($import_handle);
    }

    // Delete temporary file
    if ($file_to_unlink != '') {
        unlink($file_to_unlink);
    }
    $msg = $error_message->getDisplay();
    $_SESSION['Import_message']['message'] = $msg;

    $response = PMA_Response::getInstance();
    $response->isSuccess(false);
    $response->addJSON('message', PMA_Message::error($msg));

    exit;
}

/**
 * Handles request for Simulation of UPDATE/DELETE queries.
 *
 * @return void
 */
function PMA_handleSimulateDMLRequest()
{
    $response = PMA_Response::getInstance();
    $error = false;
    $error_msg = __('Only single-table UPDATE and DELETE queries can be simulated.');
    $sql_delimiter = $_REQUEST['sql_delimiter'];
    $sql_data = array();
    $queries = explode($sql_delimiter, $GLOBALS['sql_query']);
    foreach ($queries as $sql_query) {
        if (empty($sql_query)) {
            continue;
        }

        // Parse and Analyze the query.
        $parsed_sql = PMA_SQP_parse($sql_query);
        $analyzed_sql = PMA_SQP_analyze($parsed_sql);
        $analyzed_sql_results = array(
            'parsed_sql' => $parsed_sql,
            'analyzed_sql' => $analyzed_sql
        );

        // Only UPDATE/DELETE queries accepted.
        $query_type = $analyzed_sql_results['analyzed_sql'][0]['querytype'];
        if ($query_type != 'UPDATE' && $query_type != 'DELETE') {
            $error = $error_msg;
            break;
        }

        // Only single-table queries accepted.
        $table_references = PMA_getTableReferences($analyzed_sql_results);
        $table_references = $table_references ? $table_references : '';
        if (preg_match('/JOIN/i', $table_references)) {
            $error = $error_msg;
            break;
        } else {
            $tables = explode(',', $table_references);
            if (count($tables) > 1) {
                $error = $error_msg;
                break;
            }
        }

        // Get the matched rows for the query.
        $result = PMA_getMatchedRows($analyzed_sql_results);
        if (! $error = $GLOBALS['dbi']->getError()) {
            $sql_data[] = $result;
        } else {
            break;
        }
    }

    if ($error) {
        $message = PMA_Message::rawError($error);
        $response->addJSON('message', $message);
        $response->addJSON('sql_data', false);
    } else {
        $response->addJSON('sql_data', $sql_data);
    }
}

/**
 * Find the matching rows for UPDATE/DELETE query.
 *
 * @param array $analyzed_sql_results Analyzed SQL results from parser.
 *
 * @return mixed
 */
function PMA_getMatchedRows($analyzed_sql_results = array())
{
    // Get the query type.
    $query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
        ? $analyzed_sql_results['analyzed_sql'][0]['querytype']
        : '';

    $matched_row_query = '';
    if ($query_type == 'DELETE') {
        $matched_row_query = PMA_getSimulatedDeleteQuery($analyzed_sql_results);
    } else if ($query_type == 'UPDATE') {
        $matched_row_query = PMA_getSimulatedUpdateQuery($analyzed_sql_results);
    }

    // Execute the query and get the number of matched rows.
    $matched_rows = PMA_executeMatchedRowQuery($matched_row_query);
    // URL to matched rows.
    $_url_params = array(
        'db'        => $GLOBALS['db'],
        'sql_query' => $matched_row_query
    );
    $matched_rows_url  = 'sql.php' . PMA_URL_getCommon($_url_params);

    return array(
        'sql_query' => PMA_Util::formatSql(
            $analyzed_sql_results['parsed_sql']['raw']
        ),
        'matched_rows' => $matched_rows,
        'matched_rows_url' => $matched_rows_url
    );
}

/**
 * Transforms a UPDATE query into SELECT statement.
 *
 * @param array $analyzed_sql_results Analyzed SQL results from parser.
 *
 * @return string SQL query
 */
function PMA_getSimulatedUpdateQuery($analyzed_sql_results)
{
    $where_clause = '';
    $extra_where_clause = '';
    $target_cols = array();

    $prev_term = '';
    $i = 0;
    foreach ($analyzed_sql_results['parsed_sql'] as $key => $term) {
        if (! isset($get_set_expr)
            && preg_match(
                '/\bSET\b/i',
                isset($term['data']) ? $term['data'] : ''
            )
        ) {
            $get_set_expr = true;
            continue;
        }

        if (isset($get_set_expr)) {
            if (preg_match(
                '/\bWHERE\b|\bORDER BY\b|\bLIMIT\b/i',
                isset($term['data']) ? $term['data'] : ''
            )
            ) {
                break;
            }

            if ($term['type'] == 'punct_listsep') {
                $extra_where_clause .= ' OR ';
            } else if ($term['type'] == 'punct') {
                $extra_where_clause .= ' <> ';
            } else {
                $extra_where_clause .= $term['data'];
            }

            // Get columns in SET expression.
            if ($prev_term != 'punct') {
                if ($term['type'] != 'punct_listsep'
                    && $term['type'] != 'punct'
                    && isset($term['data'])
                ) {
                    if (isset($target_cols[$i])) {
                        $target_cols[$i] .= $term['data'];
                    } else {
                        $target_cols[$i] = $term['data'];
                    }
                }
            } else {
                $i++;
            }

            $prev_term = $term['type'];
            continue;
        }
    }

    // Get table_references.
    $table_references = PMA_getTableReferences($analyzed_sql_results);
    $target_cols = implode(', ', $target_cols);

    // Get WHERE clause.
    $where_clause .= $analyzed_sql_results['analyzed_sql'][0]['where_clause'];
    if (empty($where_clause) && empty($extra_where_clause)) {
        $where_clause = '1';
    }

    $matched_row_query = 'SELECT '
        . $target_cols
        . ' FROM '
        . $table_references
        . ' WHERE '
        . $where_clause;

    return $matched_row_query;
}

/**
 * Transforms a DELETE query into SELECT statement.
 *
 * @param array $analyzed_sql_results Analyzed SQL results from parser.
 *
 * @return string SQL query
 */
function PMA_getSimulatedDeleteQuery($analyzed_sql_results)
{
    $where_clause = '';

    $where_clause .= $analyzed_sql_results['analyzed_sql'][0]['where_clause'];
    if (empty($where_clause) && empty($extra_where_clause)) {
        $where_clause = '1';
    }

    // Get the table_references.
    $table_references = PMA_getTableReferences($analyzed_sql_results);

    $matched_row_query = 'SELECT * '
        . ' FROM '
        . $table_references
        . ' WHERE '
        . $where_clause;

    return $matched_row_query;
}

/**
 * Finds table_references from a given query.
 * Queries Supported: INSERT, UPDATE, DELETE, REPLACE, ALTER, DROP, TRUNCATE
 *                    and RENAME.
 *
 * @param array $analyzed_sql_results Analyzed SQL results from parser
 *
 * @return string table_references
 */
function PMA_getTableReferences($analyzed_sql_results)
{
    $table_references = '';
    foreach ($analyzed_sql_results['parsed_sql'] as $key => $term) {
        // Skip first KeyWord and other invalid keys.
        if ($key == 0 || ! isset($term['data'])) {
            continue;
        }

        // Get the query type.
        $query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
            ? $analyzed_sql_results['analyzed_sql'][0]['querytype']
            : '';

        // Terms to 'ignore' from query for table_references.
        $ignore_re = '/';
        // Terminating condition for table_references.
        $terminate_re = '/';

        // Create relevant Regular Expressions.
        switch ($query_type) {
        case 'REPLACE':
        case 'INSERT':
            $ignore_re .= '\bINSERT\b|\bREPLACE\b|\bLOW_PRIORITY\b|\bDELAYED\b'
                . '|\bHIGH_PRIORITY\b|\bIGNORE\b|\bINTO\b';
            $terminate_re .= '\bPARTITION\b|\(|\bVALUE\b|\bVALUES\b|\bSELECT\b';
            break;
        case 'UPDATE':
            $ignore_re .= '\bUPDATE\b|\bLOW_PRIORITY\b|\bIGNORE\b';
            $terminate_re .= '\bSET\b|\bUSING\b';
            break;
        case 'DELETE':
            $ignore_re .= '\bDELETE\b|\bLOW_PRIORITY\b|\bQUICK\b|\bIGNORE\b'
                . '|\bFROM\b';
            $terminate_re .= '\bPARTITION\b|\bWHERE\b|\bORDER\b|\bLIMIT\b|\bUSING\b';
            break;
        case 'ALTER':
            $ignore_re .= '\bALTER\b|\bONLINE\b|\bOFFLINE\b|\bIGNORE\b|\bTABLE\b';
            $terminate_re .= '\bADD\b|\bALTER\b|\bCHANGE\b|\bMODIFY\b|\bDROP\b'
                . '|\bDISABLE\b|\bENABLE\b|\bRENAME\b|\bORDER\b|\bCONVERT\b'
                . '|\bDEFAULT\b|\bDISCARD\b|\bIMPORT\b|\bCOALESCE\b|\bREORGANIZE\b'
                . '|\bANALYZE\b|\bCHECK\b|\bOPTIMIZE\b|\bREBUILD\b|\bREPAIR\b'
                . '|\bPARTITION\b|\bREMOVE\b|\bCHARACTER\b';
            break;
        case 'DROP':
            $ignore_re .= '\bDROP\b|\bTEMPORARY\b|\bTABLE\b|\bIF\b|\bEXISTS\b';
            $terminate_re .= '\bRESTRICT\b|\bCASCADE\b';
            break;
        case 'TRUNCATE':
            $ignore_re .= '\bTRUNCATE\b|\bTABLE\b';
            $terminate_re .= '';
            break;
        case 'RENAME':
            $ignore_re .= '\bRENAME\b|\bTABLE\b';
            $terminate_re .= '\bTO\b';
            break;
        default:
            return false;
        }

        // Ignore 'case' in RegEx.
        $ignore_re .= '/i';
        $terminate_re .= '/i';

        if ($query_type != 'TRUNCATE'
            && preg_match($terminate_re, $term['data'])
        ) {
            break;
        }

        if (preg_match($ignore_re, $term['data'])
            || ! is_numeric($key)
            || $key == 0
        ) {
            continue;
        }

        $table_references .= ' ' . $term['data'];
    }

    return $table_references;
}

/**
 * Executes the matched_row_query and returns the resultant row count.
 *
 * @param string $matched_row_query SQL query
 *
 * @return integer Number of rows returned
 */
function PMA_executeMatchedRowQuery($matched_row_query)
{
    $GLOBALS['dbi']->selectDb($GLOBALS['db']);
    // Execute the query.
    $result = $GLOBALS['dbi']->tryQuery($matched_row_query);
    // Count the number of rows in the result set.
    $result = $GLOBALS['dbi']->numRows($result);

    return $result;
}

/**
 * Extracts unique table names from table_references.
 *
 * @param string $table_references table_references
 *
 * @return array $table_names
 */
function PMA_getTableNamesFromTableReferences($table_references)
{
    $table_names = array();
    $parsed_data = PMA_SQP_parse($table_references);

    $prev_term = array(
        'data' => '',
        'type' => ''
    );
    $on_encountered = false;
    $qualifier_encountered = false;
    $i = 0;
    foreach ($parsed_data as $key => $term) {
        // To skip first 'raw' key and other invalid keys.
        if (! is_numeric($key)
            || ! isset($term['data'])
            || ! isset($term['type'])
        ) {
            continue;
        }

        $add_to_table_names = true;

        // Un-quote the data, if any.
        if ($term['type'] == 'quote_backtick') {
            $term['data'] = PMA_Util::unQuote($term['data']);
            $term['type'] = 'alpha_identifier';
        }

        // New table name expected after 'JOIN' keyword.
        if (preg_match('/\bJOIN\b/i', $term['data'])) {
            $on_encountered = false;
        }

        // If term is a qualifier, set flag.
        if ($term['type'] == 'punct_qualifier') {
            $qualifier_encountered = true;
        }

        // Skip the JOIN conditions after 'ON' keyword.
        if (preg_match('/\bON\b/i', $term['data'])) {
            $on_encountered = true;
        }

        // If the word is not an 'identifier', skip it.
        if ($term['type'] != 'alpha_identifier') {
            $add_to_table_names = false;
        }

        // Skip table 'alias'.
        if (preg_match('/\bAS\b/i', $prev_term['data'])
            || $prev_term['type'] == 'alpha_identifier'
        ) {
            $add_to_table_names = false;
        }

        // Everything fine up to now, add name to list if 'unique'.
        if ($add_to_table_names
            && ! $on_encountered
            && ! in_array($term['data'], $table_names)
        ) {
            if (! $qualifier_encountered) {
                $table_names[] = PMA_Util::backquote($term['data']);
                $i++;
            } else {
                // If qualifier encountered, concatenate DB name and table name.
                $table_names[$i-1] = $table_names[$i-1]
                    . '.'
                    . PMA_Util::backquote($term['data']);
                $qualifier_encountered = false;
            }
        }

        // Update previous term.
        $prev_term = $term;
    }

    return $table_names;
}

/**
 * Handles request for ROLLBACK.
 *
 * @param string $sql_query SQL query(s)
 *
 * @return void
 */
function PMA_handleRollbackRequest($sql_query)
{
    $sql_delimiter = $_REQUEST['sql_delimiter'];
    $queries = explode($sql_delimiter, $sql_query);
    $error = false;
    $error_msg = __(
        'Only INSERT, UPDATE, DELETE and REPLACE '
        . 'SQL queries containing transactional engine tables can be rolled back.'
    );
    foreach ($queries as $sql_query) {
        if (empty($sql_query)) {
            continue;
        }

        // Check each query for ROLLBACK support.
        if (! PMA_checkIfRollbackPossible($sql_query)) {
            $global_error = $GLOBALS['dbi']->getError();
            if ($global_error) {
                $error = $global_error;
            } else {
                $error = $error_msg;
            }
            break;
        }
    }

    if ($error) {
        unset($_REQUEST['rollback_query']);
        $response = PMA_Response::getInstance();
        $message = PMA_Message::rawError($error);
        $response->addJSON('message', $message);
        exit;
    } else {
        // If everything fine, START a transaction.
        $GLOBALS['dbi']->query('START TRANSACTION');
    }
}

/**
 * Checks if ROLLBACK is possible for a SQL query or not.
 *
 * @param string $sql_query SQL query
 *
 * @return bool
 */
function PMA_checkIfRollbackPossible($sql_query)
{
    // Supported queries.
    $supported_queries = array(
        'INSERT',
        'UPDATE',
        'DELETE',
        'REPLACE'
    );

    // Parse and Analyze the query.
    $parsed_sql = PMA_SQP_parse($sql_query);
    $analyzed_sql = PMA_SQP_analyze($parsed_sql);
    $analyzed_sql_results = array(
        'parsed_sql' => $parsed_sql,
        'analyzed_sql' => $analyzed_sql
    );

    // Get the query type.
    $query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
        ? $analyzed_sql_results['analyzed_sql'][0]['querytype']
        : '';

    // Check if query is supported.
    if (! in_array($query_type, $supported_queries)) {
        return false;
    }

    // Get table_references from the query.
    $table_references = PMA_getTableReferences($analyzed_sql_results);
    $table_references = $table_references ? $table_references : '';
    // Get table names from table_references.
    $tables = PMA_getTableNamesFromTableReferences($table_references);

    // Check if each table is 'InnoDB'.
    foreach ($tables as $table) {
        if (! PMA_isTableTransactional($table)) {
            return false;
        }
    }

    return true;
}

/**
 * Checks if a table is 'InnoDB' or not.
 *
 * @param string $table Table details
 *
 * @return bool
 */
function PMA_isTableTransactional($table)
{
    $table = explode('.', $table);
    if (count($table) == 2) {
        $db = PMA_Util::unQuote($table[0]);
        $table = PMA_Util::unQuote($table[1]);
    } else {
        $db = $GLOBALS['db'];
        $table = PMA_Util::unQuote($table[0]);
    }

    // Query to check if table exists.
    $check_table_query = 'SELECT * FROM ' . PMA_Util::backquote($db)
        . '.' . PMA_Util::backquote($table) . ' '
        . 'LIMIT 1';

    $result = $GLOBALS['dbi']->tryQuery($check_table_query);

    if (! $result) {
        return false;
    }

    // List of Transactional Engines.
    $transactional_engines = array(
        'INNODB',
        'FALCON',
        'NDB',
        'INFINIDB',
        'TOKUDB',
        'XTRADB',
        'SEQUENCE',
        'BDB'
    );

    // Query to check if table is 'Transactional'.
    $check_query = 'SELECT `ENGINE` FROM `information_schema`.`tables` '
        . 'WHERE `table_name` = "' . $table . '" '
        . 'AND `table_schema` = "' . $db . '" '
        . 'AND UPPER(`engine`) IN ("'
        . implode('", "', $transactional_engines)
        . '")';

    $result = $GLOBALS['dbi']->tryQuery($check_query);

    if ($GLOBALS['dbi']->numRows($result) == 1) {
        return true;
    } else {
        return false;
    }
}
?>