1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
|
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Display;
use PhpMyAdmin\Config\SpecialSchemaLinks;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Index;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\Transformations\Output\Text_Octetstream_Sql;
use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Json;
use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Sql;
use PhpMyAdmin\Plugins\Transformations\Text_Plain_Link;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Sql;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\SqlParser\Utils\Query;
use PhpMyAdmin\Table;
use PhpMyAdmin\Template;
use PhpMyAdmin\Theme;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\Gis;
use function __;
use function _pgettext;
use function array_filter;
use function array_keys;
use function array_merge;
use function array_shift;
use function bin2hex;
use function ceil;
use function class_exists;
use function count;
use function explode;
use function file_exists;
use function floor;
use function htmlspecialchars;
use function implode;
use function in_array;
use function intval;
use function is_array;
use function is_numeric;
use function json_encode;
use function max;
use function mb_check_encoding;
use function mb_strlen;
use function mb_strpos;
use function mb_strtolower;
use function mb_strtoupper;
use function mb_substr;
use function md5;
use function mt_getrandmax;
use function pack;
use function preg_match;
use function preg_replace;
use function random_int;
use function str_contains;
use function str_ends_with;
use function str_replace;
use function strcasecmp;
use function strip_tags;
use function stripos;
use function strlen;
use function strpos;
use function strtoupper;
use function substr;
use function trim;
/**
* Handle all the functionalities related to displaying results
* of sql queries, stored procedure, browsing sql processes or
* displaying binary log.
*/
class Results
{
// Define constants
public const NO_EDIT_OR_DELETE = 'nn';
public const UPDATE_ROW = 'ur';
public const DELETE_ROW = 'dr';
public const KILL_PROCESS = 'kp';
public const POSITION_LEFT = 'left';
public const POSITION_RIGHT = 'right';
public const POSITION_BOTH = 'both';
public const POSITION_NONE = 'none';
public const DISPLAY_FULL_TEXT = 'F';
public const DISPLAY_PARTIAL_TEXT = 'P';
public const HEADER_FLIP_TYPE_AUTO = 'auto';
public const HEADER_FLIP_TYPE_CSS = 'css';
public const HEADER_FLIP_TYPE_FAKE = 'fake';
public const RELATIONAL_KEY = 'K';
public const RELATIONAL_DISPLAY_COLUMN = 'D';
public const GEOMETRY_DISP_GEOM = 'GEOM';
public const GEOMETRY_DISP_WKT = 'WKT';
public const GEOMETRY_DISP_WKB = 'WKB';
public const SMART_SORT_ORDER = 'SMART';
public const ASCENDING_SORT_DIR = 'ASC';
public const DESCENDING_SORT_DIR = 'DESC';
public const TABLE_TYPE_INNO_DB = 'InnoDB';
public const ALL_ROWS = 'all';
public const QUERY_TYPE_SELECT = 'SELECT';
public const ROUTINE_PROCEDURE = 'procedure';
public const ROUTINE_FUNCTION = 'function';
public const ACTION_LINK_CONTENT_ICONS = 'icons';
public const ACTION_LINK_CONTENT_TEXT = 'text';
/**
* @psalm-var array{
* server: int,
* db: string,
* table: string,
* goto: string,
* sql_query: string,
* unlim_num_rows: int|numeric-string|false,
* fields_meta: FieldMetadata[],
* is_count: bool|null,
* is_export: bool|null,
* is_func: bool|null,
* is_analyse: bool|null,
* num_rows: int|numeric-string,
* fields_cnt: int,
* querytime: float|null,
* text_dir: string|null,
* is_maint: bool|null,
* is_explain: bool|null,
* is_show: bool|null,
* is_browse_distinct: bool|null,
* showtable: array<string, mixed>|null,
* printview: string|null,
* highlight_columns: array|null,
* display_params: array|null,
* mime_map: array|null,
* editable: bool|null,
* unique_id: int,
* whereClauseMap: array,
* }
*/
public $properties = [
/* server id */
'server' => 0,
/* Database name */
'db' => '',
/* Table name */
'table' => '',
/* the URL to go back in case of errors */
'goto' => '',
/* the SQL query */
'sql_query' => '',
/* the total number of rows returned by the SQL query without any appended "LIMIT" clause programmatically */
'unlim_num_rows' => 0,
/* meta information about fields */
'fields_meta' => [],
'is_count' => null,
'is_export' => null,
'is_func' => null,
'is_analyse' => null,
/* the total number of rows returned by the SQL query */
'num_rows' => 0,
/* the total number of fields returned by the SQL query */
'fields_cnt' => 0,
/* time taken for execute the SQL query */
'querytime' => null,
'text_dir' => null,
'is_maint' => null,
'is_explain' => null,
'is_show' => null,
'is_browse_distinct' => null,
/* table definitions */
'showtable' => null,
'printview' => null,
/* column names to highlight */
'highlight_columns' => null,
/* display information */
'display_params' => null,
/* mime types information of fields */
'mime_map' => null,
'editable' => null,
/* random unique ID to distinguish result set */
'unique_id' => 0,
/* where clauses for each row, each table in the row */
'whereClauseMap' => [],
];
/**
* This variable contains the column transformation information
* for some of the system databases.
* One element of this array represent all relevant columns in all tables in
* one specific database
*
* @var array<string, array<string, array<string, string[]>>>
* @psalm-var array<string, array<string, array<string, array{string, class-string, string}>>> $transformationInfo
*/
public $transformationInfo;
/** @var DatabaseInterface */
private $dbi;
/** @var Relation */
private $relation;
/** @var Transformations */
private $transformations;
/** @var Template */
public $template;
/**
* @param string $db the database name
* @param string $table the table name
* @param int $server the server id
* @param string $goto the URL to go back in case of errors
* @param string $sqlQuery the SQL query
*/
public function __construct(DatabaseInterface $dbi, $db, $table, $server, $goto, $sqlQuery)
{
$this->dbi = $dbi;
$this->relation = new Relation($this->dbi);
$this->transformations = new Transformations();
$this->template = new Template();
$this->setDefaultTransformations();
$this->properties['db'] = $db;
$this->properties['table'] = $table;
$this->properties['server'] = $server;
$this->properties['goto'] = $goto;
$this->properties['sql_query'] = $sqlQuery;
$this->properties['unique_id'] = random_int(0, mt_getrandmax());
}
/**
* Sets default transformations for some columns
*/
private function setDefaultTransformations(): void
{
$jsonHighlightingData = [
'libraries/classes/Plugins/Transformations/Output/Text_Plain_Json.php',
Text_Plain_Json::class,
'Text_Plain',
];
$sqlHighlightingData = [
'libraries/classes/Plugins/Transformations/Output/Text_Plain_Sql.php',
Text_Plain_Sql::class,
'Text_Plain',
];
$blobSqlHighlightingData = [
'libraries/classes/Plugins/Transformations/Output/Text_Octetstream_Sql.php',
Text_Octetstream_Sql::class,
'Text_Octetstream',
];
$linkData = [
'libraries/classes/Plugins/Transformations/Text_Plain_Link.php',
Text_Plain_Link::class,
'Text_Plain',
];
$this->transformationInfo = [
'information_schema' => [
'events' => ['event_definition' => $sqlHighlightingData],
'processlist' => ['info' => $sqlHighlightingData],
'routines' => ['routine_definition' => $sqlHighlightingData],
'triggers' => ['action_statement' => $sqlHighlightingData],
'views' => ['view_definition' => $sqlHighlightingData],
],
'mysql' => [
'event' => [
'body' => $blobSqlHighlightingData,
'body_utf8' => $blobSqlHighlightingData,
],
'general_log' => ['argument' => $sqlHighlightingData],
'help_category' => ['url' => $linkData],
'help_topic' => [
'example' => $sqlHighlightingData,
'url' => $linkData,
],
'proc' => [
'param_list' => $blobSqlHighlightingData,
'returns' => $blobSqlHighlightingData,
'body' => $blobSqlHighlightingData,
'body_utf8' => $blobSqlHighlightingData,
],
'slow_log' => ['sql_text' => $sqlHighlightingData],
],
];
$relationParameters = $this->relation->getRelationParameters();
if ($relationParameters->db === null) {
return;
}
$relDb = [];
if ($relationParameters->sqlHistoryFeature !== null) {
$relDb[$relationParameters->sqlHistoryFeature->history->getName()] = ['sqlquery' => $sqlHighlightingData];
}
if ($relationParameters->bookmarkFeature !== null) {
$relDb[$relationParameters->bookmarkFeature->bookmark->getName()] = ['query' => $sqlHighlightingData];
}
if ($relationParameters->trackingFeature !== null) {
$relDb[$relationParameters->trackingFeature->tracking->getName()] = [
'schema_sql' => $sqlHighlightingData,
'data_sql' => $sqlHighlightingData,
];
}
if ($relationParameters->favoriteTablesFeature !== null) {
$table = $relationParameters->favoriteTablesFeature->favorite->getName();
$relDb[$table] = ['tables' => $jsonHighlightingData];
}
if ($relationParameters->recentlyUsedTablesFeature !== null) {
$table = $relationParameters->recentlyUsedTablesFeature->recent->getName();
$relDb[$table] = ['tables' => $jsonHighlightingData];
}
if ($relationParameters->savedQueryByExampleSearchesFeature !== null) {
$table = $relationParameters->savedQueryByExampleSearchesFeature->savedSearches->getName();
$relDb[$table] = ['search_data' => $jsonHighlightingData];
}
if ($relationParameters->databaseDesignerSettingsFeature !== null) {
$table = $relationParameters->databaseDesignerSettingsFeature->designerSettings->getName();
$relDb[$table] = ['settings_data' => $jsonHighlightingData];
}
if ($relationParameters->uiPreferencesFeature !== null) {
$table = $relationParameters->uiPreferencesFeature->tableUiPrefs->getName();
$relDb[$table] = ['prefs' => $jsonHighlightingData];
}
if ($relationParameters->userPreferencesFeature !== null) {
$table = $relationParameters->userPreferencesFeature->userConfig->getName();
$relDb[$table] = ['config_data' => $jsonHighlightingData];
}
if ($relationParameters->exportTemplatesFeature !== null) {
$table = $relationParameters->exportTemplatesFeature->exportTemplates->getName();
$relDb[$table] = ['template_data' => $jsonHighlightingData];
}
$this->transformationInfo[$relationParameters->db->getName()] = $relDb;
}
/**
* Set properties which were not initialized at the constructor
*
* @param int|string $unlimNumRows the total number of rows returned by the SQL query without
* any appended "LIMIT" clause programmatically
* @param FieldMetadata[] $fieldsMeta meta information about fields
* @param bool $isCount statement is SELECT COUNT
* @param bool $isExport statement contains INTO OUTFILE
* @param bool $isFunction statement contains a function like SUM()
* @param bool $isAnalyse statement contains PROCEDURE ANALYSE
* @param int|string $numRows total no. of rows returned by SQL query
* @param int $fieldsCount total no.of fields returned by SQL query
* @param double $queryTime time taken for execute the SQL query
* @param string $textDirection text direction
* @param bool $isMaintenance statement contains a maintenance command
* @param bool $isExplain statement contains EXPLAIN
* @param bool $isShow statement contains SHOW
* @param array<string, mixed>|null $showTable table definitions
* @param string|null $printView print view was requested
* @param bool $editable whether the results set is editable
* @param bool $isBrowseDistinct whether browsing distinct values
* @psalm-param int|numeric-string $unlimNumRows
* @psalm-param int|numeric-string $numRows
*/
public function setProperties(
$unlimNumRows,
array $fieldsMeta,
$isCount,
$isExport,
$isFunction,
$isAnalyse,
$numRows,
$fieldsCount,
$queryTime,
$textDirection,
$isMaintenance,
$isExplain,
$isShow,
?array $showTable,
$printView,
$editable,
$isBrowseDistinct
): void {
$this->properties['unlim_num_rows'] = $unlimNumRows;
$this->properties['fields_meta'] = $fieldsMeta;
$this->properties['is_count'] = $isCount;
$this->properties['is_export'] = $isExport;
$this->properties['is_func'] = $isFunction;
$this->properties['is_analyse'] = $isAnalyse;
$this->properties['num_rows'] = $numRows;
$this->properties['fields_cnt'] = $fieldsCount;
$this->properties['querytime'] = $queryTime;
$this->properties['text_dir'] = $textDirection;
$this->properties['is_maint'] = $isMaintenance;
$this->properties['is_explain'] = $isExplain;
$this->properties['is_show'] = $isShow;
$this->properties['showtable'] = $showTable;
$this->properties['printview'] = $printView;
$this->properties['editable'] = $editable;
$this->properties['is_browse_distinct'] = $isBrowseDistinct;
}
/**
* Defines the parts to display for a print view
*
* @param array $displayParts the parts to display
*
* @return array the modified display parts
*/
private function setDisplayPartsForPrintView(array $displayParts)
{
// set all elements to false!
$displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
$displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
$displayParts['sort_lnk'] = '0';
$displayParts['nav_bar'] = '0';
$displayParts['bkm_form'] = '0';
$displayParts['text_btn'] = '0';
$displayParts['pview_lnk'] = '0';
return $displayParts;
}
/**
* Defines the parts to display for a SHOW statement
*
* @param array $displayParts the parts to display
*
* @return array the modified display parts
*/
private function setDisplayPartsForShow(array $displayParts)
{
preg_match(
'@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
. 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
. ')@i',
$this->properties['sql_query'],
$which
);
$bIsProcessList = isset($which[1]);
if ($bIsProcessList) {
$str = ' ' . strtoupper($which[1]);
$bIsProcessList = strpos($str, 'PROCESSLIST') > 0;
}
// no edit link
$displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
if ($bIsProcessList) {
// "kill process" type edit link
$displayParts['del_lnk'] = self::KILL_PROCESS;
} else {
// Default case -> no links
// no delete link
$displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
}
// Other settings
$displayParts['sort_lnk'] = '0';
$displayParts['nav_bar'] = '0';
$displayParts['bkm_form'] = '1';
$displayParts['text_btn'] = '1';
$displayParts['pview_lnk'] = '1';
return $displayParts;
}
/**
* Defines the parts to display for statements not related to data
*
* @param array $displayParts the parts to display
*
* @return array the modified display parts
*/
private function setDisplayPartsForNonData(array $displayParts)
{
// Statement is a "SELECT COUNT", a
// "CHECK/ANALYZE/REPAIR/OPTIMIZE/CHECKSUM", an "EXPLAIN" one or
// contains a "PROC ANALYSE" part
$displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
$displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
$displayParts['sort_lnk'] = '0';
$displayParts['nav_bar'] = '0';
$displayParts['bkm_form'] = '1';
if ($this->properties['is_maint']) {
$displayParts['text_btn'] = '1';
} else {
$displayParts['text_btn'] = '0';
}
$displayParts['pview_lnk'] = '1';
return $displayParts;
}
/**
* Defines the parts to display for other statements (probably SELECT)
*
* @param array $displayParts the parts to display
*
* @return array the modified display parts
*/
private function setDisplayPartsForSelect(array $displayParts)
{
// Other statements (ie "SELECT" ones) -> updates
// $displayParts['edit_lnk'], $displayParts['del_lnk'] and
// $displayParts['text_btn'] (keeps other default values)
$fieldsMeta = $this->properties['fields_meta'];
$previousTable = '';
$displayParts['text_btn'] = '1';
$numberOfColumns = $this->properties['fields_cnt'];
for ($i = 0; $i < $numberOfColumns; $i++) {
$isLink = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['sort_lnk'] != '0');
// Displays edit/delete/sort/insert links?
if (
$isLink
&& $previousTable != ''
&& $fieldsMeta[$i]->table != ''
&& $fieldsMeta[$i]->table != $previousTable
) {
// don't display links
$displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
$displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
/**
* @todo May be problematic with same field names
* in two joined table.
*/
if ($displayParts['text_btn'] == '1') {
break;
}
}
// Always display print view link
$displayParts['pview_lnk'] = '1';
if ($fieldsMeta[$i]->table == '') {
continue;
}
$previousTable = $fieldsMeta[$i]->table;
}
if ($previousTable == '') { // no table for any of the columns
// don't display links
$displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
$displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
}
return $displayParts;
}
/**
* Defines the parts to display for the results of a SQL query
* and the total number of rows
*
* @see getTable()
*
* @param array $displayParts the parts to display (see a few
* lines above for explanations)
*
* @return array the first element is an array with explicit indexes
* for all the display elements
* the second element is the total number of rows returned
* by the SQL query without any programmatically appended
* LIMIT clause (just a copy of $unlim_num_rows if it exists,
* else computed inside this function)
*/
private function setDisplayPartsAndTotal(array $displayParts)
{
$theTotal = 0;
// 1. Following variables are needed for use in isset/empty or
// use with array indexes or safe use in foreach
$db = $this->properties['db'];
$table = $this->properties['table'];
$unlimNumRows = $this->properties['unlim_num_rows'];
$numRows = $this->properties['num_rows'];
$printView = $this->properties['printview'];
// 2. Updates the display parts
if ($printView == '1') {
$displayParts = $this->setDisplayPartsForPrintView($displayParts);
} elseif (
$this->properties['is_count'] || $this->properties['is_analyse']
|| $this->properties['is_maint'] || $this->properties['is_explain']
) {
$displayParts = $this->setDisplayPartsForNonData($displayParts);
} elseif ($this->properties['is_show']) {
$displayParts = $this->setDisplayPartsForShow($displayParts);
} else {
$displayParts = $this->setDisplayPartsForSelect($displayParts);
}
// 3. Gets the total number of rows if it is unknown
if ($unlimNumRows > 0) {
$theTotal = $unlimNumRows;
} elseif (
($displayParts['nav_bar'] == '1')
|| ($displayParts['sort_lnk'] == '1')
&& $db !== '' && $table !== ''
) {
$theTotal = $this->dbi->getTable($db, $table)->countRecords();
}
// if for COUNT query, number of rows returned more than 1
// (may be being used GROUP BY)
if ($this->properties['is_count'] && $numRows > 1) {
$displayParts['nav_bar'] = '1';
$displayParts['sort_lnk'] = '1';
}
// 4. If navigation bar or sorting fields names URLs should be
// displayed but there is only one row, change these settings to
// false
if ($displayParts['nav_bar'] == '1' || $displayParts['sort_lnk'] == '1') {
// - Do not display sort links if less than 2 rows.
// - For a VIEW we (probably) did not count the number of rows
// so don't test this number here, it would remove the possibility
// of sorting VIEW results.
$tableObject = new Table($table, $db);
if ($unlimNumRows < 2 && ! $tableObject->isView()) {
$displayParts['sort_lnk'] = '0';
}
}
return [
$displayParts,
$theTotal,
];
}
/**
* Return true if we are executing a query in the form of
* "SELECT * FROM <a table> ..."
*
* @see getTableHeaders(), getColumnParams()
*
* @param array $analyzedSqlResults analyzed sql results
*/
private function isSelect(array $analyzedSqlResults): bool
{
return ! ($this->properties['is_count']
|| $this->properties['is_export']
|| $this->properties['is_func']
|| $this->properties['is_analyse'])
&& ! empty($analyzedSqlResults['select_from'])
&& ! empty($analyzedSqlResults['statement']->from)
&& (count($analyzedSqlResults['statement']->from) === 1)
&& ! empty($analyzedSqlResults['statement']->from[0]->table);
}
/**
* Get a navigation button
*
* @see getMoveBackwardButtonsForTableNavigation(),
* getMoveForwardButtonsForTableNavigation()
*
* @param string $caption iconic caption for button
* @param string $title text for button
* @param int $pos position for next query
* @param string $htmlSqlQuery query ready for display
* @param bool $back whether 'begin' or 'previous'
* @param string $onsubmit optional onsubmit clause
* @param string $inputForRealEnd optional hidden field for special treatment
*
* @return string html content
*/
private function getTableNavigationButton(
$caption,
$title,
$pos,
$htmlSqlQuery,
$back,
$onsubmit = '',
$inputForRealEnd = ''
): string {
$captionOutput = '';
if ($back) {
if (Util::showIcons('TableNavigationLinksMode')) {
$captionOutput .= $caption;
}
if (Util::showText('TableNavigationLinksMode')) {
$captionOutput .= ' ' . $title;
}
} else {
if (Util::showText('TableNavigationLinksMode')) {
$captionOutput .= $title;
}
if (Util::showIcons('TableNavigationLinksMode')) {
$captionOutput .= ' ' . $caption;
}
}
return $this->template->render('display/results/table_navigation_button', [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $htmlSqlQuery,
'pos' => $pos,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
'goto' => $this->properties['goto'],
'input_for_real_end' => $inputForRealEnd,
'caption_output' => $captionOutput,
'title' => $title,
'onsubmit' => $onsubmit,
]);
}
/**
* Possibly return a page selector for table navigation
*
* @return array{string, int} ($output, $nbTotalPage)
*/
private function getHtmlPageSelector(): array
{
$pageNow = (int) floor($_SESSION['tmpval']['pos'] / $_SESSION['tmpval']['max_rows']) + 1;
$nbTotalPage = (int) ceil((int) $this->properties['unlim_num_rows'] / $_SESSION['tmpval']['max_rows']);
$output = '';
if ($nbTotalPage > 1) {
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $this->properties['sql_query'],
'goto' => $this->properties['goto'],
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$output = $this->template->render('display/results/page_selector', [
'url_params' => $urlParams,
'page_selector' => Util::pageselector(
'pos',
$_SESSION['tmpval']['max_rows'],
$pageNow,
$nbTotalPage
),
]);
}
return [
$output,
$nbTotalPage,
];
}
/**
* Get a navigation bar to browse among the results of a SQL query
*
* @see getTable()
*
* @param int $posNext the offset for the "next" page
* @param int $posPrevious the offset for the "previous" page
* @param bool $isInnodb whether its InnoDB or not
* @param array $sortByKeyData the sort by key dialog
*
* @return array
*/
private function getTableNavigation(
int $posNext,
int $posPrevious,
bool $isInnodb,
array $sortByKeyData
): array {
$isShowingAll = $_SESSION['tmpval']['max_rows'] === self::ALL_ROWS;
// Move to the beginning or to the previous page
$moveBackwardButtons = '';
if ($_SESSION['tmpval']['pos'] && ! $isShowingAll) {
$moveBackwardButtons = $this->getMoveBackwardButtonsForTableNavigation(
htmlspecialchars($this->properties['sql_query']),
$posPrevious
);
}
$pageSelector = '';
$numberTotalPage = 1;
if (! $isShowingAll) {
[
$pageSelector,
$numberTotalPage,
] = $this->getHtmlPageSelector();
}
// Move to the next page or to the last one
$moveForwardButtons = '';
if (
// view with unknown number of rows
($this->properties['unlim_num_rows'] === -1 || $this->properties['unlim_num_rows'] === false)
|| (! $isShowingAll
&& intval($_SESSION['tmpval']['pos']) + intval($_SESSION['tmpval']['max_rows'])
< $this->properties['unlim_num_rows']
&& $this->properties['num_rows'] >= $_SESSION['tmpval']['max_rows'])
) {
$moveForwardButtons = $this->getMoveForwardButtonsForTableNavigation(
htmlspecialchars($this->properties['sql_query']),
$posNext,
$isInnodb
);
}
$hiddenFields = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'server' => $this->properties['server'],
'sql_query' => $this->properties['sql_query'],
'is_browse_distinct' => $this->properties['is_browse_distinct'],
'goto' => $this->properties['goto'],
];
return [
'move_backward_buttons' => $moveBackwardButtons,
'page_selector' => $pageSelector,
'move_forward_buttons' => $moveForwardButtons,
'number_total_page' => $numberTotalPage,
'has_show_all' => $GLOBALS['cfg']['ShowAll'] || ($this->properties['unlim_num_rows'] <= 500),
'hidden_fields' => $hiddenFields,
'session_max_rows' => $isShowingAll ? $GLOBALS['cfg']['MaxRows'] : 'all',
'is_showing_all' => $isShowingAll,
'max_rows' => $_SESSION['tmpval']['max_rows'],
'pos' => $_SESSION['tmpval']['pos'],
'sort_by_key' => $sortByKeyData,
];
}
/**
* Prepare move backward buttons - previous and first
*
* @see getTableNavigation()
*
* @param string $htmlSqlQuery the sql encoded by html special characters
* @param int $posPrev the offset for the "previous" page
*
* @return string html content
*/
private function getMoveBackwardButtonsForTableNavigation(
string $htmlSqlQuery,
int $posPrev
): string {
return $this->getTableNavigationButton(
'<<',
_pgettext('First page', 'Begin'),
0,
$htmlSqlQuery,
true
)
. $this->getTableNavigationButton(
'<',
_pgettext('Previous page', 'Previous'),
$posPrev,
$htmlSqlQuery,
true
);
}
/**
* Prepare move forward buttons - next and last
*
* @see getTableNavigation()
*
* @param string $htmlSqlQuery the sql encoded by htmlspecialchars()
* @param int $posNext the offset for the "next" page
* @param bool $isInnodb whether it's InnoDB or not
*
* @return string html content
*/
private function getMoveForwardButtonsForTableNavigation(
string $htmlSqlQuery,
int $posNext,
bool $isInnodb
): string {
// display the Next button
$buttonsHtml = $this->getTableNavigationButton(
'>',
_pgettext('Next page', 'Next'),
$posNext,
$htmlSqlQuery,
false
);
// If the number of rows is unknown, stop here (don't add the End button)
if ($this->properties['unlim_num_rows'] === false) {
return $buttonsHtml;
}
$inputForRealEnd = '';
// prepare some options for the End button
if ($isInnodb && $this->properties['unlim_num_rows'] > $GLOBALS['cfg']['MaxExactCount']) {
$inputForRealEnd = '<input id="real_end_input" type="hidden" name="find_real_end" value="1">';
// no backquote around this message
}
$maxRows = (int) $_SESSION['tmpval']['max_rows'];
$onsubmit = 'onsubmit="return '
. (intval($_SESSION['tmpval']['pos'])
+ $maxRows
< $this->properties['unlim_num_rows']
&& $this->properties['num_rows'] >= $maxRows
? 'true'
: 'false') . '"';
// display the End button
return $buttonsHtml . $this->getTableNavigationButton(
'>>',
_pgettext('Last page', 'End'),
@((int) ceil(
(int) $this->properties['unlim_num_rows']
/ $_SESSION['tmpval']['max_rows']
) - 1) * $maxRows,
$htmlSqlQuery,
false,
$onsubmit,
$inputForRealEnd
);
}
/**
* Get the headers of the results table, for all of the columns
*
* @see getTableHeaders()
*
* @param array $displayParts which elements to display
* @param array $analyzedSqlResults analyzed sql results
* @param array $sortExpression sort expression
* @param array<int, string> $sortExpressionNoDirection sort expression
* without direction
* @param array $sortDirection sort direction
* @param bool $isLimitedDisplay with limited operations
* or not
* @param string $unsortedSqlQuery query without the sort part
*
* @return string html content
*/
private function getTableHeadersForColumns(
array $displayParts,
array $analyzedSqlResults,
array $sortExpression,
array $sortExpressionNoDirection,
array $sortDirection,
$isLimitedDisplay,
$unsortedSqlQuery
) {
// required to generate sort links that will remember whether the
// "Show all" button has been clicked
$sqlMd5 = md5($this->properties['server'] . $this->properties['db'] . $this->properties['sql_query']);
$sessionMaxRows = $isLimitedDisplay
? 0
: $_SESSION['tmpval']['query'][$sqlMd5]['max_rows'];
// Following variable are needed for use in isset/empty or
// use with array indexes/safe use in the for loop
$highlightColumns = $this->properties['highlight_columns'];
$fieldsMeta = $this->properties['fields_meta'];
// Prepare Display column comments if enabled
// ($GLOBALS['cfg']['ShowBrowseComments']).
$commentsMap = $this->getTableCommentsArray($analyzedSqlResults);
[$colOrder, $colVisib] = $this->getColumnParams($analyzedSqlResults);
// optimize: avoid calling a method on each iteration
$numberOfColumns = $this->properties['fields_cnt'];
$columns = [];
for ($j = 0; $j < $numberOfColumns; $j++) {
// PHP 7.4 fix for accessing array offset on bool
$colVisibCurrent = $colVisib[$j] ?? null;
// assign $i with the appropriate column order
$i = $colOrder ? $colOrder[$j] : $j;
// See if this column should get highlight because it's used in the
// where-query.
$name = $fieldsMeta[$i]->name;
$conditionField = isset($highlightColumns[$name])
|| isset($highlightColumns[Util::backquote($name)]);
// Prepare comment-HTML-wrappers for each row, if defined/enabled.
$comments = $this->getCommentForRow($commentsMap, $fieldsMeta[$i]);
$displayParams = $this->properties['display_params'] ?? [];
if (($displayParts['sort_lnk'] == '1') && ! $isLimitedDisplay) {
$sortedHeaderData = $this->getOrderLinkAndSortedHeaderHtml(
$fieldsMeta[$i],
$sortExpression,
$sortExpressionNoDirection,
$unsortedSqlQuery,
$sessionMaxRows,
$comments,
$sortDirection,
$colVisib,
$colVisibCurrent
);
$orderLink = $sortedHeaderData['order_link'];
$columns[] = $sortedHeaderData;
$displayParams['desc'][] = ' <th '
. 'class="draggable'
. ($conditionField ? ' condition' : '')
. '" data-column="' . htmlspecialchars($fieldsMeta[$i]->name)
. '">' . "\n" . $orderLink . $comments . ' </th>' . "\n";
} else {
// Results can't be sorted
// Prepare columns to draggable effect for non sortable columns
$columns[] = [
'column_name' => $fieldsMeta[$i]->name,
'comments' => $comments,
'is_column_hidden' => $colVisib && ! $colVisibCurrent,
'is_column_numeric' => $this->isColumnNumeric($fieldsMeta[$i]),
'has_condition' => $conditionField,
];
$displayParams['desc'][] = ' <th '
. 'class="draggable'
. ($conditionField ? ' condition"' : '')
. '" data-column="' . htmlspecialchars((string) $fieldsMeta[$i]->name)
. '"> '
. htmlspecialchars((string) $fieldsMeta[$i]->name)
. $comments . ' </th>';
}
$this->properties['display_params'] = $displayParams;
}
return $this->template->render('display/results/table_headers_for_columns', [
'is_sortable' => $displayParts['sort_lnk'] == '1' && ! $isLimitedDisplay,
'columns' => $columns,
]);
}
/**
* Get the headers of the results table
*
* @see getTable()
*
* @param array $displayParts which elements to display
* @param array $analyzedSqlResults analyzed sql results
* @param string $unsortedSqlQuery the unsorted sql query
* @param array $sortExpression sort expression
* @param array<int, string> $sortExpressionNoDirection sort expression without direction
* @param array $sortDirection sort direction
* @param bool $isLimitedDisplay with limited operations or not
*
* @psalm-return array{
* column_order: array,
* options: array,
* has_bulk_actions_form: bool,
* button: string,
* table_headers_for_columns: string,
* column_at_right_side: string,
* }
*/
private function getTableHeaders(
array $displayParts,
array $analyzedSqlResults,
$unsortedSqlQuery,
array $sortExpression = [],
array $sortExpressionNoDirection = [],
array $sortDirection = [],
$isLimitedDisplay = false
): array {
// Needed for use in isset/empty or
// use with array indexes/safe use in foreach
$printView = $this->properties['printview'];
$displayParams = $this->properties['display_params'];
// Output data needed for column reordering and show/hide column
$columnOrder = $this->getDataForResettingColumnOrder($analyzedSqlResults);
$displayParams['emptypre'] = 0;
$displayParams['emptyafter'] = 0;
$displayParams['textbtn'] = '';
$fullOrPartialTextLink = '';
$this->properties['display_params'] = $displayParams;
// Display options (if we are not in print view)
$optionsBlock = [];
if (! (isset($printView) && ($printView == '1')) && ! $isLimitedDisplay) {
$optionsBlock = $this->getOptionsBlock();
// prepare full/partial text button or link
$fullOrPartialTextLink = $this->getFullOrPartialTextButtonOrLink();
}
// 1. Set $colspan and generate html with full/partial
// text button or link
$colspan = $displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
&& $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE ? ' colspan="4"' : '';
$buttonHtml = $this->getFieldVisibilityParams($displayParts, $fullOrPartialTextLink, $colspan);
// 2. Displays the fields' name
// 2.0 If sorting links should be used, checks if the query is a "JOIN"
// statement (see 2.1.3)
// See if we have to highlight any header fields of a WHERE query.
// Uses SQL-Parser results.
$this->setHighlightedColumnGlobalField($analyzedSqlResults);
// Get the headers for all of the columns
$tableHeadersForColumns = $this->getTableHeadersForColumns(
$displayParts,
$analyzedSqlResults,
$sortExpression,
$sortExpressionNoDirection,
$sortDirection,
$isLimitedDisplay,
$unsortedSqlQuery
);
// Display column at rightside - checkboxes or empty column
$columnAtRightSide = '';
if (! $printView) {
$columnAtRightSide = $this->getColumnAtRightSide($displayParts, $fullOrPartialTextLink, $colspan);
}
return [
'column_order' => $columnOrder,
'options' => $optionsBlock,
'has_bulk_actions_form' => $displayParts['del_lnk'] === self::DELETE_ROW
|| $displayParts['del_lnk'] === self::KILL_PROCESS,
'button' => $buttonHtml,
'table_headers_for_columns' => $tableHeadersForColumns,
'column_at_right_side' => $columnAtRightSide,
];
}
/**
* Prepare sort by key dropdown - html code segment
*
* @see getTableHeaders()
*
* @param array|null $sortExpression the sort expression
* @param string $unsortedSqlQuery the unsorted sql query
*
* @return array[]
* @psalm-return array{hidden_fields?:array, options?:array}
*/
private function getSortByKeyDropDown(
?array $sortExpression,
string $unsortedSqlQuery
): array {
// grab indexes data:
$indexes = Index::getFromTable($this->properties['table'], $this->properties['db']);
// do we have any index?
if ($indexes === []) {
return [];
}
$hiddenFields = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'server' => $this->properties['server'],
'sort_by_key' => '1',
];
// Keep the number of rows (25, 50, 100, ...) when changing sort key value
if (isset($_SESSION['tmpval']) && isset($_SESSION['tmpval']['max_rows'])) {
$hiddenFields['session_max_rows'] = $_SESSION['tmpval']['max_rows'];
}
$isIndexUsed = false;
$localOrder = is_array($sortExpression) ? implode(', ', $sortExpression) : '';
$options = [];
foreach ($indexes as $index) {
$ascSort = '`'
. implode('` ASC, `', array_keys($index->getColumns()))
. '` ASC';
$descSort = '`'
. implode('` DESC, `', array_keys($index->getColumns()))
. '` DESC';
$isIndexUsed = $isIndexUsed
|| $localOrder === $ascSort
|| $localOrder === $descSort;
$unsortedSqlQueryFirstPart = $unsortedSqlQuery;
$unsortedSqlQuerySecondPart = '';
if (
preg_match(
'@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|LOCK IN SHARE MODE))@is',
$unsortedSqlQuery,
$myReg
)
) {
$unsortedSqlQueryFirstPart = $myReg[1];
$unsortedSqlQuerySecondPart = $myReg[2];
}
$options[] = [
'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
. $ascSort . $unsortedSqlQuerySecondPart,
'content' => $index->getName() . ' (ASC)',
'is_selected' => $localOrder === $ascSort,
];
$options[] = [
'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
. $descSort . $unsortedSqlQuerySecondPart,
'content' => $index->getName() . ' (DESC)',
'is_selected' => $localOrder === $descSort,
];
}
$options[] = [
'value' => $unsortedSqlQuery,
'content' => __('None'),
'is_selected' => ! $isIndexUsed,
];
return ['hidden_fields' => $hiddenFields, 'options' => $options];
}
/**
* Set column span, row span and prepare html with full/partial
* text button or link
*
* @see getTableHeaders()
*
* @param array $displayParts which elements to display
* @param string $fullOrPartialTextLink full/partial link or text button
* @param string $colspan column span of table header
*
* @return string html with full/partial text button or link
*/
private function getFieldVisibilityParams(
array $displayParts,
string $fullOrPartialTextLink,
string $colspan
) {
$displayParams = $this->properties['display_params'];
// 1. Displays the full/partial text button (part 1)...
$buttonHtml = '<thead><tr>' . "\n";
$emptyPreCondition = $displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
&& $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE;
$leftOrBoth = $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT
|| $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH;
// ... before the result table
if (
($displayParts['edit_lnk'] === self::NO_EDIT_OR_DELETE)
&& ($displayParts['del_lnk'] === self::NO_EDIT_OR_DELETE)
&& ($displayParts['text_btn'] == '1')
) {
$displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
} elseif ($leftOrBoth && ($displayParts['text_btn'] == '1')) {
// ... at the left column of the result table header if possible
// and required
$displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
$buttonHtml .= '<th class="column_action position-sticky d-print-none"' . $colspan
. '>' . $fullOrPartialTextLink . '</th>';
} elseif (
$leftOrBoth
&& (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
) {
// ... elseif no button, displays empty(ies) col(s) if required
$displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
$buttonHtml .= '<td' . $colspan . '></td>';
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
// ... elseif display an empty column if the actions links are
// disabled to match the rest of the table
$buttonHtml .= '<th class="column_action position-sticky"></th>';
}
$this->properties['display_params'] = $displayParams;
return $buttonHtml;
}
/**
* Get table comments as array
*
* @see getTableHeaders()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return array table comments
*/
private function getTableCommentsArray(array $analyzedSqlResults)
{
if (! $GLOBALS['cfg']['ShowBrowseComments'] || empty($analyzedSqlResults['statement']->from)) {
return [];
}
$ret = [];
foreach ($analyzedSqlResults['statement']->from as $field) {
if (empty($field->table)) {
continue;
}
$ret[$field->table] = $this->relation->getComments(
empty($field->database) ? $this->properties['db'] : $field->database,
$field->table
);
}
return $ret;
}
/**
* Set global array for store highlighted header fields
*
* @see getTableHeaders()
*
* @param array $analyzedSqlResults analyzed sql results
*/
private function setHighlightedColumnGlobalField(array $analyzedSqlResults): void
{
$highlightColumns = [];
if (! empty($analyzedSqlResults['statement']->where)) {
foreach ($analyzedSqlResults['statement']->where as $expr) {
foreach ($expr->identifiers as $identifier) {
$highlightColumns[$identifier] = 'true';
}
}
}
$this->properties['highlight_columns'] = $highlightColumns;
}
/**
* Prepare data for column restoring and show/hide
*
* @see getTableHeaders()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return array
*/
private function getDataForResettingColumnOrder(array $analyzedSqlResults): array
{
if (! $this->isSelect($analyzedSqlResults)) {
return [];
}
[$columnOrder, $columnVisibility] = $this->getColumnParams($analyzedSqlResults);
$tableCreateTime = '';
$table = new Table($this->properties['table'], $this->properties['db']);
if (! $table->isView()) {
$tableCreateTime = $this->dbi->getTable(
$this->properties['db'],
$this->properties['table']
)->getStatusInfo('Create_time');
}
return [
'order' => $columnOrder,
'visibility' => $columnVisibility,
'is_view' => $table->isView(),
'table_create_time' => $tableCreateTime,
];
}
/**
* Prepare option fields block
*
* @see getTableHeaders()
*
* @return array
*/
private function getOptionsBlock(): array
{
if (
isset($_SESSION['tmpval']['possible_as_geometry'])
&& $_SESSION['tmpval']['possible_as_geometry'] == false
&& $_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM
) {
$_SESSION['tmpval']['geoOption'] = self::GEOMETRY_DISP_WKT;
}
return [
'geo_option' => $_SESSION['tmpval']['geoOption'],
'hide_transformation' => $_SESSION['tmpval']['hide_transformation'],
'display_blob' => $_SESSION['tmpval']['display_blob'],
'display_binary' => $_SESSION['tmpval']['display_binary'],
'relational_display' => $_SESSION['tmpval']['relational_display'],
'possible_as_geometry' => $_SESSION['tmpval']['possible_as_geometry'],
'pftext' => $_SESSION['tmpval']['pftext'],
];
}
/**
* Get full/partial text button or link
*
* @see getTableHeaders()
*
* @return string html content
*/
private function getFullOrPartialTextButtonOrLink(): string
{
global $theme;
$urlParamsFullText = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $this->properties['sql_query'],
'goto' => $this->properties['goto'],
'full_text_button' => 1,
];
if ($_SESSION['tmpval']['pftext'] === self::DISPLAY_FULL_TEXT) {
// currently in fulltext mode so show the opposite link
$tmpImageFile = 's_partialtext.png';
$tmpTxt = __('Partial texts');
$urlParamsFullText['pftext'] = self::DISPLAY_PARTIAL_TEXT;
} else {
$tmpImageFile = 's_fulltext.png';
$tmpTxt = __('Full texts');
$urlParamsFullText['pftext'] = self::DISPLAY_FULL_TEXT;
}
$tmpImage = '<img class="fulltext" src="'
. ($theme instanceof Theme ? $theme->getImgPath($tmpImageFile) : '')
. '" alt="' . $tmpTxt . '" title="' . $tmpTxt . '">';
return Generator::linkOrButton(Url::getFromRoute('/sql'), $urlParamsFullText, $tmpImage);
}
/**
* Get comment for row
*
* @see getTableHeaders()
*
* @param array $commentsMap comments array
* @param FieldMetadata $fieldsMeta set of field properties
*
* @return string html content
*/
private function getCommentForRow(array $commentsMap, FieldMetadata $fieldsMeta): string
{
return $this->template->render('display/results/comment_for_row', [
'comments_map' => $commentsMap,
'column_name' => $fieldsMeta->name,
'table_name' => $fieldsMeta->table,
'limit_chars' => $GLOBALS['cfg']['LimitChars'],
]);
}
/**
* Prepare parameters and html for sorted table header fields
*
* @see getTableHeaders()
*
* @param FieldMetadata $fieldsMeta set of field properties
* @param array $sortExpression sort expression
* @param array<int, string> $sortExpressionNoDirection sort expression without direction
* @param string $unsortedSqlQuery the unsorted sql query
* @param int $sessionMaxRows maximum rows resulted by sql
* @param string $comments comment for row
* @param array $sortDirection sort direction
* @param bool $colVisib column is visible(false)
* or column isn't visible(string array)
* @param string $colVisibElement element of $col_visib array
*
* @return array 2 element array - $orderLink, $sortedHeaderHtml
* @psalm-return array{
* column_name: string,
* order_link: string,
* comments: string,
* is_browse_pointer_enabled: bool,
* is_browse_marker_enabled: bool,
* is_column_hidden: bool,
* is_column_numeric: bool,
* }
*/
private function getOrderLinkAndSortedHeaderHtml(
FieldMetadata $fieldsMeta,
array $sortExpression,
array $sortExpressionNoDirection,
$unsortedSqlQuery,
$sessionMaxRows,
string $comments,
array $sortDirection,
$colVisib,
$colVisibElement
): array {
// Checks if the table name is required; it's the case
// for a query with a "JOIN" statement and if the column
// isn't aliased, or in queries like
// SELECT `1`.`master_field` , `2`.`master_field`
// FROM `PMA_relation` AS `1` , `PMA_relation` AS `2`
$sortTable = $fieldsMeta->table !== ''
&& $fieldsMeta->orgname === $fieldsMeta->name
? Util::backquote($fieldsMeta->table) . '.'
: '';
// Generates the orderby clause part of the query which is part
// of URL
[$singleSortOrder, $multiSortOrder, $orderImg] = $this->getSingleAndMultiSortUrls(
$sortExpression,
$sortExpressionNoDirection,
$sortTable,
$fieldsMeta->name,
$sortDirection,
$fieldsMeta
);
if (
preg_match(
'@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|LOCK IN SHARE MODE))@is',
$unsortedSqlQuery,
$regs3
)
) {
$singleSortedSqlQuery = $regs3[1] . $singleSortOrder . $regs3[2];
$multiSortedSqlQuery = $regs3[1] . $multiSortOrder . $regs3[2];
} else {
$singleSortedSqlQuery = $unsortedSqlQuery . $singleSortOrder;
$multiSortedSqlQuery = $unsortedSqlQuery . $multiSortOrder;
}
$singleUrlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $singleSortedSqlQuery,
'sql_signature' => Core::signSqlQuery($singleSortedSqlQuery),
'session_max_rows' => $sessionMaxRows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$multiUrlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $multiSortedSqlQuery,
'sql_signature' => Core::signSqlQuery($multiSortedSqlQuery),
'session_max_rows' => $sessionMaxRows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
// Displays the sorting URL
// enable sort order swapping for image
$orderLink = $this->getSortOrderLink($orderImg, $fieldsMeta, $singleUrlParams, $multiUrlParams);
$orderLink .= $this->getSortOrderHiddenInputs($multiUrlParams, $fieldsMeta->name);
return [
'column_name' => $fieldsMeta->name,
'order_link' => $orderLink,
'comments' => $comments,
'is_browse_pointer_enabled' => $GLOBALS['cfg']['BrowsePointerEnable'] === true,
'is_browse_marker_enabled' => $GLOBALS['cfg']['BrowseMarkerEnable'] === true,
'is_column_hidden' => $colVisib && ! $colVisibElement,
'is_column_numeric' => $this->isColumnNumeric($fieldsMeta),
];
}
/**
* Prepare parameters and html for sorted table header fields
*
* @param array $sortExpression sort expression
* @param array<int, string> $sortExpressionNoDirection sort expression without direction
* @param string $sortTable The name of the table to which
* the current column belongs to
* @param string $nameToUseInSort The current column under
* consideration
* @param string[] $sortDirection sort direction
* @param FieldMetadata $fieldsMeta set of field properties
*
* @return string[] 3 element array - $single_sort_order, $sort_order, $order_img
*/
private function getSingleAndMultiSortUrls(
array $sortExpression,
array $sortExpressionNoDirection,
string $sortTable,
string $nameToUseInSort,
array $sortDirection,
FieldMetadata $fieldsMeta
): array {
// Check if the current column is in the order by clause
$isInSort = $this->isInSorted($sortExpression, $sortExpressionNoDirection, $sortTable, $nameToUseInSort);
$currentName = $nameToUseInSort;
if ($sortExpressionNoDirection[0] == '' || ! $isInSort) {
$specialIndex = $sortExpressionNoDirection[0] == ''
? 0
: count($sortExpressionNoDirection);
$sortExpressionNoDirection[$specialIndex] = Util::backquote($currentName);
$isTimeOrDate = $fieldsMeta->isType(FieldMetadata::TYPE_TIME)
|| $fieldsMeta->isType(FieldMetadata::TYPE_DATE)
|| $fieldsMeta->isType(FieldMetadata::TYPE_DATETIME)
|| $fieldsMeta->isType(FieldMetadata::TYPE_TIMESTAMP);
$sortDirection[$specialIndex] = $isTimeOrDate ? self::DESCENDING_SORT_DIR : self::ASCENDING_SORT_DIR;
}
$sortExpressionNoDirection = array_filter($sortExpressionNoDirection);
$singleSortOrder = '';
$sortOrderColumns = [];
foreach ($sortExpressionNoDirection as $index => $expression) {
$sortOrder = '';
// check if this is the first clause,
// if it is then we have to add "order by"
$isFirstClause = ($index === 0);
$nameToUseInSort = $expression;
$sortTableNew = $sortTable;
// Test to detect if the column name is a standard name
// Standard name has the table name prefixed to the column name
if (str_contains($nameToUseInSort, '.') && ! str_contains($nameToUseInSort, '(')) {
$matches = explode('.', $nameToUseInSort);
// Matches[0] has the table name
// Matches[1] has the column name
$nameToUseInSort = $matches[1];
$sortTableNew = $matches[0];
}
// $name_to_use_in_sort might contain a space due to
// formatting of function expressions like "COUNT(name )"
// so we remove the space in this situation
$nameToUseInSort = str_replace([' )', '``'], [')', '`'], $nameToUseInSort);
$nameToUseInSort = trim($nameToUseInSort, '`');
// If this the first column name in the order by clause add
// order by clause to the column name
$sortOrder .= $isFirstClause ? "\nORDER BY " : '';
// Again a check to see if the given column is a aggregate column
if (str_contains($nameToUseInSort, '(')) {
$sortOrder .= $nameToUseInSort;
} else {
if ($sortTableNew !== '' && ! str_ends_with($sortTableNew, '.')) {
$sortTableNew .= '.';
}
$sortOrder .= $sortTableNew . Util::backquote($nameToUseInSort);
}
// Incase this is the current column save $single_sort_order
if ($currentName === $nameToUseInSort) {
$singleSortOrder = "\n" . 'ORDER BY ';
if (! str_contains($currentName, '(')) {
$singleSortOrder .= $sortTable;
}
$singleSortOrder .= Util::backquote($currentName) . ' ';
if ($isInSort) {
[$singleSortOrder, $orderImg] = $this->getSortingUrlParams(
$sortDirection[$index],
$singleSortOrder
);
} else {
$singleSortOrder .= strtoupper($sortDirection[$index]);
}
}
$sortOrder .= ' ';
if ($currentName === $nameToUseInSort && $isInSort) {
// We need to generate the arrow button and related html
[$sortOrder, $orderImg] = $this->getSortingUrlParams($sortDirection[$index], $sortOrder);
$orderImg .= ' <small>' . ($index + 1) . '</small>';
} else {
$sortOrder .= strtoupper($sortDirection[$index]);
}
// Separate columns by a comma
$sortOrderColumns[] = $sortOrder;
}
return [
$singleSortOrder,
implode(', ', $sortOrderColumns),
$orderImg ?? '',
];
}
/**
* Check whether the column is sorted
*
* @see getTableHeaders()
*
* @param array $sortExpression sort expression
* @param array $sortExpressionNoDirection sort expression without direction
* @param string $sortTable the table name
* @param string $nameToUseInSort the sorting column name
*/
private function isInSorted(
array $sortExpression,
array $sortExpressionNoDirection,
string $sortTable,
string $nameToUseInSort
): bool {
$indexInExpression = 0;
foreach ($sortExpressionNoDirection as $index => $clause) {
if (str_contains($clause, '.')) {
$fragments = explode('.', $clause);
$clause2 = $fragments[0] . '.' . str_replace('`', '', $fragments[1]);
} else {
$clause2 = $sortTable . str_replace('`', '', $clause);
}
if ($clause2 === $sortTable . $nameToUseInSort) {
$indexInExpression = $index;
break;
}
}
if (empty($sortExpression[$indexInExpression])) {
return false;
}
// Field name may be preceded by a space, or any number
// of characters followed by a dot (tablename.fieldname)
// so do a direct comparison for the sort expression;
// this avoids problems with queries like
// "SELECT id, count(id)..." and clicking to sort
// on id or on count(id).
// Another query to test this:
// SELECT p.*, FROM_UNIXTIME(p.temps) FROM mytable AS p
// (and try clicking on each column's header twice)
$noSortTable = $sortTable === '' || mb_strpos(
$sortExpressionNoDirection[$indexInExpression],
$sortTable
) === false;
$noOpenParenthesis = mb_strpos($sortExpressionNoDirection[$indexInExpression], '(') === false;
if ($sortTable !== '' && $noSortTable && $noOpenParenthesis) {
$newSortExpressionNoDirection = $sortTable
. $sortExpressionNoDirection[$indexInExpression];
} else {
$newSortExpressionNoDirection = $sortExpressionNoDirection[$indexInExpression];
}
//Back quotes are removed in next comparison, so remove them from value
//to compare.
$nameToUseInSort = str_replace('`', '', $nameToUseInSort);
$sortName = str_replace('`', '', $sortTable) . $nameToUseInSort;
return $sortName == str_replace('`', '', $newSortExpressionNoDirection)
|| $sortName == str_replace('`', '', $sortExpressionNoDirection[$indexInExpression]);
}
/**
* Get sort url parameters - sort order and order image
*
* @see getSingleAndMultiSortUrls()
*
* @param string $sortDirection the sort direction
* @param string $sortOrder the sorting order
*
* @return string[] 2 element array - $sort_order, $order_img
*/
private function getSortingUrlParams(string $sortDirection, $sortOrder): array
{
if (strtoupper(trim($sortDirection)) === self::DESCENDING_SORT_DIR) {
$sortOrder .= self::ASCENDING_SORT_DIR;
$orderImg = ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg',
'title' => '',
]
);
$orderImg .= ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
} else {
$sortOrder .= self::DESCENDING_SORT_DIR;
$orderImg = ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg',
'title' => '',
]
);
$orderImg .= ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
}
return [
$sortOrder,
$orderImg,
];
}
/**
* Get sort order link
*
* @see getTableHeaders()
*
* @param string $orderImg the sort order image
* @param FieldMetadata $fieldsMeta set of field properties
* @param array<int|string, mixed> $orderUrlParams the url params for sort
* @param array<int|string, mixed> $multiOrderUrlParams the url params for sort
*
* @return string the sort order link
*/
private function getSortOrderLink(
string $orderImg,
FieldMetadata $fieldsMeta,
array $orderUrlParams,
array $multiOrderUrlParams
): string {
$urlPath = Url::getFromRoute('/sql');
$innerLinkContent = htmlspecialchars($fieldsMeta->name) . $orderImg
. '<input type="hidden" value="'
. $urlPath
. Url::getCommon($multiOrderUrlParams, str_contains($urlPath, '?') ? '&' : '?', false)
. '">';
return Generator::linkOrButton(
Url::getFromRoute('/sql'),
$orderUrlParams,
$innerLinkContent,
['class' => 'sortlink']
);
}
private function getSortOrderHiddenInputs(
array $multipleUrlParams,
string $nameToUseInSort
): string {
$sqlQuery = $multipleUrlParams['sql_query'];
$sqlQueryAdd = $sqlQuery;
$sqlQueryRemove = null;
$parser = new Parser($sqlQuery);
$firstStatement = $parser->statements[0] ?? null;
$numberOfClausesFound = null;
if ($firstStatement instanceof SelectStatement) {
$orderClauses = $firstStatement->order ?? [];
foreach ($orderClauses as $key => $order) {
// If this is the column name, then remove it from the order clause
if ($order->expr->column !== $nameToUseInSort) {
continue;
}
// remove the order clause for this column and from the counted array
unset($firstStatement->order[$key], $orderClauses[$key]);
}
$numberOfClausesFound = count($orderClauses);
$sqlQueryRemove = $firstStatement->build();
}
$multipleUrlParams['sql_query'] = $sqlQueryRemove ?? $sqlQuery;
$multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
$urlRemoveOrder = Url::getFromRoute('/sql', $multipleUrlParams);
if ($numberOfClausesFound === 0) {
$urlRemoveOrder .= '&discard_remembered_sort=1';
}
$multipleUrlParams['sql_query'] = $sqlQueryAdd;
$multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
$urlAddOrder = Url::getFromRoute('/sql', $multipleUrlParams);
return '<input type="hidden" name="url-remove-order" value="' . $urlRemoveOrder . '">' . "\n"
. '<input type="hidden" name="url-add-order" value="' . $urlAddOrder . '">';
}
/**
* Check if the column contains numeric data
*
* @param FieldMetadata $fieldsMeta set of field properties
*/
private function isColumnNumeric(FieldMetadata $fieldsMeta): bool
{
// This was defined in commit b661cd7c9b31f8bc564d2f9a1b8527e0eb966de8
// For issue https://github.com/phpmyadmin/phpmyadmin/issues/4746
return $fieldsMeta->isType(FieldMetadata::TYPE_REAL)
|| $fieldsMeta->isMappedTypeBit
|| $fieldsMeta->isType(FieldMetadata::TYPE_INT);
}
/**
* Prepare column to show at right side - check boxes or empty column
*
* @see getTableHeaders()
*
* @param array $displayParts which elements to display
* @param string $fullOrPartialTextLink full/partial link or text button
* @param string $colspan column span of table header
*
* @return string html content
*/
private function getColumnAtRightSide(
array $displayParts,
string $fullOrPartialTextLink,
string $colspan
) {
$rightColumnHtml = '';
$displayParams = $this->properties['display_params'];
// Displays the needed checkboxes at the right
// column of the result table header if possible and required...
if (
($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_RIGHT)
|| ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
&& (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
&& ($displayParts['text_btn'] == '1')
) {
$displayParams['emptyafter'] = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
&& ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
$rightColumnHtml .= "\n"
. '<th class="column_action d-print-none"' . $colspan . '>'
. $fullOrPartialTextLink
. '</th>';
} elseif (
($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT)
|| ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
&& (($displayParts['edit_lnk'] === self::NO_EDIT_OR_DELETE)
&& ($displayParts['del_lnk'] === self::NO_EDIT_OR_DELETE))
&& (! isset($GLOBALS['is_header_sent']) || ! $GLOBALS['is_header_sent'])
) {
// ... elseif no button, displays empty columns if required
// (unless coming from Browse mode print view)
$displayParams['emptyafter'] = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
&& ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
$rightColumnHtml .= "\n" . '<td class="d-print-none"' . $colspan
. '></td>';
}
$this->properties['display_params'] = $displayParams;
return $rightColumnHtml;
}
/**
* Prepares the display for a value
*
* @see getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param string $value value to display
*
* @return string the td
*/
private function buildValueDisplay($class, $conditionField, $value)
{
return $this->template->render('display/results/value_display', [
'class' => $class,
'condition_field' => $conditionField,
'value' => $value,
]);
}
/**
* Prepares the display for a null value
*
* @see getDataCellForNumericColumns(),
* getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param FieldMetadata $meta the meta-information about this field
*
* @return string the td
*/
private function buildNullDisplay(string $class, bool $conditionField, FieldMetadata $meta): string
{
$classes = $this->addClass($class, $conditionField, $meta, '');
return $this->template->render('display/results/null_display', [
'data_decimals' => $meta->decimals,
'data_type' => $meta->getMappedType(),
'classes' => $classes,
]);
}
/**
* Prepares the display for an empty value
*
* @see getDataCellForNumericColumns(),
* getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param FieldMetadata $meta the meta-information about this field
*
* @return string the td
*/
private function buildEmptyDisplay(string $class, bool $conditionField, FieldMetadata $meta): string
{
$classes = $this->addClass($class, $conditionField, $meta, 'text-nowrap');
return $this->template->render('display/results/empty_display', ['classes' => $classes]);
}
/**
* Adds the relevant classes.
*
* @see buildNullDisplay(), getRowData()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param FieldMetadata $meta the meta-information about the field
* @param string $nowrap avoid wrapping
* @param bool $isFieldTruncated is field truncated (display ...)
*
* @return string the list of classes
*/
private function addClass(
string $class,
bool $conditionField,
FieldMetadata $meta,
string $nowrap,
bool $isFieldTruncated = false,
bool $hasTransformationPlugin = false
): string {
$classes = array_filter([
$class,
$nowrap,
]);
if (isset($meta->internalMediaType)) {
$classes[] = preg_replace('/\//', '_', $meta->internalMediaType);
}
if ($conditionField) {
$classes[] = 'condition';
}
if ($isFieldTruncated) {
$classes[] = 'truncated';
}
$mediaTypeMap = $this->properties['mime_map'];
$orgFullColName = $this->properties['db'] . '.' . $meta->orgtable
. '.' . $meta->orgname;
if ($hasTransformationPlugin || ! empty($mediaTypeMap[$orgFullColName]['input_transformation'])) {
$classes[] = 'transformed';
}
// Define classes to be added to this data field based on the type of data
if ($meta->isEnum()) {
$classes[] = 'enum';
}
if ($meta->isSet()) {
$classes[] = 'set';
}
if ($meta->isMappedTypeBit) {
$classes[] = 'bit';
}
if ($meta->isBinary()) {
$classes[] = 'hex';
}
return implode(' ', $classes);
}
/**
* Prepare the body of the results table
*
* @see getTable()
*
* @param ResultInterface $dtResult the link id associated to the query
* which results have to be displayed
* @param array $displayParts which elements to display
* @param array<string, string[]> $map the list of relations
* @param array $analyzedSqlResults analyzed sql results
* @param bool $isLimitedDisplay with limited operations or not
*
* @return string html content
*
* @global array $row current row data
*/
private function getTableBody(
ResultInterface $dtResult,
array $displayParts,
array $map,
array $analyzedSqlResults,
$isLimitedDisplay = false
) {
// Mostly because of browser transformations, to make the row-data accessible in a plugin.
global $row;
$tableBodyHtml = '';
// query without conditions to shorten URLs when needed, 200 is just
// guess, it should depend on remaining URL length
$urlSqlQuery = $this->getUrlSqlQuery($analyzedSqlResults);
$displayParams = $this->properties['display_params'];
$rowNumber = 0;
$displayParams['edit'] = [];
$displayParams['copy'] = [];
$displayParams['delete'] = [];
$displayParams['data'] = [];
$displayParams['row_delete'] = [];
$this->properties['display_params'] = $displayParams;
// name of the class added to all grid editable elements;
// if we don't have all the columns of a unique key in the result set,
// do not permit grid editing
if ($isLimitedDisplay || ! $this->properties['editable']) {
$gridEditClass = '';
} else {
switch ($GLOBALS['cfg']['GridEditing']) {
case 'double-click':
// trying to reduce generated HTML by using shorter
// classes like click1 and click2
$gridEditClass = 'grid_edit click2';
break;
case 'click':
$gridEditClass = 'grid_edit click1';
break;
default: // 'disabled'
$gridEditClass = '';
break;
}
}
// prepare to get the column order, if available
[$colOrder, $colVisib] = $this->getColumnParams($analyzedSqlResults);
// Correction University of Virginia 19991216 in the while below
// Previous code assumed that all tables have keys, specifically that
// the phpMyAdmin GUI should support row delete/edit only for such
// tables.
// Although always using keys is arguably the prescribed way of
// defining a relational table, it is not required. This will in
// particular be violated by the novice.
// We want to encourage phpMyAdmin usage by such novices. So the code
// below has been changed to conditionally work as before when the
// table being displayed has one or more keys; but to display
// delete/edit options correctly for tables without keys.
$whereClauseMap = $this->properties['whereClauseMap'];
while ($row = $dtResult->fetchRow()) {
// add repeating headers
if (
($rowNumber !== 0) && ($_SESSION['tmpval']['repeat_cells'] > 0)
&& ($rowNumber % $_SESSION['tmpval']['repeat_cells']) === 0
) {
$tableBodyHtml .= $this->getRepeatingHeaders(
$displayParams['emptypre'],
$displayParams['desc'],
$displayParams['emptyafter']
);
}
$trClass = [];
if ($GLOBALS['cfg']['BrowsePointerEnable'] != true) {
$trClass[] = 'nopointer';
}
if ($GLOBALS['cfg']['BrowseMarkerEnable'] != true) {
$trClass[] = 'nomarker';
}
// pointer code part
$tableBodyHtml .= '<tr' . ($trClass === [] ? '' : ' class="' . implode(' ', $trClass) . '"') . '>';
// 1. Prepares the row
// In print view these variable needs to be initialized
$deleteUrl = null;
$deleteString = null;
$editString = null;
$jsConf = null;
$copyUrl = null;
$copyString = null;
$editUrl = null;
$editCopyUrlParams = [];
$delUrlParams = null;
// 1.2 Defines the URLs for the modify/delete link(s)
if (
($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
) {
$expressions = [];
if (
isset($analyzedSqlResults['statement'])
&& $analyzedSqlResults['statement'] instanceof SelectStatement
) {
$expressions = $analyzedSqlResults['statement']->expr;
}
// Results from a "SELECT" statement -> builds the
// WHERE clause to use in links (a unique key if possible)
/**
* @todo $where_clause could be empty, for example a table
* with only one field and it's a BLOB; in this case,
* avoid to display the delete and edit links
*/
[$whereClause, $clauseIsUnique, $conditionArray] = Util::getUniqueCondition(
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$this->properties['table'],
$expressions
);
$whereClauseMap[$rowNumber][$this->properties['table']] = $whereClause;
$this->properties['whereClauseMap'] = $whereClauseMap;
// 1.2.1 Modify link(s) - update row case
if ($displayParts['edit_lnk'] === self::UPDATE_ROW) {
[
$editUrl,
$copyUrl,
$editString,
$copyString,
$editCopyUrlParams,
] = $this->getModifiedLinks($whereClause, $clauseIsUnique, $urlSqlQuery);
}
// 1.2.2 Delete/Kill link(s)
[$deleteUrl, $deleteString, $jsConf, $delUrlParams] = $this->getDeleteAndKillLinks(
$whereClause,
$clauseIsUnique,
$urlSqlQuery,
$displayParts['del_lnk'],
(int) $row[0]
);
// 1.3 Displays the links at left if required
if (
($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT)
|| ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_LEFT,
'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => [
'url' => $editUrl,
'params' => $editCopyUrlParams + ['default_action' => 'update'],
'string' => $editString,
'clause_is_unique' => $clauseIsUnique,
],
'copy' => [
'url' => $copyUrl,
'params' => $editCopyUrlParams + ['default_action' => 'insert'],
'string' => $copyString,
],
'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause,
'condition' => json_encode($conditionArray),
'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_NONE,
'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => [
'url' => $editUrl,
'params' => $editCopyUrlParams + ['default_action' => 'update'],
'string' => $editString,
'clause_is_unique' => $clauseIsUnique,
],
'copy' => [
'url' => $copyUrl,
'params' => $editCopyUrlParams + ['default_action' => 'insert'],
'string' => $copyString,
],
'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause,
'condition' => json_encode($conditionArray),
'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
}
}
// 2. Displays the rows' values
if ($this->properties['mime_map'] === null) {
$this->setMimeMap();
}
$tableBodyHtml .= $this->getRowValues(
$row,
$rowNumber,
$colOrder,
$map,
$gridEditClass,
$colVisib,
$urlSqlQuery,
$analyzedSqlResults
);
// 3. Displays the modify/delete links on the right if required
if (
($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
|| $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
&& ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_RIGHT
|| $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_RIGHT,
'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => [
'url' => $editUrl,
'params' => $editCopyUrlParams + ['default_action' => 'update'],
'string' => $editString,
'clause_is_unique' => $clauseIsUnique ?? true,
],
'copy' => [
'url' => $copyUrl,
'params' => $editCopyUrlParams + ['default_action' => 'insert'],
'string' => $copyString,
],
'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause ?? '',
'condition' => json_encode($conditionArray ?? []),
'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
}
$tableBodyHtml .= '</tr>';
$tableBodyHtml .= "\n";
$rowNumber++;
}
return $tableBodyHtml;
}
/**
* Sets the MIME details of the columns in the results set
*/
private function setMimeMap(): void
{
$fieldsMeta = $this->properties['fields_meta'];
$mediaTypeMap = [];
$added = [];
$relationParameters = $this->relation->getRelationParameters();
for ($currentColumn = 0; $currentColumn < $this->properties['fields_cnt']; ++$currentColumn) {
$meta = $fieldsMeta[$currentColumn];
$orgFullTableName = $this->properties['db'] . '.' . $meta->orgtable;
if (
$relationParameters->columnCommentsFeature === null
|| $relationParameters->browserTransformationFeature === null
|| ! $GLOBALS['cfg']['BrowseMIME']
|| $_SESSION['tmpval']['hide_transformation']
|| ! empty($added[$orgFullTableName])
) {
continue;
}
$mediaTypeMap = array_merge(
$mediaTypeMap,
$this->transformations->getMime($this->properties['db'], $meta->orgtable, false, true) ?? []
);
$added[$orgFullTableName] = true;
}
// special browser transformation for some SHOW statements
if ($this->properties['is_show'] && ! $_SESSION['tmpval']['hide_transformation']) {
preg_match(
'@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
. 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
. ')@i',
$this->properties['sql_query'],
$which
);
if (isset($which[1])) {
$str = ' ' . strtoupper($which[1]);
$isShowProcessList = strpos($str, 'PROCESSLIST') > 0;
if ($isShowProcessList) {
$mediaTypeMap['..Info'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
$isShowCreateTable = preg_match('@CREATE[[:space:]]+TABLE@i', $this->properties['sql_query']);
if ($isShowCreateTable) {
$mediaTypeMap['..Create Table'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
}
}
$this->properties['mime_map'] = $mediaTypeMap;
}
/**
* Get the values for one data row
*
* @see getTableBody()
*
* @param array $row current row data
* @param int $rowNumber the index of current row
* @param array|false $colOrder the column order false when
* a property not found false
* when a property not found
* @param array<string, string[]> $map the list of relations
* @param string $gridEditClass the class for all editable
* columns
* @param bool|array|string $colVisib column is visible(false);
* column isn't visible(string
* array)
* @param string $urlSqlQuery the analyzed sql query
* @param array $analyzedSqlResults analyzed sql results
*
* @return string html content
*/
private function getRowValues(
array $row,
$rowNumber,
$colOrder,
array $map,
$gridEditClass,
$colVisib,
$urlSqlQuery,
array $analyzedSqlResults
) {
$rowValuesHtml = '';
// Following variable are needed for use in isset/empty or
// use with array indexes/safe use in foreach
$sqlQuery = $this->properties['sql_query'];
$fieldsMeta = $this->properties['fields_meta'];
$highlightColumns = $this->properties['highlight_columns'];
$mediaTypeMap = $this->properties['mime_map'];
$rowInfo = $this->getRowInfoForSpecialLinks($row, $colOrder);
$whereClauseMap = $this->properties['whereClauseMap'];
$columnCount = $this->properties['fields_cnt'];
// Load SpecialSchemaLinks for all rows
$specialSchemaLinks = SpecialSchemaLinks::get();
$relationParameters = $this->relation->getRelationParameters();
for ($currentColumn = 0; $currentColumn < $columnCount; ++$currentColumn) {
// assign $i with appropriate column order
$i = is_array($colOrder) ? $colOrder[$currentColumn] : $currentColumn;
$meta = $fieldsMeta[$i];
$orgFullColName = $this->properties['db'] . '.' . $meta->orgtable . '.' . $meta->orgname;
$notNullClass = $meta->isNotNull() ? 'not_null' : '';
$relationClass = isset($map[$meta->name]) ? 'relation' : '';
$hideClass = is_array($colVisib) && isset($colVisib[$currentColumn]) && ! $colVisib[$currentColumn]
? 'hide'
: '';
$gridEdit = $meta->orgtable != '' ? $gridEditClass : '';
// handle datetime-related class, for grid editing
$fieldTypeClass = $this->getClassForDateTimeRelatedFields($meta);
// combine all the classes applicable to this column's value
$class = implode(' ', array_filter([
'data',
$gridEdit,
$notNullClass,
$relationClass,
$hideClass,
$fieldTypeClass,
]));
// See if this column should get highlight because it's used in the
// where-query.
$conditionField = isset($highlightColumns)
&& (isset($highlightColumns[$meta->name])
|| isset($highlightColumns[Util::backquote($meta->name)]));
// Wrap MIME-transformations. [MIME]
$transformationPlugin = null;
$transformOptions = [];
if ($relationParameters->browserTransformationFeature !== null && $GLOBALS['cfg']['BrowseMIME']) {
if (
isset($mediaTypeMap[$orgFullColName]['mimetype'])
&& ! empty($mediaTypeMap[$orgFullColName]['transformation'])
) {
$file = $mediaTypeMap[$orgFullColName]['transformation'];
$includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
if (@file_exists(ROOT_PATH . $includeFile)) {
$className = $this->transformations->getClassName($includeFile);
if (class_exists($className)) {
$plugin = new $className();
if ($plugin instanceof TransformationsPlugin) {
$transformationPlugin = $plugin;
$transformOptions = $this->transformations->getOptions(
$mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
);
$meta->internalMediaType = str_replace(
'_',
'/',
$mediaTypeMap[$orgFullColName]['mimetype']
);
}
}
}
}
}
// Check whether the field needs to display with syntax highlighting
$dbLower = mb_strtolower($this->properties['db']);
$tblLower = mb_strtolower($meta->orgtable);
$nameLower = mb_strtolower($meta->orgname);
if (
! empty($this->transformationInfo[$dbLower][$tblLower][$nameLower])
&& isset($row[$i])
&& (trim($row[$i]) != '')
&& ! $_SESSION['tmpval']['hide_transformation']
) {
/** @psalm-suppress UnresolvableInclude */
include_once ROOT_PATH . $this->transformationInfo[$dbLower][$tblLower][$nameLower][0];
$plugin = new $this->transformationInfo[$dbLower][$tblLower][$nameLower][1]();
if ($plugin instanceof TransformationsPlugin) {
$transformationPlugin = $plugin;
$transformOptions = $this->transformations->getOptions(
$mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
);
$orgTable = mb_strtolower($meta->orgtable);
$orgName = mb_strtolower($meta->orgname);
$meta->internalMediaType = str_replace(
'_',
'/',
$this->transformationInfo[$dbLower][$orgTable][$orgName][2]
);
}
}
// Check for the predefined fields need to show as link in schemas
if (! empty($specialSchemaLinks[$dbLower][$tblLower][$nameLower])) {
$linkingUrl = $this->getSpecialLinkUrl(
$specialSchemaLinks[$dbLower][$tblLower][$nameLower],
$row[$i],
$rowInfo
);
$transformationPlugin = new Text_Plain_Link();
$transformOptions = [
0 => $linkingUrl,
2 => true,
];
$meta->internalMediaType = str_replace('_', '/', 'Text/Plain');
}
$expressions = [];
if (
isset($analyzedSqlResults['statement'])
&& $analyzedSqlResults['statement'] instanceof SelectStatement
) {
$expressions = $analyzedSqlResults['statement']->expr;
}
/**
* The result set can have columns from more than one table,
* this is why we have to check for the unique conditions
* related to this table; however getUniqueCondition() is
* costly and does not need to be called if we already know
* the conditions for the current table.
*/
if (! isset($whereClauseMap[$rowNumber][$meta->orgtable])) {
$uniqueConditions = Util::getUniqueCondition(
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$meta->orgtable,
$expressions
);
$whereClauseMap[$rowNumber][$meta->orgtable] = $uniqueConditions[0];
}
$urlParams = [
'db' => $this->properties['db'],
'table' => $meta->orgtable,
'where_clause_sign' => Core::signSqlQuery($whereClauseMap[$rowNumber][$meta->orgtable]),
'where_clause' => $whereClauseMap[$rowNumber][$meta->orgtable],
'transform_key' => $meta->orgname,
];
if ($sqlQuery !== '') {
$urlParams['sql_query'] = $urlSqlQuery;
}
$transformOptions['wrapper_link'] = Url::getCommon($urlParams);
$transformOptions['wrapper_params'] = $urlParams;
$displayParams = $this->properties['display_params'] ?? [];
if ($meta->isNumeric) {
// n u m e r i c
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForNumericColumns(
$row[$i] === null ? null : (string) $row[$i],
'text-end ' . $class,
$conditionField,
$meta,
$map,
$analyzedSqlResults,
$transformationPlugin,
$transformOptions
);
} elseif ($meta->isMappedTypeGeometry) {
// g e o m e t r y
// Remove 'grid_edit' from $class as we do not allow to
// inline-edit geometry data.
$class = str_replace('grid_edit', '', $class);
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForGeometryColumns(
$row[$i] === null ? null : (string) $row[$i],
$class,
$meta,
$map,
$urlParams,
$conditionField,
$transformationPlugin,
$transformOptions,
$analyzedSqlResults
);
} else {
// n o t n u m e r i c
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForNonNumericColumns(
$row[$i] === null ? null : (string) $row[$i],
$class,
$meta,
$map,
$urlParams,
$conditionField,
$transformationPlugin,
$transformOptions,
$analyzedSqlResults
);
}
// output stored cell
$rowValuesHtml .= $displayParams['data'][$rowNumber][$i];
if (isset($displayParams['rowdata'][$i][$rowNumber])) {
$displayParams['rowdata'][$i][$rowNumber] .= $displayParams['data'][$rowNumber][$i];
} else {
$displayParams['rowdata'][$i][$rowNumber] = $displayParams['data'][$rowNumber][$i];
}
$this->properties['display_params'] = $displayParams;
}
return $rowValuesHtml;
}
/**
* Get link for display special schema links
*
* @param array<string,array<int,array<string,string>>|string> $linkRelations
* @param string $columnValue column value
* @param array $rowInfo information about row
* @phpstan-param array{
* 'link_param': string,
* 'link_dependancy_params'?: array<
* int,
* array{'param_info': string, 'column_name': string}
* >,
* 'default_page': string
* } $linkRelations
*
* @return string generated link
*/
private function getSpecialLinkUrl(
array $linkRelations,
$columnValue,
array $rowInfo
) {
$linkingUrlParams = [];
$linkingUrlParams[$linkRelations['link_param']] = $columnValue;
$divider = strpos($linkRelations['default_page'], '?') ? '&' : '?';
if (empty($linkRelations['link_dependancy_params'])) {
return $linkRelations['default_page']
. Url::getCommonRaw($linkingUrlParams, $divider);
}
foreach ($linkRelations['link_dependancy_params'] as $new_param) {
$columnName = mb_strtolower($new_param['column_name']);
// If there is a value for this column name in the rowInfo provided
if (isset($rowInfo[$columnName])) {
$linkingUrlParams[$new_param['param_info']] = $rowInfo[$columnName];
}
// Special case 1 - when executing routines, according
// to the type of the routine, url param changes
if (empty($rowInfo['routine_type'])) {
continue;
}
}
return $linkRelations['default_page']
. Url::getCommonRaw($linkingUrlParams, $divider);
}
/**
* Prepare row information for display special links
*
* @param array $row current row data
* @param array|bool $colOrder the column order
*
* @return array<string, mixed> associative array with column nama -> value
*/
private function getRowInfoForSpecialLinks(array $row, $colOrder): array
{
$rowInfo = [];
$fieldsMeta = $this->properties['fields_meta'];
for ($n = 0; $n < $this->properties['fields_cnt']; ++$n) {
$m = is_array($colOrder) ? $colOrder[$n] : $n;
$rowInfo[mb_strtolower($fieldsMeta[$m]->orgname)] = $row[$m];
}
return $rowInfo;
}
/**
* Get url sql query without conditions to shorten URLs
*
* @see getTableBody()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return string analyzed sql query
*/
private function getUrlSqlQuery(array $analyzedSqlResults)
{
if (($analyzedSqlResults['querytype'] !== 'SELECT') || (mb_strlen($this->properties['sql_query']) < 200)) {
return $this->properties['sql_query'];
}
$query = 'SELECT ' . Query::getClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'SELECT'
);
$fromClause = Query::getClause($analyzedSqlResults['statement'], $analyzedSqlResults['parser']->list, 'FROM');
if ($fromClause !== '') {
$query .= ' FROM ' . $fromClause;
}
return $query;
}
/**
* Get column order and column visibility
*
* @see getTableBody()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return mixed[] 2 element array - $col_order, $col_visib
*/
private function getColumnParams(array $analyzedSqlResults): array
{
if ($this->isSelect($analyzedSqlResults)) {
$pmatable = new Table($this->properties['table'], $this->properties['db']);
$colOrder = $pmatable->getUiProp(Table::PROP_COLUMN_ORDER);
$fieldsCount = $this->properties['fields_cnt'];
/* Validate the value */
if (is_array($colOrder)) {
foreach ($colOrder as $value) {
if ($value < $fieldsCount) {
continue;
}
$pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
break;
}
if ($fieldsCount !== count($colOrder)) {
$pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
$colOrder = false;
}
}
$colVisib = $pmatable->getUiProp(Table::PROP_COLUMN_VISIB);
if (is_array($colVisib) && $fieldsCount !== count($colVisib)) {
$pmatable->removeUiProp(Table::PROP_COLUMN_VISIB);
$colVisib = false;
}
} else {
$colOrder = false;
$colVisib = false;
}
return [
$colOrder,
$colVisib,
];
}
/**
* Get HTML for repeating headers
*
* @see getTableBody()
*
* @param int $numEmptyColumnsBefore The number of blank columns before this one
* @param string[] $descriptions A list of descriptions
* @param int $numEmptyColumnsAfter The number of blank columns after this one
*
* @return string html content
*/
private function getRepeatingHeaders(
int $numEmptyColumnsBefore,
array $descriptions,
int $numEmptyColumnsAfter
): string {
$headerHtml = '<tr>' . "\n";
if ($numEmptyColumnsBefore > 0) {
$headerHtml .= ' <th colspan="'
. $numEmptyColumnsBefore . '">'
. "\n" . ' </th>' . "\n";
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
$headerHtml .= ' <th></th>' . "\n";
}
$headerHtml .= implode($descriptions);
if ($numEmptyColumnsAfter > 0) {
$headerHtml .= ' <th colspan="' . $numEmptyColumnsAfter
. '">'
. "\n" . ' </th>' . "\n";
}
$headerHtml .= '</tr>' . "\n";
return $headerHtml;
}
/**
* Get modified links
*
* @see getTableBody()
*
* @param string $whereClause the where clause of the sql
* @param bool $clauseIsUnique the unique condition of clause
* @param string $urlSqlQuery the analyzed sql query
*
* @return array<int,string|array<string, bool|string>>
*/
private function getModifiedLinks(
$whereClause,
$clauseIsUnique,
$urlSqlQuery
) {
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'where_clause' => $whereClause,
'clause_is_unique' => $clauseIsUnique,
'sql_query' => $urlSqlQuery,
'goto' => Url::getFromRoute('/sql'),
];
$editUrl = Url::getFromRoute('/table/change');
$copyUrl = Url::getFromRoute('/table/change');
$editStr = $this->getActionLinkContent(
'b_edit',
__('Edit')
);
$copyStr = $this->getActionLinkContent(
'b_insrow',
__('Copy')
);
return [
$editUrl,
$copyUrl,
$editStr,
$copyStr,
$urlParams,
];
}
/**
* Get delete and kill links
*
* @see getTableBody()
*
* @param string $whereClause the where clause of the sql
* @param bool $clauseIsUnique the unique condition of clause
* @param string $urlSqlQuery the analyzed sql query
* @param string $deleteLink the delete link of current row
* @param int $processId Process ID
*
* @return array $del_url, $del_str, $js_conf
* @psalm-return array{?string, ?string, ?string}
*/
private function getDeleteAndKillLinks(
$whereClause,
$clauseIsUnique,
$urlSqlQuery,
$deleteLink,
int $processId
) {
$goto = $this->properties['goto'];
if ($deleteLink === self::DELETE_ROW) { // delete row case
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $urlSqlQuery,
'message_to_show' => __('The row has been deleted.'),
'goto' => $goto ?: Url::getFromRoute('/table/sql'),
];
$linkGoto = Url::getFromRoute('/sql', $urlParams);
$deleteQuery = 'DELETE FROM '
. Util::backquote($this->properties['table'])
. ' WHERE ' . $whereClause .
($clauseIsUnique ? '' : ' LIMIT 1');
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $deleteQuery,
'message_to_show' => __('The row has been deleted.'),
'goto' => $linkGoto,
];
$deleteUrl = Url::getFromRoute('/sql');
$jsConf = 'DELETE FROM ' . $this->properties['table']
. ' WHERE ' . $whereClause
. ($clauseIsUnique ? '' : ' LIMIT 1');
$deleteString = $this->getActionLinkContent('b_drop', __('Delete'));
} elseif ($deleteLink === self::KILL_PROCESS) { // kill process case
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $urlSqlQuery,
'goto' => Url::getFromRoute('/'),
];
$linkGoto = Url::getFromRoute('/sql', $urlParams);
$kill = $this->dbi->getKillQuery($processId);
$urlParams = [
'db' => 'mysql',
'sql_query' => $kill,
'goto' => $linkGoto,
];
$deleteUrl = Url::getFromRoute('/sql');
$jsConf = $kill;
$deleteString = Generator::getIcon(
'b_drop',
__('Kill')
);
} else {
$deleteUrl = $deleteString = $jsConf = $urlParams = null;
}
return [
$deleteUrl,
$deleteString,
$jsConf,
$urlParams,
];
}
/**
* Get content inside the table row action links (Edit/Copy/Delete)
*
* @see getModifiedLinks(), getDeleteAndKillLinks()
*
* @param string $icon The name of the file to get
* @param string $displayText The text displaying after the image icon
*
* @return string
*/
private function getActionLinkContent($icon, $displayText)
{
if (
isset($GLOBALS['cfg']['RowActionType'])
&& $GLOBALS['cfg']['RowActionType'] === self::ACTION_LINK_CONTENT_ICONS
) {
return '<span class="text-nowrap">'
. Generator::getImage($icon, $displayText)
. '</span>';
}
if (
isset($GLOBALS['cfg']['RowActionType'])
&& $GLOBALS['cfg']['RowActionType'] === self::ACTION_LINK_CONTENT_TEXT
) {
return '<span class="text-nowrap">' . $displayText . '</span>';
}
return Generator::getIcon($icon, $displayText);
}
/**
* Get class for datetime related fields
*
* @see getTableBody()
*
* @param FieldMetadata $meta the type of the column field
*
* @return string the class for the column
*/
private function getClassForDateTimeRelatedFields(FieldMetadata $meta): string
{
$fieldTypeClass = '';
if ($meta->isMappedTypeTimestamp || $meta->isType(FieldMetadata::TYPE_DATETIME)) {
$fieldTypeClass = 'datetimefield';
} elseif ($meta->isType(FieldMetadata::TYPE_DATE)) {
$fieldTypeClass = 'datefield';
} elseif ($meta->isType(FieldMetadata::TYPE_TIME)) {
$fieldTypeClass = 'timefield';
} elseif ($meta->isType(FieldMetadata::TYPE_STRING)) {
$fieldTypeClass = 'text';
}
return $fieldTypeClass;
}
/**
* Prepare data cell for numeric type fields
*
* @see getTableBody()
*
* @param string|null $column the column's value
* @param string $class the html class for column
* @param bool $conditionField the column should highlighted or not
* @param FieldMetadata $meta the meta-information about this field
* @param array<string, string[]> $map the list of relations
* @param array $analyzedSqlResults the analyzed query
* @param array $transformOptions the transformation parameters
*
* @return string the prepared cell, html content
*/
private function getDataCellForNumericColumns(
?string $column,
string $class,
bool $conditionField,
FieldMetadata $meta,
array $map,
array $analyzedSqlResults,
?TransformationsPlugin $transformationPlugin,
array $transformOptions
) {
if ($column === null) {
return $this->buildNullDisplay($class, $conditionField, $meta);
}
if ($column === '') {
return $this->buildEmptyDisplay($class, $conditionField, $meta);
}
$whereComparison = ' = ' . $column;
return $this->getRowData(
$class,
$conditionField,
$analyzedSqlResults,
$meta,
$map,
$column,
$column,
$transformationPlugin,
'text-nowrap',
$whereComparison,
$transformOptions
);
}
/**
* Get data cell for geometry type fields
*
* @see getTableBody()
*
* @param string|null $column the relevant column in data row
* @param string $class the html class for column
* @param FieldMetadata $meta the meta-information about this field
* @param array<string, string[]> $map the list of relations
* @param array $urlParams the parameters for generate url
* @param bool $conditionField the column should highlighted or not
* @param array $transformOptions the transformation parameters
* @param array $analyzedSqlResults the analyzed query
*
* @return string the prepared data cell, html content
*/
private function getDataCellForGeometryColumns(
?string $column,
string $class,
FieldMetadata $meta,
array $map,
array $urlParams,
bool $conditionField,
?TransformationsPlugin $transformationPlugin,
$transformOptions,
array $analyzedSqlResults
) {
if ($column === null) {
return $this->buildNullDisplay($class, $conditionField, $meta);
}
if ($column === '') {
return $this->buildEmptyDisplay($class, $conditionField, $meta);
}
// Display as [GEOMETRY - (size)]
if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM) {
$geometryText = $this->handleNonPrintableContents(
'GEOMETRY',
$column,
$transformationPlugin,
$transformOptions,
$meta,
$urlParams
);
return $this->buildValueDisplay($class, $conditionField, $geometryText);
}
if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_WKT) {
// Prepare in Well Known Text(WKT) format.
$whereComparison = ' = ' . $column;
// Convert to WKT format
$wktval = Gis::convertToWellKnownText($column);
[
$isFieldTruncated,
$displayedColumn,
// skip 3rd param
] = $this->getPartialText($wktval);
return $this->getRowData(
$class,
$conditionField,
$analyzedSqlResults,
$meta,
$map,
$wktval,
$displayedColumn,
$transformationPlugin,
'',
$whereComparison,
$transformOptions,
$isFieldTruncated
);
}
// Prepare in Well Known Binary (WKB) format.
if ($_SESSION['tmpval']['display_binary']) {
$whereComparison = ' = ' . $column;
$wkbval = substr(bin2hex($column), 8);
[
$isFieldTruncated,
$displayedColumn,
// skip 3rd param
] = $this->getPartialText($wkbval);
return $this->getRowData(
$class,
$conditionField,
$analyzedSqlResults,
$meta,
$map,
$wkbval,
$displayedColumn,
$transformationPlugin,
'',
$whereComparison,
$transformOptions,
$isFieldTruncated
);
}
$wkbval = $this->handleNonPrintableContents(
'BINARY',
$column,
$transformationPlugin,
$transformOptions,
$meta,
$urlParams
);
return $this->buildValueDisplay($class, $conditionField, $wkbval);
}
/**
* Get data cell for non numeric type fields
*
* @see getTableBody()
*
* @param string|null $column the relevant column in data row
* @param string $class the html class for column
* @param FieldMetadata $meta the meta-information about the field
* @param array<string, string[]> $map the list of relations
* @param array $urlParams the parameters for generate url
* @param bool $conditionField the column should highlighted or not
* @param array $transformOptions the transformation parameters
* @param array $analyzedSqlResults the analyzed query
*
* @return string the prepared data cell, html content
*/
private function getDataCellForNonNumericColumns(
?string $column,
string $class,
FieldMetadata $meta,
array $map,
array $urlParams,
bool $conditionField,
?TransformationsPlugin $transformationPlugin,
$transformOptions,
array $analyzedSqlResults
) {
$originalLength = 0;
$isAnalyse = $this->properties['is_analyse'];
$bIsText = $transformationPlugin !== null && ! str_contains($transformationPlugin->getMIMEType(), 'Text');
// disable inline grid editing
// if binary fields are protected
// or transformation plugin is of non text type
// such as image
$isTypeBlob = $meta->isType(FieldMetadata::TYPE_BLOB);
$cfgProtectBinary = $GLOBALS['cfg']['ProtectBinary'];
if (
($meta->isBinary()
&& (
$cfgProtectBinary === 'all'
|| ($cfgProtectBinary === 'noblob' && ! $isTypeBlob)
|| ($cfgProtectBinary === 'blob' && $isTypeBlob)
)
) || $bIsText
) {
$class = str_replace('grid_edit', '', $class);
}
if ($column === null) {
return $this->buildNullDisplay($class, $conditionField, $meta);
}
if ($column === '') {
return $this->buildEmptyDisplay($class, $conditionField, $meta);
}
// Cut all fields to $GLOBALS['cfg']['LimitChars']
// (unless it's a link-type transformation or binary)
$originalDataForWhereClause = $column;
$displayedColumn = $column;
$isFieldTruncated = false;
if (
! ($transformationPlugin !== null
&& str_contains($transformationPlugin->getName(), 'Link'))
&& ! $meta->isBinary()
) {
[
$isFieldTruncated,
$column,
$originalLength,
] = $this->getPartialText($column);
}
if ($meta->isMappedTypeBit) {
$displayedColumn = Util::printableBitValue((int) $displayedColumn, (int) $meta->length);
// some results of PROCEDURE ANALYSE() are reported as
// being BINARY but they are quite readable,
// so don't treat them as BINARY
} elseif ($meta->isBinary() && $isAnalyse !== true) {
// we show the BINARY or BLOB message and field's size
// (or maybe use a transformation)
$binaryOrBlob = 'BLOB';
if ($meta->isType(FieldMetadata::TYPE_STRING)) {
$binaryOrBlob = 'BINARY';
}
$displayedColumn = $this->handleNonPrintableContents(
$binaryOrBlob,
$displayedColumn,
$transformationPlugin,
$transformOptions,
$meta,
$urlParams,
$isFieldTruncated
);
$class = $this->addClass(
$class,
$conditionField,
$meta,
'',
$isFieldTruncated,
$transformationPlugin !== null
);
$result = strip_tags($column);
// disable inline grid editing
// if binary or blob data is not shown
if (stripos($result, $binaryOrBlob) !== false) {
$class = str_replace('grid_edit', '', $class);
}
return $this->buildValueDisplay($class, $conditionField, $displayedColumn);
}
// transform functions may enable no-wrapping:
$boolNoWrap = $transformationPlugin !== null
&& $transformationPlugin->applyTransformationNoWrap($transformOptions);
// do not wrap if date field type or if no-wrapping enabled by transform functions
// otherwise, preserve whitespaces and wrap
$nowrap = $meta->isDateTimeType() || $boolNoWrap ? 'text-nowrap' : 'pre_wrap';
$whereComparison = ' = \''
. $this->dbi->escapeString($originalDataForWhereClause)
. '\'';
return $this->getRowData(
$class,
$conditionField,
$analyzedSqlResults,
$meta,
$map,
$column,
$displayedColumn,
$transformationPlugin,
$nowrap,
$whereComparison,
$transformOptions,
$isFieldTruncated,
(string) $originalLength
);
}
/**
* Checks the posted options for viewing query results
* and sets appropriate values in the session.
*
* @param array $analyzedSqlResults the analyzed query results
*
* @todo make maximum remembered queries configurable
* @todo move/split into SQL class!?
* @todo currently this is called twice unnecessary
* @todo ignore LIMIT and ORDER in query!?
*/
public function setConfigParamsForDisplayTable(array $analyzedSqlResults): void
{
$sqlMd5 = md5($this->properties['server'] . $this->properties['db'] . $this->properties['sql_query']);
$query = [];
if (isset($_SESSION['tmpval']['query'][$sqlMd5])) {
$query = $_SESSION['tmpval']['query'][$sqlMd5];
}
$query['sql'] = $this->properties['sql_query'];
if (empty($query['repeat_cells'])) {
$query['repeat_cells'] = $GLOBALS['cfg']['RepeatCells'];
}
// The value can also be from _GET as described on issue #16146 when sorting results
$sessionMaxRows = $_GET['session_max_rows'] ?? $_POST['session_max_rows'] ?? '';
if (isset($sessionMaxRows) && is_numeric($sessionMaxRows)) {
$query['max_rows'] = (int) $sessionMaxRows;
unset($_GET['session_max_rows'], $_POST['session_max_rows']);
} elseif ($sessionMaxRows === self::ALL_ROWS) {
$query['max_rows'] = self::ALL_ROWS;
unset($_GET['session_max_rows'], $_POST['session_max_rows']);
} elseif (empty($query['max_rows'])) {
$query['max_rows'] = intval($GLOBALS['cfg']['MaxRows']);
}
if (isset($_REQUEST['pos']) && is_numeric($_REQUEST['pos'])) {
$query['pos'] = (int) $_REQUEST['pos'];
unset($_REQUEST['pos']);
} elseif (empty($query['pos'])) {
$query['pos'] = 0;
}
// Full text is needed in case of explain statements, if not specified.
$fullText = $analyzedSqlResults['is_explain'];
if (
isset($_REQUEST['pftext']) && in_array(
$_REQUEST['pftext'],
[self::DISPLAY_PARTIAL_TEXT, self::DISPLAY_FULL_TEXT]
)
) {
$query['pftext'] = $_REQUEST['pftext'];
unset($_REQUEST['pftext']);
} elseif ($fullText) {
$query['pftext'] = self::DISPLAY_FULL_TEXT;
} elseif (empty($query['pftext'])) {
$query['pftext'] = self::DISPLAY_PARTIAL_TEXT;
}
if (
isset($_REQUEST['relational_display']) && in_array(
$_REQUEST['relational_display'],
[self::RELATIONAL_KEY, self::RELATIONAL_DISPLAY_COLUMN]
)
) {
$query['relational_display'] = $_REQUEST['relational_display'];
unset($_REQUEST['relational_display']);
} elseif (empty($query['relational_display'])) {
// The current session value has priority over a
// change via Settings; this change will be apparent
// starting from the next session
$query['relational_display'] = $GLOBALS['cfg']['RelationalDisplay'];
}
if (
isset($_REQUEST['geoOption']) && in_array(
$_REQUEST['geoOption'],
[self::GEOMETRY_DISP_WKT, self::GEOMETRY_DISP_WKB, self::GEOMETRY_DISP_GEOM]
)
) {
$query['geoOption'] = $_REQUEST['geoOption'];
unset($_REQUEST['geoOption']);
} elseif (empty($query['geoOption'])) {
$query['geoOption'] = self::GEOMETRY_DISP_GEOM;
}
if (isset($_REQUEST['display_binary'])) {
$query['display_binary'] = true;
unset($_REQUEST['display_binary']);
} elseif (isset($_REQUEST['display_options_form'])) {
// we know that the checkbox was unchecked
unset($query['display_binary']);
} elseif (! isset($_REQUEST['full_text_button'])) {
// selected by default because some operations like OPTIMIZE TABLE
// and all queries involving functions return "binary" contents,
// according to low-level field flags
$query['display_binary'] = true;
}
if (isset($_REQUEST['display_blob'])) {
$query['display_blob'] = true;
unset($_REQUEST['display_blob']);
} elseif (isset($_REQUEST['display_options_form'])) {
// we know that the checkbox was unchecked
unset($query['display_blob']);
}
if (isset($_REQUEST['hide_transformation'])) {
$query['hide_transformation'] = true;
unset($_REQUEST['hide_transformation']);
} elseif (isset($_REQUEST['display_options_form'])) {
// we know that the checkbox was unchecked
unset($query['hide_transformation']);
}
// move current query to the last position, to be removed last
// so only least executed query will be removed if maximum remembered
// queries limit is reached
unset($_SESSION['tmpval']['query'][$sqlMd5]);
$_SESSION['tmpval']['query'][$sqlMd5] = $query;
// do not exceed a maximum number of queries to remember
if (count($_SESSION['tmpval']['query']) > 10) {
array_shift($_SESSION['tmpval']['query']);
//echo 'deleting one element ...';
}
// populate query configuration
$_SESSION['tmpval']['pftext'] = $query['pftext'];
$_SESSION['tmpval']['relational_display'] = $query['relational_display'];
$_SESSION['tmpval']['geoOption'] = $query['geoOption'];
$_SESSION['tmpval']['display_binary'] = isset($query['display_binary']);
$_SESSION['tmpval']['display_blob'] = isset($query['display_blob']);
$_SESSION['tmpval']['hide_transformation'] = isset($query['hide_transformation']);
$_SESSION['tmpval']['pos'] = $query['pos'];
$_SESSION['tmpval']['max_rows'] = $query['max_rows'];
$_SESSION['tmpval']['repeat_cells'] = $query['repeat_cells'];
}
/**
* Prepare a table of results returned by a SQL query.
*
* @param ResultInterface $dtResult the link id associated to the query
* which results have to be displayed
* @param array $displayParts the parts to display
* @param array $analyzedSqlResults analyzed sql results
* @param bool $isLimitedDisplay With limited operations or not
*
* @return string Generated HTML content for resulted table
*/
public function getTable(
ResultInterface $dtResult,
array &$displayParts,
array $analyzedSqlResults,
$isLimitedDisplay = false
) {
// The statement this table is built for.
if (isset($analyzedSqlResults['statement'])) {
/** @var SelectStatement $statement */
$statement = $analyzedSqlResults['statement'];
} else {
$statement = null;
}
// Following variable are needed for use in isset/empty or
// use with array indexes/safe use in foreach
$fieldsMeta = $this->properties['fields_meta'];
$showTable = $this->properties['showtable'];
$printView = $this->properties['printview'];
/**
* @todo move this to a central place
* @todo for other future table types
*/
$isInnodb = (isset($showTable['Type'])
&& $showTable['Type'] === self::TABLE_TYPE_INNO_DB);
if ($isInnodb && Sql::isJustBrowsing($analyzedSqlResults, true)) {
$preCount = '~';
$afterCount = Generator::showHint(
Sanitize::sanitizeMessage(
__('May be approximate. See [doc@faq3-11]FAQ 3.11[/doc].')
)
);
} else {
$preCount = '';
$afterCount = '';
}
// 1. ----- Prepares the work -----
// 1.1 Gets the information about which functionalities should be
// displayed
[
$displayParts,
$total,
] = $this->setDisplayPartsAndTotal($displayParts);
// 1.2 Defines offsets for the next and previous pages
$posNext = 0;
$posPrev = 0;
if ($displayParts['nav_bar'] == '1') {
[$posNext, $posPrev] = $this->getOffsets();
}
// 1.3 Extract sorting expressions.
// we need $sort_expression and $sort_expression_nodirection
// even if there are many table references
$sortExpression = [];
$sortExpressionNoDirection = [];
$sortDirection = [];
if ($statement !== null && ! empty($statement->order)) {
foreach ($statement->order as $o) {
$sortExpression[] = $o->expr->expr . ' ' . $o->type;
$sortExpressionNoDirection[] = $o->expr->expr;
$sortDirection[] = $o->type;
}
} else {
$sortExpression[] = '';
$sortExpressionNoDirection[] = '';
$sortDirection[] = '';
}
// 1.4 Prepares display of first and last value of the sorted column
$sortedColumnMessage = '';
foreach ($sortExpressionNoDirection as $expression) {
$sortedColumnMessage .= $this->getSortedColumnMessage($dtResult, $expression);
}
// 2. ----- Prepare to display the top of the page -----
// 2.1 Prepares a messages with position information
$sqlQueryMessage = '';
if ($displayParts['nav_bar'] == '1') {
$message = $this->setMessageInformation(
$sortedColumnMessage,
$analyzedSqlResults,
$total,
$posNext,
$preCount,
$afterCount
);
$sqlQueryMessage = Generator::getMessage($message, $this->properties['sql_query'], 'success');
} elseif (($printView === null || $printView != '1') && ! $isLimitedDisplay) {
$sqlQueryMessage = Generator::getMessage(
__('Your SQL query has been executed successfully.'),
$this->properties['sql_query'],
'success'
);
}
// 2.3 Prepare the navigation bars
if ($this->properties['table'] === '' && $analyzedSqlResults['querytype'] === 'SELECT') {
// table does not always contain a real table name,
// for example in MySQL 5.0.x, the query SHOW STATUS
// returns STATUS as a table name
$this->properties['table'] = $fieldsMeta[0]->table;
}
$unsortedSqlQuery = '';
$sortByKeyData = [];
// can the result be sorted?
if ($displayParts['sort_lnk'] == '1' && isset($analyzedSqlResults['statement'])) {
$unsortedSqlQuery = Query::replaceClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'ORDER BY',
''
);
// Data is sorted by indexes only if there is only one table.
if ($this->isSelect($analyzedSqlResults)) {
$sortByKeyData = $this->getSortByKeyDropDown(
$sortExpression,
$unsortedSqlQuery
);
}
}
$navigation = [];
if ($displayParts['nav_bar'] == '1' && $statement !== null && empty($statement->limit)) {
$navigation = $this->getTableNavigation($posNext, $posPrev, $isInnodb, $sortByKeyData);
}
// 2b ----- Get field references from Database -----
// (see the 'relation' configuration variable)
// initialize map
$map = [];
if ($this->properties['table'] !== '') {
// This method set the values for $map array
$map = $this->setParamForLinkForeignKeyRelatedTables($map);
// Coming from 'Distinct values' action of structure page
// We manipulate relations mechanism to show a link to related rows.
if ($this->properties['is_browse_distinct']) {
$map[$fieldsMeta[1]->name] = [
$this->properties['table'],
$fieldsMeta[1]->name,
'',
$this->properties['db'],
];
}
}
// end 2b
// 3. ----- Prepare the results table -----
$headers = $this->getTableHeaders(
$displayParts,
$analyzedSqlResults,
$unsortedSqlQuery,
$sortExpression,
$sortExpressionNoDirection,
$sortDirection,
$isLimitedDisplay
);
$body = $this->getTableBody($dtResult, $displayParts, $map, $analyzedSqlResults, $isLimitedDisplay);
$this->properties['display_params'] = null;
// 4. ----- Prepares the link for multi-fields edit and delete
$bulkLinks = $this->getBulkLinks($dtResult, $analyzedSqlResults, $displayParts['del_lnk']);
// 5. ----- Prepare "Query results operations"
$operations = [];
if (($printView === null || $printView != '1') && ! $isLimitedDisplay) {
$operations = $this->getResultsOperations($displayParts['pview_lnk'], $analyzedSqlResults);
}
$relationParameters = $this->relation->getRelationParameters();
return $this->template->render('display/results/table', [
'sql_query_message' => $sqlQueryMessage,
'navigation' => $navigation,
'headers' => $headers,
'body' => $body,
'bulk_links' => $bulkLinks,
'operations' => $operations,
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'unique_id' => $this->properties['unique_id'],
'sql_query' => $this->properties['sql_query'],
'goto' => $this->properties['goto'],
'unlim_num_rows' => $this->properties['unlim_num_rows'],
'displaywork' => $relationParameters->displayFeature !== null,
'relwork' => $relationParameters->relationFeature !== null,
'save_cells_at_once' => $GLOBALS['cfg']['SaveCellsAtOnce'],
'default_sliders_state' => $GLOBALS['cfg']['InitialSlidersState'],
'text_dir' => $this->properties['text_dir'],
]);
}
/**
* Get offsets for next page and previous page
*
* @see getTable()
*
* @return int[] array with two elements - $pos_next, $pos_prev
*/
private function getOffsets()
{
if ($_SESSION['tmpval']['max_rows'] === self::ALL_ROWS) {
return [0, 0];
}
return [
$_SESSION['tmpval']['pos'] + $_SESSION['tmpval']['max_rows'],
max(0, $_SESSION['tmpval']['pos'] - $_SESSION['tmpval']['max_rows']),
];
}
/**
* Prepare sorted column message
*
* @see getTable()
*
* @param ResultInterface $dtResult the link id associated to the query
* which results have to be displayed
* @param string|null $sortExpressionNoDirection sort expression without direction
*
* @return string
*/
private function getSortedColumnMessage(
ResultInterface $dtResult,
$sortExpressionNoDirection
) {
$fieldsMeta = $this->properties['fields_meta']; // To use array indexes
if (empty($sortExpressionNoDirection)) {
return '';
}
if (! str_contains($sortExpressionNoDirection, '.')) {
$sortTable = $this->properties['table'];
$sortColumn = $sortExpressionNoDirection;
} else {
[$sortTable, $sortColumn] = explode('.', $sortExpressionNoDirection);
}
$sortTable = Util::unQuote($sortTable);
$sortColumn = Util::unQuote($sortColumn);
// find the sorted column index in row result
// (this might be a multi-table query)
$sortedColumnIndex = false;
foreach ($fieldsMeta as $key => $meta) {
if (($meta->table == $sortTable) && ($meta->name == $sortColumn)) {
$sortedColumnIndex = $key;
break;
}
}
if ($sortedColumnIndex === false) {
return '';
}
// fetch first row of the result set
$row = $dtResult->fetchRow();
// check for non printable sorted row data
$meta = $fieldsMeta[$sortedColumnIndex];
$isBlobOrGeometryOrBinary = $meta->isType(FieldMetadata::TYPE_BLOB)
|| $meta->isMappedTypeGeometry || $meta->isBinary;
if ($isBlobOrGeometryOrBinary) {
$columnForFirstRow = $this->handleNonPrintableContents(
$meta->getMappedType(),
$row ? $row[$sortedColumnIndex] : '',
null,
[],
$meta
);
} else {
$columnForFirstRow = $row !== [] ? $row[$sortedColumnIndex] : '';
}
$columnForFirstRow = mb_strtoupper(
mb_substr(
(string) $columnForFirstRow,
0,
(int) $GLOBALS['cfg']['LimitChars']
) . '...'
);
// fetch last row of the result set
$dtResult->seek($this->properties['num_rows'] > 0 ? $this->properties['num_rows'] - 1 : 0);
$row = $dtResult->fetchRow();
// check for non printable sorted row data
$meta = $fieldsMeta[$sortedColumnIndex];
if ($isBlobOrGeometryOrBinary) {
$columnForLastRow = $this->handleNonPrintableContents(
$meta->getMappedType(),
$row ? $row[$sortedColumnIndex] : '',
null,
[],
$meta
);
} else {
$columnForLastRow = $row !== [] ? $row[$sortedColumnIndex] : '';
}
$columnForLastRow = mb_strtoupper(
mb_substr(
(string) $columnForLastRow,
0,
(int) $GLOBALS['cfg']['LimitChars']
) . '...'
);
// reset to first row for the loop in getTableBody()
$dtResult->seek(0);
// we could also use here $sort_expression_nodirection
return ' [' . htmlspecialchars($sortColumn)
. ': <strong>' . htmlspecialchars($columnForFirstRow) . ' - '
. htmlspecialchars($columnForLastRow) . '</strong>]';
}
/**
* Set the content that needs to be shown in message
*
* @see getTable()
*
* @param string $sortedColumnMessage the message for sorted column
* @param array $analyzedSqlResults the analyzed query
* @param int $total the total number of rows returned by
* the SQL query without any
* programmatically appended LIMIT clause
* @param int $posNext the offset for next page
* @param string $preCount the string renders before row count
* @param string $afterCount the string renders after row count
*
* @return Message an object of Message
*/
private function setMessageInformation(
string $sortedColumnMessage,
array $analyzedSqlResults,
$total,
$posNext,
string $preCount,
string $afterCount
) {
$unlimNumRows = $this->properties['unlim_num_rows']; // To use in isset()
if (! empty($analyzedSqlResults['statement']->limit)) {
$firstShownRec = $analyzedSqlResults['statement']->limit->offset;
$rowCount = $analyzedSqlResults['statement']->limit->rowCount;
if ($rowCount < $total) {
$lastShownRec = $firstShownRec + $rowCount - 1;
} else {
$lastShownRec = $firstShownRec + $total - 1;
}
} elseif (($_SESSION['tmpval']['max_rows'] === self::ALL_ROWS) || ($posNext > $total)) {
$firstShownRec = $_SESSION['tmpval']['pos'];
$lastShownRec = $total - 1;
} else {
$firstShownRec = $_SESSION['tmpval']['pos'];
$lastShownRec = $posNext - 1;
}
$messageViewWarning = false;
$table = new Table($this->properties['table'], $this->properties['db']);
if ($table->isView() && ($total == $GLOBALS['cfg']['MaxExactCountViews'])) {
$message = Message::notice(
__(
'This view has at least this number of rows. Please refer to %sdocumentation%s.'
)
);
$message->addParam('[doc@cfg_MaxExactCount]');
$message->addParam('[/doc]');
$messageViewWarning = Generator::showHint($message->getMessage());
}
$message = Message::success(__('Showing rows %1s - %2s'));
$message->addParam($firstShownRec);
if ($messageViewWarning !== false) {
$message->addParamHtml('... ' . $messageViewWarning);
} else {
$message->addParam($lastShownRec);
}
$message->addText('(');
if ($messageViewWarning === false) {
if ($unlimNumRows != $total) {
$messageTotal = Message::notice(
$preCount . __('%1$d total, %2$d in query')
);
$messageTotal->addParam($total);
$messageTotal->addParam($unlimNumRows);
} else {
$messageTotal = Message::notice($preCount . __('%d total'));
$messageTotal->addParam($total);
}
if ($afterCount !== '') {
$messageTotal->addHtml($afterCount);
}
$message->addMessage($messageTotal, '');
$message->addText(', ', '');
}
$messageQueryTime = Message::notice(__('Query took %01.4f seconds.') . ')');
$messageQueryTime->addParam($this->properties['querytime']);
$message->addMessage($messageQueryTime, '');
$message->addHtml($sortedColumnMessage, '');
return $message;
}
/**
* Set the value of $map array for linking foreign key related tables
*
* @see getTable()
*
* @param array<string, string[]> $map the list of relations
*
* @return array<string, string[]>
*/
private function setParamForLinkForeignKeyRelatedTables(array $map): array
{
// To be able to later display a link to the related table,
// we verify both types of relations: either those that are
// native foreign keys or those defined in the phpMyAdmin
// configuration storage. If no PMA storage, we won't be able
// to use the "column to display" notion (for example show
// the name related to a numeric id).
$existRel = $this->relation->getForeigners(
$this->properties['db'],
$this->properties['table'],
'',
self::POSITION_BOTH
);
if ($existRel === []) {
return $map;
}
foreach ($existRel as $masterField => $rel) {
if ($masterField !== 'foreign_keys_data') {
$displayField = $this->relation->getDisplayField($rel['foreign_db'], $rel['foreign_table']);
$map[$masterField] = [
$rel['foreign_table'],
$rel['foreign_field'],
$displayField,
$rel['foreign_db'],
];
} else {
foreach ($rel as $oneKey) {
foreach ($oneKey['index_list'] as $index => $oneField) {
$displayField = $this->relation->getDisplayField(
$oneKey['ref_db_name'] ?? $GLOBALS['db'],
$oneKey['ref_table_name']
);
$map[$oneField] = [
$oneKey['ref_table_name'],
$oneKey['ref_index_list'][$index],
$displayField,
$oneKey['ref_db_name'] ?? $GLOBALS['db'],
];
}
}
}
}
return $map;
}
/**
* Prepare multi field edit/delete links
*
* @see getTable()
*
* @param ResultInterface $dtResult the link id associated to the query which
* results have to be displayed
* @param array $analyzedSqlResults analyzed sql results
* @param string $deleteLink the display element - 'del_link'
*
* @psalm-return array{has_export_button:bool, clause_is_unique:mixed}|array<empty, empty>
*/
private function getBulkLinks(
ResultInterface $dtResult,
array $analyzedSqlResults,
$deleteLink
): array {
if ($deleteLink !== self::DELETE_ROW) {
return [];
}
// fetch last row of the result set
$dtResult->seek($this->properties['num_rows'] > 0 ? $this->properties['num_rows'] - 1 : 0);
$row = $dtResult->fetchRow();
$expressions = [];
if (isset($analyzedSqlResults['statement']) && $analyzedSqlResults['statement'] instanceof SelectStatement) {
$expressions = $analyzedSqlResults['statement']->expr;
}
/**
* $clause_is_unique is needed by getTable() to generate the proper param
* in the multi-edit and multi-delete form
*/
[, $clauseIsUnique] = Util::getUniqueCondition(
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
false,
$expressions
);
// reset to first row for the loop in getTableBody()
$dtResult->seek(0);
return [
'has_export_button' => $analyzedSqlResults['querytype'] === 'SELECT',
'clause_is_unique' => $clauseIsUnique,
];
}
/**
* Get operations that are available on results.
*
* @see getTable()
*
* @param string $printLink the parts to display
* @param array $analyzedSqlResults analyzed sql results
*
* @psalm-return array{
* has_export_link: bool,
* has_geometry: bool,
* has_print_link: bool,
* has_procedure: bool,
* url_params: array{
* db: string,
* table: string,
* printview: "1",
* sql_query: string,
* single_table?: "true",
* raw_query?: "true",
* unlim_num_rows?: int|numeric-string|false
* }
* }
*/
private function getResultsOperations(
string $printLink,
array $analyzedSqlResults
): array {
$urlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'printview' => '1',
'sql_query' => $this->properties['sql_query'],
];
$geometryFound = false;
// Export link
// (the single_table parameter is used in \PhpMyAdmin\Export->getDisplay()
// to hide the SQL and the structure export dialogs)
// If the parser found a PROCEDURE clause
// (most probably PROCEDURE ANALYSE()) it makes no sense to
// display the Export link).
if (
($analyzedSqlResults['querytype'] === self::QUERY_TYPE_SELECT)
&& empty($analyzedSqlResults['procedure'])
) {
if (count($analyzedSqlResults['select_tables']) === 1) {
$urlParams['single_table'] = 'true';
}
// In case this query doesn't involve any tables,
// implies only raw query is to be exported
if (! $analyzedSqlResults['select_tables']) {
$urlParams['raw_query'] = 'true';
}
$urlParams['unlim_num_rows'] = $this->properties['unlim_num_rows'];
/**
* At this point we don't know the table name; this can happen
* for example with a query like
* SELECT bike_code FROM (SELECT bike_code FROM bikes) tmp
* As a workaround we set in the table parameter the name of the
* first table of this database, so that /table/export and
* the script it calls do not fail
*/
if ($urlParams['table'] === '' && $urlParams['db'] !== '') {
$urlParams['table'] = (string) $this->dbi->fetchValue('SHOW TABLES');
}
$fieldsMeta = $this->properties['fields_meta'];
foreach ($fieldsMeta as $meta) {
if ($meta->isMappedTypeGeometry) {
$geometryFound = true;
break;
}
}
}
return [
'has_procedure' => ! empty($analyzedSqlResults['procedure']),
'has_geometry' => $geometryFound,
'has_print_link' => $printLink == '1',
'has_export_link' => $analyzedSqlResults['querytype'] === self::QUERY_TYPE_SELECT,
'url_params' => $urlParams,
];
}
/**
* Verifies what to do with non-printable contents (binary or BLOB)
* in Browse mode.
*
* @see getDataCellForGeometryColumns(), getDataCellForNonNumericColumns(), getSortedColumnMessage()
*
* @param string $category BLOB|BINARY|GEOMETRY
* @param string|null $content the binary content
* @param array $transformOptions transformation parameters
* @param FieldMetadata $meta the meta-information about the field
* @param array $urlParams parameters that should go to the download link
* @param bool $isTruncated the result is truncated or not
*/
private function handleNonPrintableContents(
$category,
?string $content,
?TransformationsPlugin $transformationPlugin,
array $transformOptions,
FieldMetadata $meta,
array $urlParams = [],
&$isTruncated = false
): string {
$isTruncated = false;
$result = '[' . $category;
if ($content !== null) {
$size = strlen($content);
$displaySize = Util::formatByteDown($size, 3, 1);
if ($displaySize !== null) {
$result .= ' - ' . $displaySize[0] . ' ' . $displaySize[1];
}
} else {
$result .= ' - NULL';
$size = 0;
$content = '';
}
$result .= ']';
// if we want to use a text transformation on a BLOB column
if ($transformationPlugin !== null) {
$posMimeOctetstream = strpos(
$transformationPlugin->getMIMESubtype(),
'Octetstream'
);
$posMimeText = strpos($transformationPlugin->getMIMEType(), 'Text');
if ($posMimeOctetstream || $posMimeText !== false) {
// Applying Transformations on hex string of binary data
// seems more appropriate
$result = pack('H*', bin2hex($content));
}
}
if ($size <= 0) {
return $result;
}
if ($transformationPlugin !== null) {
return $transformationPlugin->applyTransformation($result, $transformOptions, $meta);
}
$result = Core::mimeDefaultFunction($result);
if (
($_SESSION['tmpval']['display_binary']
&& $meta->isType(FieldMetadata::TYPE_STRING))
|| ($_SESSION['tmpval']['display_blob']
&& $meta->isType(FieldMetadata::TYPE_BLOB))
) {
// in this case, restart from the original $content
if (
mb_check_encoding($content, 'utf-8')
&& ! preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\x9F]/u', $content)
) {
// show as text if it's valid utf-8
$result = htmlspecialchars($content);
} else {
$result = '0x' . bin2hex($content);
}
[
$isTruncated,
$result,
// skip 3rd param
] = $this->getPartialText($result);
}
/* Create link to download */
if ($urlParams !== [] && $this->properties['db'] !== '' && $meta->orgtable !== '') {
$urlParams['where_clause_sign'] = Core::signSqlQuery($urlParams['where_clause']);
$result = '<a href="'
. Url::getFromRoute('/table/get-field', $urlParams)
. '" class="disableAjax">'
. $result . '</a>';
}
return $result;
}
/**
* Retrieves the associated foreign key info for a data cell
*
* @param string[] $fieldInfo the relation
* @param string $whereComparison data for the where clause
*
* @return string formatted data
*/
private function getFromForeign(array $fieldInfo, string $whereComparison): ?string
{
$dispsql = 'SELECT '
. Util::backquote($fieldInfo[2])
. ' FROM '
. Util::backquote($fieldInfo[3])
. '.'
. Util::backquote($fieldInfo[0])
. ' WHERE '
. Util::backquote($fieldInfo[1])
. $whereComparison;
$dispval = $this->dbi->fetchValue($dispsql);
if ($dispval === false) {
return __('Link not found!');
}
if ($dispval === null) {
return null;
}
// Truncate values that are too long, see: #17902
[, $dispval] = $this->getPartialText($dispval);
return $dispval;
}
/**
* Prepares the displayable content of a data cell in Browse mode,
* taking into account foreign key description field and transformations
*
* @see getDataCellForNumericColumns(), getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns(),
*
* @param string $class css classes for the td element
* @param bool $conditionField whether the column is a part of the where clause
* @param array $analyzedSqlResults the analyzed query
* @param FieldMetadata $meta the meta-information about the field
* @param array<string, string[]> $map the list of relations
* @param string $data data
* @param string $displayedData data that will be displayed (maybe be chunked)
* @param string $nowrap 'nowrap' if the content should not be wrapped
* @param string $whereComparison data for the where clause
* @param array $transformOptions options for transformation
* @param bool $isFieldTruncated whether the field is truncated
* @param string $originalLength of a truncated column, or ''
*
* @return string formatted data
*/
private function getRowData(
string $class,
bool $conditionField,
array $analyzedSqlResults,
FieldMetadata $meta,
array $map,
$data,
$displayedData,
?TransformationsPlugin $transformationPlugin,
string $nowrap,
string $whereComparison,
array $transformOptions,
bool $isFieldTruncated = false,
string $originalLength = ''
) {
$relationalDisplay = $_SESSION['tmpval']['relational_display'];
$printView = $this->properties['printview'];
$value = '';
$tableDataCellClass = $this->addClass(
$class,
$conditionField,
$meta,
$nowrap,
$isFieldTruncated,
$transformationPlugin !== null
);
if (! empty($analyzedSqlResults['statement']->expr)) {
foreach ($analyzedSqlResults['statement']->expr as $expr) {
if (empty($expr->alias) || empty($expr->column)) {
continue;
}
if (strcasecmp($meta->name, $expr->alias) !== 0) {
continue;
}
$meta->name = $expr->column;
}
}
if (isset($map[$meta->name])) {
/** @var array{0: string, 1: string, 2: string|false, 3: string} $relation */
$relation = $map[$meta->name];
// Field to display from the foreign table?
$dispval = '';
// Check that we have a valid column name
// Relation::getDisplayField() returns false by default
if ($relation[2] !== '' && $relation[2] !== false) {
$dispval = $this->getFromForeign($relation, $whereComparison);
}
if ($printView == '1') {
if ($transformationPlugin !== null) {
$value .= $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
} else {
$value .= Core::mimeDefaultFunction($data);
}
$value .= ' <code>[->' . $dispval . ']</code>';
} else {
$sqlQuery = 'SELECT * FROM '
. Util::backquote($relation[3]) . '.'
. Util::backquote($relation[0])
. ' WHERE '
. Util::backquote($relation[1])
. $whereComparison;
$urlParams = [
'db' => $relation[3],
'table' => $relation[0],
'pos' => '0',
'sql_signature' => Core::signSqlQuery($sqlQuery),
'sql_query' => $sqlQuery,
];
if ($transformationPlugin !== null) {
// always apply a transformation on the real data,
// not on the display field
$displayedData = $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
} elseif ($relationalDisplay === self::RELATIONAL_DISPLAY_COLUMN && $relation[2]) {
// user chose "relational display field" in the
// display options, so show display field in the cell
$displayedData = $dispval === null ? '<em>NULL</em>' : Core::mimeDefaultFunction($dispval);
} else {
// otherwise display data in the cell
$displayedData = Core::mimeDefaultFunction($displayedData);
}
if ($relationalDisplay === self::RELATIONAL_KEY) {
// user chose "relational key" in the display options, so
// the title contains the display field
$title = htmlspecialchars($dispval ?? '');
} else {
$title = htmlspecialchars($data);
}
$tagParams = ['title' => $title];
if (str_contains($class, 'grid_edit')) {
$tagParams['class'] = 'ajax';
}
$value .= Generator::linkOrButton(
Url::getFromRoute('/sql'),
$urlParams,
$displayedData,
$tagParams
);
}
} elseif ($transformationPlugin !== null) {
$value .= $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
} else {
$value .= Core::mimeDefaultFunction($data);
}
return $this->template->render('display/results/row_data', [
'value' => $value,
'td_class' => $tableDataCellClass,
'decimals' => $meta->decimals,
'type' => $meta->getMappedType(),
'original_length' => $originalLength,
]);
}
/**
* Truncates given string based on LimitChars configuration
* and Session pftext variable
* (string is truncated only if necessary)
*
* @see handleNonPrintableContents(), getDataCellForGeometryColumns(), getDataCellForNonNumericColumns
*
* @param string $str string to be truncated
*
* @return array
* @psalm-return array{bool, string, int}
*/
private function getPartialText($str): array
{
$originalLength = mb_strlen($str);
if (
$originalLength > $GLOBALS['cfg']['LimitChars']
&& $_SESSION['tmpval']['pftext'] === self::DISPLAY_PARTIAL_TEXT
) {
$str = mb_substr($str, 0, (int) $GLOBALS['cfg']['LimitChars']) . '...';
$truncated = true;
} else {
$truncated = false;
}
return [
$truncated,
$str,
$originalLength,
];
}
}
|