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
|
<?php
/**
* set of functions with the insert/edit features in pma
*/
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Utils\Gis;
use function __;
use function array_fill;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function array_values;
use function bin2hex;
use function class_exists;
use function count;
use function current;
use function date;
use function explode;
use function htmlspecialchars;
use function implode;
use function in_array;
use function is_array;
use function is_file;
use function is_string;
use function max;
use function mb_stripos;
use function mb_strlen;
use function mb_strstr;
use function md5;
use function method_exists;
use function min;
use function password_hash;
use function preg_match;
use function preg_replace;
use function str_contains;
use function str_replace;
use function stripcslashes;
use function stripslashes;
use function strlen;
use function substr;
use function time;
use function trim;
use const ENT_COMPAT;
use const PASSWORD_DEFAULT;
/**
* PhpMyAdmin\InsertEdit class
*/
class InsertEdit
{
/**
* DatabaseInterface instance
*
* @var DatabaseInterface
*/
private $dbi;
/** @var Relation */
private $relation;
/** @var Transformations */
private $transformations;
/** @var FileListing */
private $fileListing;
/** @var Template */
public $template;
/**
* @param DatabaseInterface $dbi DatabaseInterface instance
*/
public function __construct(DatabaseInterface $dbi)
{
$this->dbi = $dbi;
$this->relation = new Relation($this->dbi);
$this->transformations = new Transformations();
$this->fileListing = new FileListing();
$this->template = new Template();
}
/**
* Retrieve form parameters for insert/edit form
*
* @param string $db name of the database
* @param string $table name of the table
* @param array|null $whereClauses where clauses
* @param array $whereClauseArray array of where clauses
* @param string $errorUrl error url
*
* @return array array of insert/edit form parameters
*/
public function getFormParametersForInsertForm(
$db,
$table,
?array $whereClauses,
array $whereClauseArray,
$errorUrl
): array {
$formParams = [
'db' => $db,
'table' => $table,
'goto' => $GLOBALS['goto'],
'err_url' => $errorUrl,
'sql_query' => $_POST['sql_query'] ?? '',
];
if (isset($whereClauses)) {
foreach ($whereClauseArray as $keyId => $whereClause) {
$formParams['where_clause[' . $keyId . ']'] = trim($whereClause);
}
}
if (isset($_POST['clause_is_unique'])) {
$formParams['clause_is_unique'] = $_POST['clause_is_unique'];
}
return $formParams;
}
/**
* Creates array of where clauses
*
* @param array|string|null $whereClause where clause
*
* @return array whereClauseArray array of where clauses
*/
private function getWhereClauseArray($whereClause): array
{
if ($whereClause === null) {
return [];
}
if (is_array($whereClause)) {
return $whereClause;
}
return [0 => $whereClause];
}
/**
* Analysing where clauses array
*
* @param array $whereClauseArray array of where clauses
* @param string $table name of the table
* @param string $db name of the database
*
* @return array $where_clauses, $result, $rows, $found_unique_key
*/
private function analyzeWhereClauses(
array $whereClauseArray,
$table,
$db
): array {
$rows = [];
$result = [];
$whereClauses = [];
$foundUniqueKey = false;
foreach ($whereClauseArray as $keyId => $whereClause) {
$localQuery = 'SELECT * FROM '
. Util::backquote($db) . '.'
. Util::backquote($table)
. ' WHERE ' . $whereClause . ';';
$result[$keyId] = $this->dbi->query($localQuery);
$rows[$keyId] = $result[$keyId]->fetchAssoc();
$whereClauses[$keyId] = str_replace('\\', '\\\\', $whereClause);
$hasUniqueCondition = $this->showEmptyResultMessageOrSetUniqueCondition(
$rows,
$keyId,
$whereClauseArray,
$localQuery,
$result
);
if (! $hasUniqueCondition) {
continue;
}
$foundUniqueKey = true;
}
return [
$whereClauses,
$result,
$rows,
$foundUniqueKey,
];
}
/**
* Show message for empty result or set the unique_condition
*
* @param array $rows MySQL returned rows
* @param string $keyId ID in current key
* @param array $whereClauseArray array of where clauses
* @param string $localQuery query performed
* @param ResultInterface[] $result MySQL result handle
*/
private function showEmptyResultMessageOrSetUniqueCondition(
array $rows,
$keyId,
array $whereClauseArray,
$localQuery,
array $result
): bool {
// No row returned
if (! $rows[$keyId]) {
unset($rows[$keyId], $whereClauseArray[$keyId]);
ResponseRenderer::getInstance()->addHTML(
Generator::getMessage(
__('MySQL returned an empty result set (i.e. zero rows).'),
$localQuery
)
);
/**
* @todo not sure what should be done at this point, but we must not
* exit if we want the message to be displayed
*/
return false;
}
$meta = $this->dbi->getFieldsMeta($result[$keyId]);
[$uniqueCondition] = Util::getUniqueCondition(
count($meta),
$meta,
$rows[$keyId],
true
);
return (bool) $uniqueCondition;
}
/**
* 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
*/
private function loadFirstRow($table, $db)
{
$result = $this->dbi->query(
'SELECT * FROM ' . Util::backquote($db)
. '.' . Util::backquote($table) . ' LIMIT 1;'
);
// Can be a string on some old configuration storage settings
$rows = array_fill(0, (int) $GLOBALS['cfg']['InsertRows'], false);
return [
$result,
$rows,
];
}
/**
* Add some url parameters
*
* @param array $urlParams containing $db and $table as url parameters
* @param array $whereClauseArray where clauses array
*
* @return array Add some url parameters to $url_params array and return it
*/
public function urlParamsInEditMode(
array $urlParams,
array $whereClauseArray
): array {
foreach ($whereClauseArray as $whereClause) {
$urlParams['where_clause'] = trim($whereClause);
}
if (! empty($_POST['sql_query'])) {
$urlParams['sql_query'] = $_POST['sql_query'];
}
return $urlParams;
}
/**
* Show type information or function selectors in Insert/Edit
*
* @param string $which function|type
* @param array $urlParams containing url parameters
* @param bool $isShow whether to show the element in $which
*
* @return string an HTML snippet
*/
public function showTypeOrFunction($which, array $urlParams, $isShow): string
{
$params = [];
switch ($which) {
case 'function':
$params['ShowFunctionFields'] = ($isShow ? 0 : 1);
$params['ShowFieldTypesInDataEditView'] = $GLOBALS['cfg']['ShowFieldTypesInDataEditView'];
break;
case 'type':
$params['ShowFieldTypesInDataEditView'] = ($isShow ? 0 : 1);
$params['ShowFunctionFields'] = $GLOBALS['cfg']['ShowFunctionFields'];
break;
}
$params['goto'] = Url::getFromRoute('/sql');
$thisUrlParams = array_merge($urlParams, $params);
if (! $isShow) {
return ' : <a href="' . Url::getFromRoute('/table/change') . '" data-post="'
. Url::getCommon($thisUrlParams, '', false) . '">'
. $this->showTypeOrFunctionLabel($which)
. '</a>';
}
return '<th><a href="' . Url::getFromRoute('/table/change') . '" data-post="'
. Url::getCommon($thisUrlParams, '', false)
. '" title="' . __('Hide') . '">'
. $this->showTypeOrFunctionLabel($which)
. '</a></th>';
}
/**
* Show type information or function selectors labels in Insert/Edit
*
* @param string $which function|type
*
* @return string an HTML snippet
*/
private function showTypeOrFunctionLabel($which): string
{
switch ($which) {
case 'function':
return __('Function');
case 'type':
return __('Type');
}
return '';
}
/**
* Analyze the table column array
*
* @param array $column description of column in given table
* @param array $commentsMap comments for every column that has a comment
* @param bool $timestampSeen whether a timestamp has been seen
*
* @return array description of column in given table
*/
private function analyzeTableColumnsArray(
array $column,
array $commentsMap,
$timestampSeen
) {
$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'] = $this->getColumnTitle($column, $commentsMap);
$column['is_binary'] = $this->isColumn(
$column,
[
'binary',
'varbinary',
]
);
$column['is_blob'] = $this->isColumn(
$column,
[
'blob',
'tinyblob',
'mediumblob',
'longblob',
]
);
$column['is_char'] = $this->isColumn(
$column,
[
'char',
'varchar',
]
);
[
$column['pma_type'],
$column['wrap'],
$column['first_timestamp'],
] = $this->getEnumSetAndTimestampColumns($column, $timestampSeen);
return $column;
}
/**
* Retrieve the column title
*
* @param array $column description of column in given table
* @param array $commentsMap comments for every column that has a comment
*
* @return string column title
*/
private function getColumnTitle(array $column, array $commentsMap): string
{
if (isset($commentsMap[$column['Field']])) {
return '<span style="border-bottom: 1px dashed black;" title="'
. htmlspecialchars($commentsMap[$column['Field']]) . '">'
. htmlspecialchars($column['Field']) . '</span>';
}
return htmlspecialchars($column['Field']);
}
/**
* 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 string[] $types the types to verify
*/
public function isColumn(array $column, array $types): bool
{
foreach ($types as $oneType) {
if (mb_stripos($column['Type'], $oneType) === 0) {
return true;
}
}
return false;
}
/**
* Retrieve set, enum, timestamp table columns
*
* @param array $column description of column in given table
* @param bool $timestampSeen whether a timestamp has been seen
*
* @return array $column['pma_type'], $column['wrap'], $column['first_timestamp']
* @psalm-return array{0: mixed, 1: string, 2: bool}
*/
private function getEnumSetAndTimestampColumns(array $column, $timestampSeen)
{
switch ($column['True_Type']) {
case 'set':
return [
'set',
'',
false,
];
case 'enum':
return [
'enum',
'',
false,
];
case 'timestamp':
return [
$column['Type'],
' text-nowrap',
! $timestampSeen, // can only occur once per table
];
default:
return [
$column['Type'],
' text-nowrap',
false,
];
}
}
/**
* 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
*/
private function getNullifyCodeForNullColumn(
array $column,
array $foreigners,
array $foreignData
): string {
$foreigner = $this->relation->searchColumnInForeigners($foreigners, $column['Field']);
if (mb_strstr($column['True_Type'], 'enum')) {
if (mb_strlen((string) $column['Type']) > 20) {
$nullifyCode = '1';
} else {
$nullifyCode = '2';
}
} elseif (mb_strstr($column['True_Type'], 'set')) {
$nullifyCode = '3';
} elseif ($foreigner && $foreignData['foreign_link'] == false) {
// foreign key in a drop-down
$nullifyCode = '4';
} elseif ($foreigner && $foreignData['foreign_link'] == true) {
// foreign key with a browsing icon
$nullifyCode = '6';
} else {
$nullifyCode = '5';
}
return $nullifyCode;
}
/**
* Get HTML textarea for insert form
*
* @param array $column column information
* @param string $backupField hidden input field
* @param string $columnNameAppendix the name attribute
* @param string $onChangeClause onchange clause for fields
* @param int $tabindex tab index
* @param int $tabindexForValue offset for the values tabindex
* @param int $idindex id index
* @param string $textDir text direction
* @param string $specialCharsEncoded replaced char if the string starts
* with a \r\n pair (0x0d0a) add an extra \n
* @param string $dataType the html5 data-* attribute type
* @param bool $readOnly is column read only or not
*
* @return string an html snippet
*/
private function getTextarea(
array $column,
$backupField,
$columnNameAppendix,
$onChangeClause,
$tabindex,
$tabindexForValue,
$idindex,
$textDir,
$specialCharsEncoded,
$dataType,
$readOnly
): string {
$theClass = '';
$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
*/
$theClass = 'char charField';
$textAreaRows = $GLOBALS['cfg']['CharTextareaRows'];
$textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
$extractedColumnspec = Util::extractColumnSpec($column['Type']);
$maxlength = $extractedColumnspec['spec_in_brackets'];
} elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
$textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
$textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
}
return $backupField . "\n"
. '<textarea name="fields' . $columnNameAppendix . '"'
. ' class="' . $theClass . '"'
. ($readOnly ? ' readonly="readonly"' : '')
. (isset($maxlength) ? ' data-maxlength="' . $maxlength . '"' : '')
. ' rows="' . $textAreaRows . '"'
. ' cols="' . $textareaCols . '"'
. ' dir="' . $textDir . '"'
. ' id="field_' . $idindex . '_3"'
. ($onChangeClause ? ' ' . $onChangeClause : '')
. ' tabindex="' . ($tabindex + $tabindexForValue) . '"'
. ' data-type="' . $dataType . '">'
. $specialCharsEncoded
. '</textarea>';
}
/**
* Get column values
*
* @param string[] $enum_set_values
*
* @return array column values as an associative array
* @psalm-return list<array{html: string, plain: string}>
*/
private function getColumnEnumValues(array $enum_set_values): array
{
$values = [];
foreach ($enum_set_values as $val) {
$values[] = [
'plain' => $val,
'html' => htmlspecialchars($val),
];
}
return $values;
}
/**
* Retrieve column 'set' value and select size
*
* @param array $column description of column in given table
* @param string[] $enum_set_values
*
* @return array $column['values'], $column['select_size']
*/
private function getColumnSetValueAndSelectSize(
array $column,
array $enum_set_values
): array {
if (! isset($column['values'])) {
$column['values'] = [];
foreach ($enum_set_values as $val) {
$column['values'][] = [
'plain' => $val,
'html' => htmlspecialchars($val),
];
}
$column['select_size'] = min(4, count($column['values']));
}
return [
$column['values'],
$column['select_size'],
];
}
/**
* Get HTML input type
*
* @param array $column description of column in given table
* @param string $columnNameAppendix the name attribute
* @param string $specialChars special characters
* @param int $fieldsize html field size
* @param string $onChangeClause onchange clause for fields
* @param int $tabindex tab index
* @param int $tabindexForValue offset for the values tabindex
* @param int $idindex id index
* @param string $dataType the html5 data-* attribute type
* @param bool $readOnly is column read only or not
*
* @return string an html snippet
*/
private function getHtmlInput(
array $column,
$columnNameAppendix,
$specialChars,
$fieldsize,
$onChangeClause,
$tabindex,
$tabindexForValue,
$idindex,
$dataType,
$readOnly
): string {
$theClass = 'textfield';
// verify True_Type which does not contain the parentheses and length
if (! $readOnly) {
if ($column['True_Type'] === 'date') {
$theClass .= ' datefield';
} elseif ($column['True_Type'] === 'time') {
$theClass .= ' timefield';
} elseif ($column['True_Type'] === 'datetime' || $column['True_Type'] === 'timestamp') {
$theClass .= ' datetimefield';
}
}
$inputMinMax = '';
if (in_array($column['True_Type'], $this->dbi->types->getIntegerTypes())) {
$extractedColumnspec = Util::extractColumnSpec($column['Type']);
$isUnsigned = $extractedColumnspec['unsigned'];
$minMaxValues = $this->dbi->types->getIntegerRange($column['True_Type'], ! $isUnsigned);
$inputMinMax = 'min="' . $minMaxValues[0] . '" '
. 'max="' . $minMaxValues[1] . '"';
$dataType = 'INT';
}
// do not use the 'date' or 'time' types here; they have no effect on some
// browsers and create side effects (see bug #4218)
return '<input type="text"'
. ' name="fields' . $columnNameAppendix . '"'
. ' value="' . $specialChars . '" size="' . $fieldsize . '"'
. (isset($column['is_char']) && $column['is_char']
? ' data-maxlength="' . $fieldsize . '"'
: '')
. ($readOnly ? ' readonly="readonly"' : '')
. ($inputMinMax ? ' ' . $inputMinMax : '')
. ' data-type="' . $dataType . '"'
. ' class="' . $theClass . '" ' . $onChangeClause
. ' tabindex="' . ($tabindex + $tabindexForValue) . '"'
. ' id="field_' . $idindex . '_3">';
}
/**
* Get HTML select option for upload
*
* @param string $vkey [multi_edit]['row_id']
* @param string $fieldHashMd5 array index as an MD5 to avoid having special characters
*
* @return string an HTML snippet
*/
private function getSelectOptionForUpload(string $vkey, string $fieldHashMd5): string
{
$files = $this->fileListing->getFileSelectOptions(
Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? ''))
);
if ($files === false) {
return '<span style="color:red">' . __('Error') . '</span><br>' . "\n"
. __('The directory you set for upload work cannot be reached.') . "\n";
}
if ($files === '') {
return '';
}
return "<br>\n"
. '<i>' . __('Or') . '</i> '
. __('web server upload directory:') . '<br>' . "\n"
. '<select size="1" name="fields_uploadlocal'
. $vkey . '[' . $fieldHashMd5 . ']">' . "\n"
. '<option value="" selected="selected"></option>' . "\n"
. $files
. '</select>' . "\n";
}
/**
* Retrieve the maximum upload file size
*
* @param string $pma_type column type
* @param int $biggestMaxFileSize biggest max file size for uploading
*
* @return array an html snippet and $biggest_max_file_size
* @psalm-return array{non-empty-string, int}
*/
private function getMaxUploadSize(string $pma_type, $biggestMaxFileSize): array
{
// 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
*/
$maxFieldSizes = [
'tinyblob' => 256,
'blob' => 65536,
'mediumblob' => 16777216,
'longblob' => 4294967296,// yeah, really
];
$thisFieldMaxSize = (int) $GLOBALS['config']->get('max_upload_size'); // from PHP max
if ($thisFieldMaxSize > $maxFieldSizes[$pma_type]) {
$thisFieldMaxSize = $maxFieldSizes[$pma_type];
}
$htmlOutput = Util::getFormattedMaximumUploadSize($thisFieldMaxSize) . "\n";
// do not generate here the MAX_FILE_SIZE, because we should
// put only one in the form to accommodate the biggest field
if ($thisFieldMaxSize > $biggestMaxFileSize) {
$biggestMaxFileSize = $thisFieldMaxSize;
}
return [
$htmlOutput,
$biggestMaxFileSize,
];
}
/**
* 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 $defaultCharEditing default char editing mode which is stored
* in the config.inc.php script
* @param string $backupField hidden input field
* @param string $columnNameAppendix the name attribute
* @param string $onChangeClause onchange clause for fields
* @param int $tabindex tab index
* @param string $specialChars special characters
* @param int $tabindexForValue offset for the values tabindex
* @param int $idindex id index
* @param string $textDir text direction
* @param string $specialCharsEncoded replaced char if the string starts
* with a \r\n pair (0x0d0a) add an extra \n
* @param string $data data to edit
* @param array $extractedColumnspec associative array containing type,
* spec_in_brackets and possibly
* enum_set_values (another array)
* @param bool $readOnly is column read only or not
*
* @return string an html snippet
*/
private function getValueColumnForOtherDatatypes(
array $column,
$defaultCharEditing,
$backupField,
$columnNameAppendix,
$onChangeClause,
$tabindex,
$specialChars,
$tabindexForValue,
$idindex,
$textDir,
$specialCharsEncoded,
$data,
array $extractedColumnspec,
$readOnly
): string {
// HTML5 data-* attribute data-type
$dataType = $this->dbi->types->getTypeClass($column['True_Type']);
$fieldsize = $this->getColumnSize($column, $extractedColumnspec['spec_in_brackets']);
$htmlOutput = $backupField . "\n";
if ($column['is_char'] && ($GLOBALS['cfg']['CharEditing'] === 'textarea' || str_contains($data, "\n"))) {
$htmlOutput .= "\n";
$GLOBALS['cfg']['CharEditing'] = $defaultCharEditing;
$htmlOutput .= $this->getTextarea(
$column,
$backupField,
$columnNameAppendix,
$onChangeClause,
$tabindex,
$tabindexForValue,
$idindex,
$textDir,
$specialCharsEncoded,
$dataType,
$readOnly
);
} else {
$htmlOutput .= $this->getHtmlInput(
$column,
$columnNameAppendix,
$specialChars,
$fieldsize,
$onChangeClause,
$tabindex,
$tabindexForValue,
$idindex,
$dataType,
$readOnly
);
if (
preg_match('/(VIRTUAL|PERSISTENT|GENERATED)/', $column['Extra'])
&& ! str_contains($column['Extra'], 'DEFAULT_GENERATED')
) {
$htmlOutput .= '<input type="hidden" name="virtual'
. $columnNameAppendix . '" value="1">';
}
if ($column['Extra'] === 'auto_increment') {
$htmlOutput .= '<input type="hidden" name="auto_increment'
. $columnNameAppendix . '" value="1">';
}
if (substr($column['pma_type'], 0, 9) === 'timestamp') {
$htmlOutput .= '<input type="hidden" name="fields_type'
. $columnNameAppendix . '" value="timestamp">';
}
if (substr($column['pma_type'], 0, 4) === 'date') {
$type = substr($column['pma_type'], 0, 8) === 'datetime' ? 'datetime' : 'date';
$htmlOutput .= '<input type="hidden" name="fields_type'
. $columnNameAppendix . '" value="' . $type . '">';
}
if (in_array($column['True_Type'], ['bit', 'uuid'], true)) {
$htmlOutput .= '<input type="hidden" name="fields_type'
. $columnNameAppendix . '" value="' . $column['True_Type'] . '">';
}
}
return $htmlOutput;
}
/**
* Get the field size
*
* @param array $column description of column in given table
* @param string $specInBrackets text in brackets inside column definition
*
* @return int field size
*/
private function getColumnSize(array $column, string $specInBrackets): int
{
if ($column['is_char']) {
$fieldsize = (int) $specInBrackets;
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 continue insertion form
*
* @param string $table name of the table
* @param string $db name of the database
* @param array $whereClauseArray array of where clauses
* @param string $errorUrl error url
*
* @return string an html snippet
*/
public function getContinueInsertionForm(
$table,
$db,
array $whereClauseArray,
$errorUrl
): string {
return $this->template->render('table/insert/continue_insertion_form', [
'db' => $db,
'table' => $table,
'where_clause_array' => $whereClauseArray,
'err_url' => $errorUrl,
'goto' => $GLOBALS['goto'],
'sql_query' => $_POST['sql_query'] ?? null,
'has_where_clause' => isset($_POST['where_clause']),
'insert_rows_default' => $GLOBALS['cfg']['InsertRows'],
]);
}
/**
* @param string[]|string|null $whereClause
*
* @psalm-pure
*/
public static function isWhereClauseNumeric($whereClause): bool
{
if ($whereClause === null) {
return false;
}
if (! is_array($whereClause)) {
$whereClause = [$whereClause];
}
// If we have just numeric primary key, we can also edit next
// we are looking for `table_name`.`field_name` = numeric_value
foreach ($whereClause as $clause) {
// preg_match() returns 1 if there is a match
$isNumeric = preg_match('@^[\s]*`[^`]*`[\.]`[^`]*` = [0-9]+@', $clause) === 1;
if ($isNumeric) {
return true;
}
}
return false;
}
/**
* Get table head and table foot for insert row table
*
* @param array $urlParams url parameters
*
* @return string an html snippet
*/
private function getHeadAndFootOfInsertRowTable(array $urlParams): string
{
$type = '';
$function = '';
if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
$type = $this->showTypeOrFunction('type', $urlParams, true);
}
if ($GLOBALS['cfg']['ShowFunctionFields']) {
$function = $this->showTypeOrFunction('function', $urlParams, true);
}
$template = new Template();
return $template->render('table/insert/get_head_and_foot_of_insert_row_table', [
'type' => $type,
'function' => $function,
]);
}
/**
* Prepares the field value and retrieve special chars, backup field and data array
*
* @param array $currentRow a row of the table
* @param array $column description of column in given table
* @param array $extractedColumnspec associative array containing type,
* spec_in_brackets and possibly
* enum_set_values (another array)
* @param array $gisDataTypes list of GIS data types
* @param string $columnNameAppendix string to append to column name in input
* @param bool $asIs use the data as is, used in repopulating
*
* @return array $real_null_value, $data, $special_chars, $backup_field,
* $special_chars_encoded
*/
private function getSpecialCharsAndBackupFieldForExistingRow(
array $currentRow,
array $column,
array $extractedColumnspec,
array $gisDataTypes,
$columnNameAppendix,
$asIs
) {
$specialCharsEncoded = '';
$data = null;
$realNullValue = false;
// (we are editing)
if (! isset($currentRow[$column['Field']])) {
$realNullValue = true;
$currentRow[$column['Field']] = '';
$specialChars = '';
$data = $currentRow[$column['Field']];
} elseif ($column['True_Type'] === 'bit') {
$specialChars = $asIs
? $currentRow[$column['Field']]
: Util::printableBitValue(
(int) $currentRow[$column['Field']],
(int) $extractedColumnspec['spec_in_brackets']
);
} elseif (
(substr($column['True_Type'], 0, 9) === 'timestamp'
|| $column['True_Type'] === 'datetime'
|| $column['True_Type'] === 'time')
&& (str_contains($currentRow[$column['Field']], '.'))
) {
$currentRow[$column['Field']] = $asIs
? $currentRow[$column['Field']]
: Util::addMicroseconds($currentRow[$column['Field']]);
$specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
} elseif (in_array($column['True_Type'], $gisDataTypes)) {
// Convert gis data to Well Know Text format
$currentRow[$column['Field']] = $asIs
? $currentRow[$column['Field']]
: Gis::convertToWellKnownText($currentRow[$column['Field']], true);
$specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
} else {
// special binary "characters"
if ($column['is_binary'] || ($column['is_blob'] && $GLOBALS['cfg']['ProtectBinary'] !== 'all')) {
$currentRow[$column['Field']] = $asIs
? $currentRow[$column['Field']]
: bin2hex($currentRow[$column['Field']]);
}
$specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
//We need to duplicate the first \n or otherwise we will lose
//the first newline entered in a VARCHAR or TEXT column
$specialCharsEncoded = Util::duplicateFirstNewline($specialChars);
$data = $currentRow[$column['Field']];
}
//when copying row, it is useful to empty auto-increment column
// to prevent duplicate key error
if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
if ($column['Key'] === 'PRI' && str_contains($column['Extra'], 'auto_increment')) {
$data = $specialCharsEncoded = $specialChars = 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
$backupField = '<input type="hidden" name="fields_prev'
. $columnNameAppendix . '" value="'
. htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT) . '">';
return [
$realNullValue,
$specialCharsEncoded,
$specialChars,
$data,
$backupField,
];
}
/**
* display default values
*
* @param array $column description of column in given table
*
* @return array $real_null_value, $data, $special_chars,
* $backup_field, $special_chars_encoded
* @psalm-return array{bool, mixed, string, string, string}
*/
private function getSpecialCharsAndBackupFieldForInsertingMode(
array $column
) {
if (! isset($column['Default'])) {
$column['Default'] = '';
$realNullValue = true;
$data = '';
} else {
$realNullValue = false;
$data = $column['Default'];
}
$trueType = $column['True_Type'];
if ($trueType === 'bit') {
$specialChars = Util::convertBitDefaultValue($column['Default']);
} elseif (substr($trueType, 0, 9) === 'timestamp' || $trueType === 'datetime' || $trueType === 'time') {
$specialChars = Util::addMicroseconds($column['Default']);
} elseif ($trueType === 'binary' || $trueType === 'varbinary') {
$specialChars = bin2hex($column['Default']);
} elseif (substr($trueType, -4) === 'text') {
$textDefault = (string) substr($column['Default'], 1, -1);
$specialChars = htmlspecialchars(stripcslashes($textDefault !== '' ? $textDefault : $column['Default']));
} else {
$specialChars = htmlspecialchars($column['Default']);
}
$specialCharsEncoded = Util::duplicateFirstNewline($specialChars);
return [
$realNullValue,
$data,
$specialChars,
'',
$specialCharsEncoded,
];
}
/**
* Prepares the update/insert of a row
*
* @return array $loop_array, $using_key, $is_insert, $is_insertignore
* @psalm-return array{array, bool, bool, bool}
*/
public function getParamsForUpdateOrInsert()
{
if (isset($_POST['where_clause'])) {
// we were editing something => use the WHERE clause
$loopArray = is_array($_POST['where_clause'])
? $_POST['where_clause']
: [$_POST['where_clause']];
$usingKey = true;
$isInsert = isset($_POST['submit_type'])
&& ($_POST['submit_type'] === 'insert'
|| $_POST['submit_type'] === 'showinsert'
|| $_POST['submit_type'] === 'insertignore');
} else {
// new row => use indexes
$loopArray = [];
if (! empty($_POST['fields'])) {
$loopArray = array_keys($_POST['fields']['multi_edit']);
}
$usingKey = false;
$isInsert = true;
}
$isInsertIgnore = isset($_POST['submit_type'])
&& $_POST['submit_type'] === 'insertignore';
return [
$loopArray,
$usingKey,
$isInsert,
$isInsertIgnore,
];
}
/**
* set $_SESSION for edit_next
*
* @param string $oneWhereClause one where clause from where clauses array
*/
public function setSessionForEditNext($oneWhereClause): void
{
$localQuery = 'SELECT * FROM ' . Util::backquote($GLOBALS['db'])
. '.' . Util::backquote($GLOBALS['table']) . ' WHERE '
. str_replace('` =', '` >', $oneWhereClause) . ' LIMIT 1;';
$res = $this->dbi->query($localQuery);
$row = $res->fetchRow();
$meta = $this->dbi->getFieldsMeta($res);
// must find a unique condition based on unique key,
// not a combination of all fields
[$uniqueCondition] = Util::getUniqueCondition(
count($meta),
$meta,
$row,
true
);
if (! $uniqueCondition) {
return;
}
$_SESSION['edit_next'] = $uniqueCondition;
}
/**
* 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|false $gotoInclude store some script for include, otherwise it is
* boolean false
*/
public function getGotoInclude($gotoInclude): string
{
$validOptions = [
'new_insert',
'same_insert',
'edit_next',
];
if (isset($_POST['after_insert']) && in_array($_POST['after_insert'], $validOptions)) {
return '/table/change';
}
if (! empty($GLOBALS['goto'])) {
if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
// this should NOT happen
//$GLOBALS['goto'] = false;
if ($GLOBALS['goto'] === 'index.php?route=/sql') {
$gotoInclude = '/sql';
} else {
$gotoInclude = false;
}
} else {
$gotoInclude = $GLOBALS['goto'];
}
if ($GLOBALS['goto'] === 'index.php?route=/database/sql' && strlen($GLOBALS['table']) > 0) {
$GLOBALS['table'] = '';
}
}
if (! $gotoInclude) {
if (strlen($GLOBALS['table']) === 0) {
$gotoInclude = '/database/sql';
} else {
$gotoInclude = '/table/sql';
}
}
return $gotoInclude;
}
/**
* Defines the url to return in case of failure of the query
*
* @param array $urlParams url parameters
*
* @return string error url for query failure
*/
public function getErrorUrl(array $urlParams)
{
if (isset($_POST['err_url'])) {
return $_POST['err_url'];
}
return Url::getFromRoute('/table/change', $urlParams);
}
/**
* Builds the sql query
*
* @param bool $isInsertIgnore $_POST['submit_type'] === 'insertignore'
* @param array $queryFields column names array
* @param array $valueSets array of query values
*
* @return array of query
* @psalm-return array{string}
*/
public function buildSqlQuery(bool $isInsertIgnore, array $queryFields, array $valueSets)
{
if ($isInsertIgnore) {
$insertCommand = 'INSERT IGNORE ';
} else {
$insertCommand = 'INSERT ';
}
return [
$insertCommand . 'INTO '
. Util::backquote($GLOBALS['table'])
. ' (' . implode(', ', $queryFields) . ') VALUES ('
. implode('), (', $valueSets) . ')',
];
}
/**
* Executes the sql query and get the result, then move back to the calling page
*
* @param array $urlParams url parameters array
* @param array $query built query from buildSqlQuery()
*
* @return array $url_params, $total_affected_rows, $last_messages
* $warning_messages, $error_messages, $return_to_sql_query
*/
public function executeSqlQuery(array $urlParams, array $query)
{
$returnToSqlQuery = '';
if (! empty($GLOBALS['sql_query'])) {
$urlParams['sql_query'] = $GLOBALS['sql_query'];
$returnToSqlQuery = $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'];
$totalAffectedRows = 0;
$lastMessages = [];
$warningMessages = [];
$errorMessages = [];
foreach ($query as $singleQuery) {
if (isset($_POST['submit_type']) && $_POST['submit_type'] === 'showinsert') {
$lastMessages[] = Message::notice(__('Showing SQL query'));
continue;
}
if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
$result = $this->dbi->tryQuery($singleQuery);
} else {
$result = $this->dbi->query($singleQuery);
}
if (! $result) {
$errorMessages[] = $this->dbi->getError();
} else {
$totalAffectedRows += $this->dbi->affectedRows();
$insertId = $this->dbi->insertId();
if ($insertId) {
// insert_id is id of FIRST record inserted in one insert, so if we
// inserted multiple rows, we had to increment this
if ($totalAffectedRows > 0) {
$insertId += $totalAffectedRows - 1;
}
$lastMessage = Message::notice(__('Inserted row id: %1$d'));
$lastMessage->addParam($insertId);
$lastMessages[] = $lastMessage;
}
}
$warningMessages = $this->getWarningMessages();
}
return [
$urlParams,
$totalAffectedRows,
$lastMessages,
$warningMessages,
$errorMessages,
$returnToSqlQuery,
];
}
/**
* get the warning messages array
*
* @return string[]
*/
private function getWarningMessages(): array
{
$warningMessages = [];
foreach ($this->dbi->getWarnings() as $warning) {
$warningMessages[] = htmlspecialchars((string) $warning);
}
return $warningMessages;
}
/**
* Column to display from the foreign table?
*
* @param string $whereComparison 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 $relationField relation field
*
* @return string display value from the foreign table
*/
public function getDisplayValueForForeignTableColumn(
$whereComparison,
array $map,
$relationField
) {
$foreigner = $this->relation->searchColumnInForeigners($map, $relationField);
if (! is_array($foreigner)) {
return '';
}
$displayField = $this->relation->getDisplayField($foreigner['foreign_db'], $foreigner['foreign_table']);
// Field to display from the foreign table?
if (is_string($displayField) && strlen($displayField) > 0) {
$dispsql = 'SELECT ' . Util::backquote($displayField)
. ' FROM ' . Util::backquote($foreigner['foreign_db'])
. '.' . Util::backquote($foreigner['foreign_table'])
. ' WHERE ' . Util::backquote($foreigner['foreign_field'])
. $whereComparison;
$dispresult = $this->dbi->tryQuery($dispsql);
if ($dispresult && $dispresult->numRows() > 0) {
return (string) $dispresult->fetchValue();
}
}
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 $relationField relation field
* @param string $whereComparison string that contain relation field value
* @param string $dispval display value from the foreign table
* @param string $relationFieldValue relation field value
*
* @return string HTML <a> tag
*/
public function getLinkForRelationalDisplayField(
array $map,
$relationField,
$whereComparison,
$dispval,
$relationFieldValue
): string {
$foreigner = $this->relation->searchColumnInForeigners($map, $relationField);
if (! is_array($foreigner)) {
return '';
}
if ($_SESSION['tmpval']['relational_display'] === 'K') {
// user chose "relational key" in the display options, so
// the title contains the display field
$title = $dispval
? ' title="' . htmlspecialchars($dispval) . '"'
: '';
} else {
$title = ' title="' . htmlspecialchars($relationFieldValue) . '"';
}
$sqlQuery = 'SELECT * FROM '
. Util::backquote($foreigner['foreign_db'])
. '.' . Util::backquote($foreigner['foreign_table'])
. ' WHERE ' . Util::backquote($foreigner['foreign_field'])
. $whereComparison;
$urlParams = [
'db' => $foreigner['foreign_db'],
'table' => $foreigner['foreign_table'],
'pos' => '0',
'sql_signature' => Core::signSqlQuery($sqlQuery),
'sql_query' => $sqlQuery,
];
$output = '<a href="' . Url::getFromRoute('/sql', $urlParams) . '"' . $title . '>';
if ($_SESSION['tmpval']['relational_display'] === 'D') {
// user chose "relational display field" in the
// display options, so show display field in the cell
$output .= htmlspecialchars($dispval);
} else {
// otherwise display data in the cell
$output .= htmlspecialchars($relationFieldValue);
}
$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 $editedValues transform columns list and new values
* @param string $file file containing the transformation plugin
* @param string $columnName column name
* @param array $extraData extra data array
* @param string $type the type of transformation
*
* @return array
*/
public function transformEditedValues(
$db,
$table,
array $transformation,
array &$editedValues,
$file,
$columnName,
array $extraData,
$type
) {
$includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
if (is_file(ROOT_PATH . $includeFile)) {
// $cfg['SaveCellsAtOnce'] = true; JS code sends an array
$whereClause = is_array($_POST['where_clause']) ? $_POST['where_clause'][0] : $_POST['where_clause'];
$urlParams = [
'db' => $db,
'table' => $table,
'where_clause_sign' => Core::signSqlQuery($whereClause),
'where_clause' => $whereClause,
'transform_key' => $columnName,
];
$transformOptions = $this->transformations->getOptions($transformation[$type . '_options'] ?? '');
$transformOptions['wrapper_link'] = Url::getCommon($urlParams);
$transformOptions['wrapper_params'] = $urlParams;
$className = $this->transformations->getClassName($includeFile);
if (class_exists($className)) {
/** @var TransformationsPlugin $transformationPlugin */
$transformationPlugin = new $className();
foreach ($editedValues as $cellIndex => $currCellEditedValues) {
if (! isset($currCellEditedValues[$columnName])) {
continue;
}
$extraData['transformations'][$cellIndex] = $transformationPlugin->applyTransformation(
$currCellEditedValues[$columnName],
$transformOptions
);
$editedValues[$cellIndex][$columnName] = $extraData['transformations'][$cellIndex];
}
}
}
return $extraData;
}
/**
* Get current value in multi edit mode
*
* @param array $multiEditFuncs multiple edit functions array
* @param array $multiEditSalt multiple edit array with encryption salt
* @param array $gisFromTextFunctions array that contains gis from text functions
* @param string $currentValue current value in the column
* @param array $gisFromWkbFunctions initially $val is $multi_edit_columns[$key]
* @param array $funcOptionalParam array('RAND','UNIX_TIMESTAMP')
* @param array $funcNoParam array of set of string
* @param string $key an md5 of the column name
*/
public function getCurrentValueAsAnArrayForMultipleEdit(
$multiEditFuncs,
$multiEditSalt,
$gisFromTextFunctions,
$currentValue,
$gisFromWkbFunctions,
$funcOptionalParam,
$funcNoParam,
$key
): string {
if ($multiEditFuncs[$key] === 'PHP_PASSWORD_HASH') {
/**
* @see https://github.com/vimeo/psalm/issues/3350
*
* @psalm-suppress InvalidArgument
*/
$hash = password_hash($currentValue, PASSWORD_DEFAULT);
return "'" . $this->dbi->escapeString($hash) . "'";
}
if ($multiEditFuncs[$key] === 'UUID') {
/* This way user will know what UUID new row has */
$uuid = (string) $this->dbi->fetchValue('SELECT UUID()');
return "'" . $this->dbi->escapeString($uuid) . "'";
}
if (
in_array($multiEditFuncs[$key], $gisFromTextFunctions)
|| in_array($multiEditFuncs[$key], $gisFromWkbFunctions)
) {
return $multiEditFuncs[$key] . "('" . $this->dbi->escapeString($currentValue) . "')";
}
if (
! in_array($multiEditFuncs[$key], $funcNoParam)
|| ($currentValue != "''"
&& in_array($multiEditFuncs[$key], $funcOptionalParam))
) {
if (
(isset($multiEditSalt[$key])
&& ($multiEditFuncs[$key] === 'AES_ENCRYPT'
|| $multiEditFuncs[$key] === 'AES_DECRYPT'))
|| (! empty($multiEditSalt[$key])
&& ($multiEditFuncs[$key] === 'DES_ENCRYPT'
|| $multiEditFuncs[$key] === 'DES_DECRYPT'
|| $multiEditFuncs[$key] === 'ENCRYPT'))
) {
return $multiEditFuncs[$key] . "('" . $this->dbi->escapeString($currentValue) . "','"
. $this->dbi->escapeString($multiEditSalt[$key]) . "')";
}
return $multiEditFuncs[$key] . "('" . $this->dbi->escapeString($currentValue) . "')";
}
return $multiEditFuncs[$key] . '()';
}
/**
* Get query values array and query fields array for insert and update in multi edit
*
* @param array $multiEditColumnsName multiple edit columns name array
* @param array $multiEditColumnsNull multiple edit columns null array
* @param string $currentValue current value in the column in loop
* @param array $multiEditColumnsPrev multiple edit previous columns array
* @param array $multiEditFuncs multiple edit functions array
* @param bool $isInsert boolean value whether insert or not
* @param array $queryValues SET part of the sql query
* @param array $queryFields array of query fields
* @param string $currentValueAsAnArray current value in the column
* as an array
* @param array $valueSets array of valu sets
* @param string $key an md5 of the column name
* @param array $multiEditColumnsNullPrev array of multiple edit columns
* null previous
*
* @return array[] ($query_values, $query_fields)
*/
public function getQueryValuesForInsertAndUpdateInMultipleEdit(
$multiEditColumnsName,
$multiEditColumnsNull,
$currentValue,
$multiEditColumnsPrev,
$multiEditFuncs,
$isInsert,
$queryValues,
$queryFields,
$currentValueAsAnArray,
$valueSets,
$key,
$multiEditColumnsNullPrev
) {
// i n s e r t
if ($isInsert) {
// no need to add column into the valuelist
if (strlen($currentValueAsAnArray) > 0) {
$queryValues[] = $currentValueAsAnArray;
// first inserted row so prepare the list of fields
if (empty($valueSets)) {
$queryFields[] = Util::backquote($multiEditColumnsName[$key]);
}
}
} elseif (! empty($multiEditColumnsNullPrev[$key]) && ! isset($multiEditColumnsNull[$key])) {
// u p d a t e
// field had the null checkbox before the update
// field no longer has the null checkbox
$queryValues[] = Util::backquote($multiEditColumnsName[$key])
. ' = ' . $currentValueAsAnArray;
} elseif (
! (empty($multiEditFuncs[$key])
&& empty($multiEditColumnsNull[$key])
&& isset($multiEditColumnsPrev[$key])
&& $currentValue === $multiEditColumnsPrev[$key])
&& $currentValueAsAnArray !== ''
) {
// 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($multiEditColumnsNullPrev[$key]) || empty($multiEditColumnsNull[$key])) {
$queryValues[] = Util::backquote($multiEditColumnsName[$key])
. ' = ' . $currentValueAsAnArray;
}
}
return [
$queryValues,
$queryFields,
];
}
/**
* Get the current column value in the form for different data types
*
* @param string|false $possiblyUploadedVal uploaded file content
* @param string $key an md5 of the column name
* @param array|null $multiEditColumnsType array of multi edit column types
* @param string $currentValue current column value in the form
* @param array|null $multiEditAutoIncrement multi edit auto increment
* @param int $rownumber index of where clause array
* @param array $multiEditColumnsName multi edit column names array
* @param array $multiEditColumnsNull multi edit columns null array
* @param array $multiEditColumnsNullPrev multi edit columns previous null
* @param bool $isInsert whether insert or not
* @param bool $usingKey whether editing or new row
* @param string $whereClause where clause
* @param string $table table name
* @param array $multiEditFuncs multiple edit functions array
*
* @return string current column value in the form
*/
public function getCurrentValueForDifferentTypes(
$possiblyUploadedVal,
$key,
?array $multiEditColumnsType,
$currentValue,
?array $multiEditAutoIncrement,
$rownumber,
$multiEditColumnsName,
$multiEditColumnsNull,
$multiEditColumnsNullPrev,
$isInsert,
$usingKey,
$whereClause,
$table,
$multiEditFuncs
): string {
if ($possiblyUploadedVal !== false) {
return $possiblyUploadedVal;
}
// c o l u m n v a l u e i n t h e f o r m
$type = $multiEditColumnsType[$key] ?? '';
if ($type !== 'protected' && $type !== 'set' && strlen($currentValue) === 0) {
// best way to avoid problems in strict mode
// (works also in non-strict mode)
$currentValue = "''";
if (isset($multiEditAutoIncrement, $multiEditAutoIncrement[$key])) {
$currentValue = 'NULL';
}
} elseif ($type === 'set') {
$currentValue = "''";
if (! empty($_POST['fields']['multi_edit'][$rownumber][$key])) {
$currentValue = implode(',', $_POST['fields']['multi_edit'][$rownumber][$key]);
$currentValue = "'"
. $this->dbi->escapeString($currentValue) . "'";
}
} elseif ($type === 'protected') {
// Fetch the current values of a row to use in case we have a protected field
if (
$isInsert
&& $usingKey
&& is_array($multiEditColumnsType) && $whereClause
) {
$protectedRow = $this->dbi->fetchSingleRow(
'SELECT * FROM ' . Util::backquote($table)
. ' WHERE ' . $whereClause . ';'
);
}
// 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.
$currentValue = '';
if (! empty($protectedRow[$multiEditColumnsName[$key]])) {
$currentValue = '0x'
. bin2hex($protectedRow[$multiEditColumnsName[$key]]);
}
} elseif ($type === 'hex') {
if (substr($currentValue, 0, 2) != '0x') {
$currentValue = '0x' . $currentValue;
}
} elseif ($type === 'bit') {
$currentValue = (string) preg_replace('/[^01]/', '0', $currentValue);
$currentValue = "b'" . $this->dbi->escapeString($currentValue) . "'";
} elseif (
! ($type === 'datetime' || $type === 'timestamp' || $type === 'date')
|| ($currentValue !== 'CURRENT_TIMESTAMP'
&& $currentValue !== 'current_timestamp()')
) {
$currentValue = "'" . $this->dbi->escapeString($currentValue)
. "'";
}
// 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($multiEditColumnsNull[$key]) && ($currentValue == "''" || $currentValue == '')) {
$currentValue = 'NULL';
}
// The Null checkbox was unchecked for this field
if (
empty($currentValue)
&& ! empty($multiEditColumnsNullPrev[$key])
&& ! isset($multiEditColumnsNull[$key])
) {
$currentValue = "''";
}
// For uuid type, generate uuid value
// if empty value but not set null or value is uuid() function
if (
$type === 'uuid'
&& ! isset($multiEditColumnsNull[$key])
&& ($currentValue == "''"
|| $currentValue == ''
|| $currentValue === "'uuid()'")
) {
$currentValue = 'uuid()';
}
return $currentValue;
}
/**
* 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 $columnName Column name
* @param array $extraData Extra data for ajax response
*/
public function verifyWhetherValueCanBeTruncatedAndAppendExtraData(
$db,
$table,
$columnName,
array &$extraData
): void {
$extraData['isNeedToRecheck'] = false;
$sqlForRealValue = 'SELECT ' . Util::backquote($table) . '.'
. Util::backquote($columnName)
. ' FROM ' . Util::backquote($db) . '.'
. Util::backquote($table)
. ' WHERE ' . $_POST['where_clause'][0];
$result = $this->dbi->tryQuery($sqlForRealValue);
if (! $result) {
return;
}
$fieldsMeta = $this->dbi->getFieldsMeta($result);
$meta = $fieldsMeta[0];
$newValue = $result->fetchValue();
if ($newValue === false) {
return;
}
if ($meta->isTimeType()) {
$newValue = Util::addMicroseconds($newValue);
} elseif ($meta->isBinary()) {
$newValue = '0x' . bin2hex($newValue);
}
$extraData['isNeedToRecheck'] = true;
$extraData['truncatableFieldValue'] = $newValue;
}
/**
* Function to get the columns of a table
*
* @param string $db current db
* @param string $table current table
*
* @return array[]
*/
public function getTableColumns($db, $table)
{
$this->dbi->selectDb($db);
return array_values($this->dbi->getColumns($db, $table, true));
}
/**
* Function to determine Insert/Edit rows
*
* @param string|null $whereClause where clause
* @param string $db current database
* @param string $table current table
*
* @return array
*/
public function determineInsertOrEdit($whereClause, $db, $table): array
{
if (isset($_POST['where_clause'])) {
$whereClause = $_POST['where_clause'];
}
if (isset($_SESSION['edit_next'])) {
$whereClause = $_SESSION['edit_next'];
unset($_SESSION['edit_next']);
$afterInsert = 'edit_next';
}
if (isset($_POST['ShowFunctionFields'])) {
$GLOBALS['cfg']['ShowFunctionFields'] = $_POST['ShowFunctionFields'];
}
if (isset($_POST['ShowFieldTypesInDataEditView'])) {
$GLOBALS['cfg']['ShowFieldTypesInDataEditView'] = $_POST['ShowFieldTypesInDataEditView'];
}
if (isset($_POST['after_insert'])) {
$afterInsert = $_POST['after_insert'];
}
if (isset($whereClause)) {
// we are editing
$insertMode = false;
$whereClauseArray = $this->getWhereClauseArray($whereClause);
[$whereClauses, $result, $rows, $foundUniqueKey] = $this->analyzeWhereClauses(
$whereClauseArray,
$table,
$db
);
} else {
// we are inserting
$insertMode = true;
$whereClause = null;
[$result, $rows] = $this->loadFirstRow($table, $db);
$whereClauses = null;
$whereClauseArray = [];
$foundUniqueKey = false;
}
// Copying a row - fetched data will be inserted as a new row,
// therefore the where clause is needless.
if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
$whereClause = $whereClauses = null;
}
return [
$insertMode,
$whereClause,
$whereClauseArray,
$whereClauses,
$result,
$rows,
$foundUniqueKey,
$afterInsert ?? null,
];
}
/**
* Function to get comments for the table columns
*
* @param string $db current database
* @param string $table current table
*
* @return array comments for columns
*/
public function getCommentsMap($db, $table): array
{
if ($GLOBALS['cfg']['ShowPropertyComments']) {
return $this->relation->getComments($db, $table);
}
return [];
}
/**
* Function to get html for the gis editor div
*/
public function getHtmlForGisEditor(): string
{
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 $rowId row id
* @param bool $checked ignore option is checked or not
*/
public function getHtmlForIgnoreOption($rowId, $checked = true): string
{
return '<input type="checkbox"'
. ($checked ? ' checked="checked"' : '')
. ' name="insert_ignore_' . $rowId . '"'
. ' id="insert_ignore_' . $rowId . '">'
. '<label for="insert_ignore_' . $rowId . '">'
. __('Ignore')
. '</label><br>' . "\n";
}
/**
* Function to get html for the insert edit form header
*
* @param bool $hasBlobField whether has blob field
* @param bool $isUpload whether is upload
*/
public function getHtmlForInsertEditFormHeader($hasBlobField, $isUpload): string
{
$template = new Template();
return $template->render('table/insert/get_html_for_insert_edit_form_header', [
'has_blob_field' => $hasBlobField,
'is_upload' => $isUpload,
]);
}
/**
* Function to get html for each insert/edit column
*
* @param array $column column
* @param int $columnNumber column index in table_columns
* @param array $commentsMap comments map
* @param bool $timestampSeen whether timestamp seen
* @param ResultInterface $currentResult current result
* @param string $chgEvtHandler javascript change event handler
* @param string $jsvkey javascript validation key
* @param string $vkey validation key
* @param bool $insertMode whether insert mode
* @param array $currentRow current row
* @param int $oRows row offset
* @param int $tabindex tab index
* @param int $columnsCnt columns count
* @param bool $isUpload whether upload
* @param array $foreigners foreigners
* @param int $tabindexForValue tab index offset for value
* @param string $table table
* @param string $db database
* @param int $rowId row id
* @param int $biggestMaxFileSize biggest max file size
* @param string $defaultCharEditing default char editing mode which is stored in the config.inc.php script
* @param string $textDir text direction
* @param array $repopulate the data to be repopulated
* @param array $columnMime the mime information of column
* @param string $whereClause the where clause
*
* @return string
*/
private function getHtmlForInsertEditFormColumn(
array $column,
int $columnNumber,
array $commentsMap,
$timestampSeen,
ResultInterface $currentResult,
$chgEvtHandler,
$jsvkey,
$vkey,
$insertMode,
array $currentRow,
$oRows,
&$tabindex,
$columnsCnt,
$isUpload,
array $foreigners,
$tabindexForValue,
$table,
$db,
$rowId,
$biggestMaxFileSize,
$defaultCharEditing,
$textDir,
array $repopulate,
array $columnMime,
$whereClause
) {
$readOnly = false;
if (! isset($column['processed'])) {
$column = $this->analyzeTableColumnsArray($column, $commentsMap, $timestampSeen);
}
$asIs = false;
/** @var string $fieldHashMd5 */
$fieldHashMd5 = $column['Field_md5'];
if ($repopulate && array_key_exists($fieldHashMd5, $currentRow)) {
$currentRow[$column['Field']] = $repopulate[$fieldHashMd5];
$asIs = true;
}
$extractedColumnspec = Util::extractColumnSpec($column['Type']);
if ($column['len'] === -1) {
$column['len'] = $this->dbi->getFieldsMeta($currentResult)[$columnNumber]->length;
// length is unknown for geometry fields,
// make enough space to edit very simple WKTs
if ($column['len'] === -1) {
$column['len'] = 30;
}
}
//Call validation when the form submitted...
$onChangeClause = $chgEvtHandler
. "=\"return verificationsAfterFieldChange('"
. Sanitize::escapeJsString($fieldHashMd5) . "', '"
. Sanitize::escapeJsString($jsvkey) . "','" . $column['pma_type'] . "')\"";
// Use an MD5 as an array index to avoid having special characters
// in the name attribute (see bug #1746964 )
$columnNameAppendix = $vkey . '[' . $fieldHashMd5 . ']';
if ($column['Type'] === 'datetime' && $column['Null'] !== 'YES' && ! isset($column['Default']) && $insertMode) {
$column['Default'] = date('Y-m-d H:i:s', time());
}
// Get a list of GIS data types.
$gisDataTypes = Gis::getDataTypes();
// Prepares the field value
if ($currentRow) {
// (we are editing)
[
$realNullValue,
$specialCharsEncoded,
$specialChars,
$data,
$backupField,
] = $this->getSpecialCharsAndBackupFieldForExistingRow(
$currentRow,
$column,
$extractedColumnspec,
$gisDataTypes,
$columnNameAppendix,
$asIs
);
} else {
// (we are inserting)
// display default values
$tmp = $column;
if (isset($repopulate[$fieldHashMd5])) {
$tmp['Default'] = $repopulate[$fieldHashMd5];
}
[
$realNullValue,
$data,
$specialChars,
$backupField,
$specialCharsEncoded,
] = $this->getSpecialCharsAndBackupFieldForInsertingMode($tmp);
unset($tmp);
}
$idindex = ($oRows * $columnsCnt) + $columnNumber + 1;
$tabindex = $idindex;
// The function column
// -------------------
$foreignData = $this->relation->getForeignData($foreigners, $column['Field'], false, '', '');
$isColumnBinary = $this->isColumnBinary($column, $isUpload);
$functionOptions = '';
if ($GLOBALS['cfg']['ShowFunctionFields']) {
$functionOptions = Generator::getFunctionsForField($column, $insertMode, $foreignData);
}
// nullify code is needed by the js nullify() function to be able to generate calls to nullify() in jQuery
$nullifyCode = $this->getNullifyCodeForNullColumn($column, $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"
$noDecimals = 0;
$type = current(explode('(', $column['pma_type']));
if (preg_match('/\(([^()]+)\)/', $column['pma_type'], $match)) {
$match[0] = trim($match[0], '()');
$noDecimals = $match[0];
}
// Check input transformation of column
$transformedHtml = '';
if (! empty($columnMime['input_transformation'])) {
$file = $columnMime['input_transformation'];
$includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
if (is_file(ROOT_PATH . $includeFile)) {
$className = $this->transformations->getClassName($includeFile);
if (class_exists($className)) {
$transformationPlugin = new $className();
$transformationOptions = $this->transformations->getOptions(
$columnMime['input_transformation_options']
);
$urlParams = [
'db' => $db,
'table' => $table,
'transform_key' => $column['Field'],
'where_clause_sign' => Core::signSqlQuery($whereClause),
'where_clause' => $whereClause,
];
$transformationOptions['wrapper_link'] = Url::getCommon($urlParams);
$transformationOptions['wrapper_params'] = $urlParams;
$currentValue = '';
if (isset($currentRow[$column['Field']])) {
$currentValue = $currentRow[$column['Field']];
}
if (method_exists($transformationPlugin, 'getInputHtml')) {
$transformedHtml = $transformationPlugin->getInputHtml(
$column,
$rowId,
$columnNameAppendix,
$transformationOptions,
$currentValue,
$textDir,
$tabindex,
$tabindexForValue,
$idindex
);
}
if (method_exists($transformationPlugin, 'getScripts')) {
$GLOBALS['plugin_scripts'] = array_merge(
$GLOBALS['plugin_scripts'],
$transformationPlugin->getScripts()
);
}
}
}
}
$columnValue = '';
$foreignDropdown = '';
$dataType = '';
$textAreaRows = $GLOBALS['cfg']['TextareaRows'];
$textareaCols = $GLOBALS['cfg']['TextareaCols'];
$maxlength = '';
$enumSelectedValue = '';
$columnSetValues = [];
$setSelectSize = 0;
$isColumnProtectedBlob = false;
$blobValue = '';
$blobValueUnit = '';
$maxUploadSize = 0;
$selectOptionForUpload = '';
$inputFieldHtml = '';
if (empty($transformedHtml)) {
if (is_array($foreignData['disp_row'])) {
$foreignDropdown = $this->relation->foreignDropdown(
$foreignData['disp_row'],
$foreignData['foreign_field'],
$foreignData['foreign_display'],
$data,
$GLOBALS['cfg']['ForeignKeyMaxLimit']
);
}
$dataType = $this->dbi->types->getTypeClass($column['True_Type']);
if ($column['is_char']) {
$textAreaRows = max($GLOBALS['cfg']['CharTextareaRows'], 7);
$textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
$maxlength = $extractedColumnspec['spec_in_brackets'];
} elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
$textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
$textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
}
if ($column['pma_type'] === 'enum') {
if (! isset($column['values'])) {
$column['values'] = $this->getColumnEnumValues($extractedColumnspec['enum_set_values']);
}
foreach ($column['values'] as $enumValue) {
if (
$data == $enumValue['plain'] || ($data == ''
&& (! isset($_POST['where_clause']) || $column['Null'] !== 'YES')
&& isset($column['Default']) && $enumValue['plain'] == $column['Default'])
) {
$enumSelectedValue = $enumValue['plain'];
break;
}
}
} elseif ($column['pma_type'] === 'set') {
[$columnSetValues, $setSelectSize] = $this->getColumnSetValueAndSelectSize(
$column,
$extractedColumnspec['enum_set_values']
);
} elseif ($column['is_binary'] || $column['is_blob']) {
$isColumnProtectedBlob = ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'])
|| ($GLOBALS['cfg']['ProtectBinary'] === 'all')
|| ($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && ! $column['is_blob']);
if ($isColumnProtectedBlob && isset($data)) {
$blobSize = Util::formatByteDown(mb_strlen(stripslashes($data)), 3, 1);
if ($blobSize !== null) {
[$blobValue, $blobValueUnit] = $blobSize;
}
}
if ($isUpload && $column['is_blob']) {
[$maxUploadSize] = $this->getMaxUploadSize($column['pma_type'], $biggestMaxFileSize);
}
if (! empty($GLOBALS['cfg']['UploadDir'])) {
$selectOptionForUpload = $this->getSelectOptionForUpload($vkey, $fieldHashMd5);
}
if (
! $isColumnProtectedBlob
&& ! ($column['is_blob'] || ($column['len'] > $GLOBALS['cfg']['LimitChars']))
) {
$inputFieldHtml = $this->getHtmlInput(
$column,
$columnNameAppendix,
$specialChars,
min(max($column['len'], 4), $GLOBALS['cfg']['LimitChars']),
$onChangeClause,
$tabindex,
$tabindexForValue,
$idindex,
'HEX',
$readOnly
);
}
} else {
$columnValue = $this->getValueColumnForOtherDatatypes(
$column,
$defaultCharEditing,
$backupField,
$columnNameAppendix,
$onChangeClause,
$tabindex,
$specialChars,
$tabindexForValue,
$idindex,
$textDir,
$specialCharsEncoded,
$data,
$extractedColumnspec,
$readOnly
);
}
}
return $this->template->render('table/insert/column_row', [
'db' => $db,
'table' => $table,
'column' => $column,
'row_id' => $rowId,
'show_field_types_in_data_edit_view' => $GLOBALS['cfg']['ShowFieldTypesInDataEditView'],
'show_function_fields' => $GLOBALS['cfg']['ShowFunctionFields'],
'is_column_binary' => $isColumnBinary,
'function_options' => $functionOptions,
'read_only' => $readOnly,
'nullify_code' => $nullifyCode,
'real_null_value' => $realNullValue,
'id_index' => $idindex,
'type' => $type,
'decimals' => $noDecimals,
'special_chars' => $specialChars,
'transformed_value' => $transformedHtml,
'value' => $columnValue,
'is_value_foreign_link' => $foreignData['foreign_link'] === true,
'backup_field' => $backupField,
'data' => $data,
'gis_data_types' => $gisDataTypes,
'foreign_dropdown' => $foreignDropdown,
'data_type' => $dataType,
'textarea_cols' => $textareaCols,
'textarea_rows' => $textAreaRows,
'text_dir' => $textDir,
'max_length' => $maxlength,
'longtext_double_textarea' => $GLOBALS['cfg']['LongtextDoubleTextarea'],
'enum_selected_value' => $enumSelectedValue,
'set_values' => $columnSetValues,
'set_select_size' => $setSelectSize,
'is_column_protected_blob' => $isColumnProtectedBlob,
'blob_value' => $blobValue,
'blob_value_unit' => $blobValueUnit,
'is_upload' => $isUpload,
'max_upload_size' => $maxUploadSize,
'select_option_for_upload' => $selectOptionForUpload,
'limit_chars' => $GLOBALS['cfg']['LimitChars'],
'input_field_html' => $inputFieldHtml,
]);
}
private function isColumnBinary(array $column, bool $isUpload): bool
{
global $cfg;
if (! $cfg['ShowFunctionFields']) {
return false;
}
return ($cfg['ProtectBinary'] === 'blob' && $column['is_blob'] && ! $isUpload)
|| ($cfg['ProtectBinary'] === 'all' && $column['is_binary'])
|| ($cfg['ProtectBinary'] === 'noblob' && $column['is_binary']);
}
/**
* Function to get html for each insert/edit row
*
* @param array $urlParams url parameters
* @param array[] $tableColumns table columns
* @param array $commentsMap comments map
* @param bool $timestampSeen whether timestamp seen
* @param ResultInterface $currentResult current result
* @param string $chgEvtHandler javascript change event handler
* @param string $jsvkey javascript validation key
* @param string $vkey validation key
* @param bool $insertMode whether insert mode
* @param array $currentRow current row
* @param int $oRows row offset
* @param int $tabindex tab index
* @param int $columnsCnt columns count
* @param bool $isUpload whether upload
* @param array $foreigners foreigners
* @param int $tabindexForValue tab index offset for value
* @param string $table table
* @param string $db database
* @param int $rowId row id
* @param int $biggestMaxFileSize biggest max file size
* @param string $textDir text direction
* @param array $repopulate the data to be repopulated
* @param array $whereClauseArray the array of where clauses
*
* @return string
*/
public function getHtmlForInsertEditRow(
array $urlParams,
array $tableColumns,
array $commentsMap,
$timestampSeen,
ResultInterface $currentResult,
$chgEvtHandler,
$jsvkey,
$vkey,
$insertMode,
array $currentRow,
&$oRows,
&$tabindex,
$columnsCnt,
$isUpload,
array $foreigners,
$tabindexForValue,
$table,
$db,
$rowId,
$biggestMaxFileSize,
$textDir,
array $repopulate,
array $whereClauseArray
) {
$htmlOutput = $this->getHeadAndFootOfInsertRowTable($urlParams)
. '<tbody>';
//store the default value for CharEditing
$defaultCharEditing = $GLOBALS['cfg']['CharEditing'];
$mimeMap = $this->transformations->getMime($db, $table);
$whereClause = '';
if (isset($whereClauseArray[$rowId])) {
$whereClause = $whereClauseArray[$rowId];
}
for ($columnNumber = 0; $columnNumber < $columnsCnt; $columnNumber++) {
$tableColumn = $tableColumns[$columnNumber];
$columnMime = [];
if (isset($mimeMap[$tableColumn['Field']])) {
$columnMime = $mimeMap[$tableColumn['Field']];
}
$virtual = [
'VIRTUAL',
'PERSISTENT',
'VIRTUAL GENERATED',
'STORED GENERATED',
];
if (in_array($tableColumn['Extra'], $virtual)) {
continue;
}
$htmlOutput .= $this->getHtmlForInsertEditFormColumn(
$tableColumn,
$columnNumber,
$commentsMap,
$timestampSeen,
$currentResult,
$chgEvtHandler,
$jsvkey,
$vkey,
$insertMode,
$currentRow,
$oRows,
$tabindex,
$columnsCnt,
$isUpload,
$foreigners,
$tabindexForValue,
$table,
$db,
$rowId,
$biggestMaxFileSize,
$defaultCharEditing,
$textDir,
$repopulate,
$columnMime,
$whereClause
);
}
$oRows++;
return $htmlOutput . ' </tbody>'
. '</table></div><br>'
. '<div class="clearfloat"></div>';
}
}
|