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
|
<?php
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\ConfigStorage\Features\BookmarkFeature;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\Display\Results as DisplayResults;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Html\MySQLDocumentation;
use PhpMyAdmin\Query\Generator as QueryGenerator;
use PhpMyAdmin\Query\Utilities;
use PhpMyAdmin\SqlParser\Statements\AlterStatement;
use PhpMyAdmin\SqlParser\Statements\DropStatement;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\SqlParser\Utils\Query;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function array_keys;
use function array_map;
use function bin2hex;
use function ceil;
use function count;
use function defined;
use function explode;
use function htmlspecialchars;
use function in_array;
use function is_array;
use function is_bool;
use function is_object;
use function session_start;
use function session_write_close;
use function sprintf;
use function str_contains;
use function str_replace;
use function ucwords;
/**
* Set of functions for the SQL executor
*/
class Sql
{
/** @var DatabaseInterface */
private $dbi;
/** @var Relation */
private $relation;
/** @var RelationCleanup */
private $relationCleanup;
/** @var Transformations */
private $transformations;
/** @var Operations */
private $operations;
/** @var Template */
private $template;
public function __construct(
DatabaseInterface $dbi,
Relation $relation,
RelationCleanup $relationCleanup,
Operations $operations,
Transformations $transformations,
Template $template
) {
$this->dbi = $dbi;
$this->relation = $relation;
$this->relationCleanup = $relationCleanup;
$this->operations = $operations;
$this->transformations = $transformations;
$this->template = $template;
}
/**
* Handle remembered sorting order, only for single table query
*
* @param string $db database name
* @param string $table table name
* @param array $analyzedSqlResults the analyzed query results
* @param string $fullSqlQuery SQL query
*/
private function handleSortOrder(
$db,
$table,
array &$analyzedSqlResults,
&$fullSqlQuery
): void {
$tableObject = new Table($table, $db);
if (empty($analyzedSqlResults['order'])) {
// Retrieving the name of the column we should sort after.
$sortCol = $tableObject->getUiProp(Table::PROP_SORTED_COLUMN);
if (empty($sortCol)) {
return;
}
// Remove the name of the table from the retrieved field name.
$sortCol = str_replace(
Util::backquote($table) . '.',
'',
$sortCol
);
// Create the new query.
$fullSqlQuery = Query::replaceClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'ORDER BY ' . $sortCol
);
// TODO: Avoid reparsing the query.
$analyzedSqlResults = Query::getAll($fullSqlQuery);
} else {
// Store the remembered table into session.
$tableObject->setUiProp(
Table::PROP_SORTED_COLUMN,
Query::getClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'ORDER BY'
)
);
}
}
/**
* Append limit clause to SQL query
*
* @param array $analyzedSqlResults the analyzed query results
*
* @return string limit clause appended SQL query
*/
private function getSqlWithLimitClause(array $analyzedSqlResults)
{
return Query::replaceClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'LIMIT ' . $_SESSION['tmpval']['pos'] . ', '
. $_SESSION['tmpval']['max_rows']
);
}
/**
* Verify whether the result set has columns from just one table
*
* @param array $fieldsMeta meta fields
*/
private function resultSetHasJustOneTable(array $fieldsMeta): bool
{
$justOneTable = true;
$prevTable = '';
foreach ($fieldsMeta as $oneFieldMeta) {
if ($oneFieldMeta->table != '' && $prevTable != '' && $oneFieldMeta->table != $prevTable) {
$justOneTable = false;
}
if ($oneFieldMeta->table == '') {
continue;
}
$prevTable = $oneFieldMeta->table;
}
return $justOneTable && $prevTable != '';
}
/**
* Verify whether the result set contains all the columns
* of at least one unique key
*
* @param string $db database name
* @param string $table table name
* @param array $fieldsMeta meta fields
*/
private function resultSetContainsUniqueKey(string $db, string $table, array $fieldsMeta): bool
{
$columns = $this->dbi->getColumns($db, $table);
$resultSetColumnNames = [];
foreach ($fieldsMeta as $oneMeta) {
$resultSetColumnNames[] = $oneMeta->name;
}
foreach (Index::getFromTable($table, $db) as $index) {
if (! $index->isUnique()) {
continue;
}
$indexColumns = $index->getColumns();
$numberFound = 0;
foreach (array_keys($indexColumns) as $indexColumnName) {
if (
! in_array($indexColumnName, $resultSetColumnNames)
&& in_array($indexColumnName, $columns)
&& ! str_contains($columns[$indexColumnName]['Extra'], 'INVISIBLE')
) {
continue;
}
$numberFound++;
}
if ($numberFound == count($indexColumns)) {
return true;
}
}
return false;
}
/**
* Get the HTML for relational column dropdown
* During grid edit, if we have a relational field, returns the html for the
* dropdown
*
* @param string $db current database
* @param string $table current table
* @param string $column current column
* @param string $currentValue current selected value
*
* @return string html for the dropdown
*/
public function getHtmlForRelationalColumnDropdown($db, $table, $column, $currentValue)
{
$foreigners = $this->relation->getForeigners($db, $table, $column);
$foreignData = $this->relation->getForeignData($foreigners, $column, false, '', '');
if ($foreignData['disp_row'] == null) {
//Handle the case when number of values
//is more than $cfg['ForeignKeyMaxLimit']
$urlParams = [
'db' => $db,
'table' => $table,
'field' => $column,
];
$dropdown = $this->template->render('sql/relational_column_dropdown', [
'current_value' => $_POST['curr_value'],
'params' => $urlParams,
]);
} else {
$dropdown = $this->relation->foreignDropdown(
$foreignData['disp_row'],
$foreignData['foreign_field'],
$foreignData['foreign_display'],
$currentValue,
$GLOBALS['cfg']['ForeignKeyMaxLimit']
);
$dropdown = '<select>' . $dropdown . '</select>';
}
return $dropdown;
}
/** @return array<string, int|array> */
private function getDetailedProfilingStats(array $profilingResults): array
{
$profiling = [
'total_time' => 0,
'states' => [],
'chart' => [],
'profile' => [],
];
foreach ($profilingResults as $oneResult) {
$status = ucwords($oneResult['Status']);
$profiling['total_time'] += $oneResult['Duration'];
$profiling['profile'][] = [
'status' => $status,
'duration' => Util::formatNumber($oneResult['Duration'], 3, 1),
'duration_raw' => $oneResult['Duration'],
];
if (! isset($profiling['states'][$status])) {
$profiling['states'][$status] = [
'total_time' => $oneResult['Duration'],
'calls' => 1,
];
$profiling['chart'][$status] = $oneResult['Duration'];
} else {
$profiling['states'][$status]['calls']++;
$profiling['chart'][$status] += $oneResult['Duration'];
}
}
return $profiling;
}
/**
* Get value of a column for a specific row (marked by $whereClause)
*/
public function getFullValuesForSetColumn(
string $db,
string $table,
string $column,
string $whereClause
): string {
$row = $this->dbi->fetchSingleRow(sprintf(
'SELECT `%s` FROM `%s`.`%s` WHERE %s',
$column,
$db,
$table,
$whereClause
));
if ($row === null) {
return '';
}
return $row[$column];
}
/**
* Get all the values for a enum column or set column in a table
*
* @param string $db current database
* @param string $table current table
* @param string $column current column
*
* @return array|null array containing the value list for the column, null on failure
*/
public function getValuesForColumn(string $db, string $table, string $column): ?array
{
$fieldInfoQuery = QueryGenerator::getColumnsSql($db, $table, $this->dbi->escapeString($column));
$fieldInfoResult = $this->dbi->fetchResult($fieldInfoQuery);
if (! isset($fieldInfoResult[0])) {
return null;
}
return Util::parseEnumSetValues($fieldInfoResult[0]['Type']);
}
/**
* Function to check whether to remember the sorting order or not
*
* @param array $analyzedSqlResults the analyzed query and other variables set
* after analyzing the query
*/
private function isRememberSortingOrder(array $analyzedSqlResults): bool
{
return isset($analyzedSqlResults['select_expr'], $analyzedSqlResults['select_tables'])
&& $GLOBALS['cfg']['RememberSorting']
&& ! ($analyzedSqlResults['is_count']
|| $analyzedSqlResults['is_export']
|| $analyzedSqlResults['is_func']
|| $analyzedSqlResults['is_analyse'])
&& $analyzedSqlResults['select_from']
&& (empty($analyzedSqlResults['select_expr'])
|| ((count($analyzedSqlResults['select_expr']) === 1)
&& ($analyzedSqlResults['select_expr'][0] === '*')))
&& count($analyzedSqlResults['select_tables']) === 1;
}
/**
* Function to check whether the LIMIT clause should be appended or not
*
* @param array $analyzedSqlResults the analyzed query and other variables set
* after analyzing the query
*/
private function isAppendLimitClause(array $analyzedSqlResults): bool
{
// Assigning LIMIT clause to an syntactically-wrong query
// is not needed. Also we would want to show the true query
// and the true error message to the query executor
return (isset($analyzedSqlResults['parser'])
&& count($analyzedSqlResults['parser']->errors) === 0)
&& ($_SESSION['tmpval']['max_rows'] !== 'all')
&& ! ($analyzedSqlResults['is_export']
|| $analyzedSqlResults['is_analyse'])
&& ($analyzedSqlResults['select_from']
|| $analyzedSqlResults['is_subquery'])
&& empty($analyzedSqlResults['limit']);
}
/**
* Function to check whether this query is for just browsing
*
* @param array<string, mixed> $analyzedSqlResults the analyzed query and other variables set
* after analyzing the query
* @param bool|null $findRealEnd whether the real end should be found
*/
public static function isJustBrowsing(array $analyzedSqlResults, ?bool $findRealEnd): bool
{
return ! $analyzedSqlResults['is_group']
&& ! $analyzedSqlResults['is_func']
&& empty($analyzedSqlResults['union'])
&& empty($analyzedSqlResults['distinct'])
&& $analyzedSqlResults['select_from']
&& (count($analyzedSqlResults['select_tables']) === 1)
&& (empty($analyzedSqlResults['statement']->where)
|| (count($analyzedSqlResults['statement']->where) === 1
&& $analyzedSqlResults['statement']->where[0]->expr === '1'))
&& empty($analyzedSqlResults['group'])
&& ! isset($findRealEnd)
&& ! $analyzedSqlResults['is_subquery']
&& ! $analyzedSqlResults['join']
&& empty($analyzedSqlResults['having']);
}
/**
* Function to check whether the related transformation information should be deleted
*
* @param array $analyzedSqlResults the analyzed query and other variables set
* after analyzing the query
*/
private function isDeleteTransformationInfo(array $analyzedSqlResults): bool
{
return ! empty($analyzedSqlResults['querytype'])
&& (($analyzedSqlResults['querytype'] === 'ALTER')
|| ($analyzedSqlResults['querytype'] === 'DROP'));
}
/**
* Function to check whether the user has rights to drop the database
*
* @param array $analyzedSqlResults the analyzed query and other variables set
* after analyzing the query
* @param bool $allowUserDropDatabase whether the user is allowed to drop db
* @param bool $isSuperUser whether this user is a superuser
*/
public function hasNoRightsToDropDatabase(
array $analyzedSqlResults,
$allowUserDropDatabase,
$isSuperUser
): bool {
return ! $allowUserDropDatabase
&& isset($analyzedSqlResults['drop_database'])
&& $analyzedSqlResults['drop_database']
&& ! $isSuperUser;
}
/**
* Function to set a column property
*
* @param Table $table Table instance
* @param string $requestIndex col_order|col_visib
*
* @return bool|Message
*/
public function setColumnProperty(Table $table, string $requestIndex)
{
$propertyValue = array_map('intval', explode(',', $_POST[$requestIndex]));
switch ($requestIndex) {
case 'col_order':
$propertyToSet = Table::PROP_COLUMN_ORDER;
break;
case 'col_visib':
$propertyToSet = Table::PROP_COLUMN_VISIB;
break;
default:
$propertyToSet = '';
}
return $table->setUiProp($propertyToSet, $propertyValue, $_POST['table_create_time'] ?? null);
}
/**
* Function to find the real end of rows
*
* @param string $db the current database
* @param string $table the current table
*
* @return mixed the number of rows if "retain" param is true, otherwise true
*/
public function findRealEndOfRows($db, $table)
{
$unlimNumRows = $this->dbi->getTable($db, $table)->countRecords(true);
$_SESSION['tmpval']['pos'] = $this->getStartPosToDisplayRow($unlimNumRows);
return $unlimNumRows;
}
/**
* Function to get the default sql query for browsing page
*
* @param string $db the current database
* @param string $table the current table
*
* @return string the default $sql_query for browse page
*/
public function getDefaultSqlQueryForBrowse($db, $table): string
{
$bookmark = Bookmark::get($this->dbi, $GLOBALS['cfg']['Server']['user'], $db, $table, 'label', false, true);
if ($bookmark !== null && $bookmark->getQuery() !== '') {
$GLOBALS['using_bookmark_message'] = Message::notice(
__('Using bookmark "%s" as default browse query.')
);
$GLOBALS['using_bookmark_message']->addParam($table);
$GLOBALS['using_bookmark_message']->addHtml(
MySQLDocumentation::showDocumentation('faq', 'faq6-22')
);
return $bookmark->getQuery();
}
$defaultOrderByClause = '';
if (
isset($GLOBALS['cfg']['TablePrimaryKeyOrder'])
&& ($GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE')
) {
$primaryKey = null;
$primary = Index::getPrimary($table, $db);
if ($primary !== false) {
$primarycols = $primary->getColumns();
foreach ($primarycols as $col) {
$primaryKey = $col->getName();
break;
}
if ($primaryKey !== null) {
$defaultOrderByClause = ' ORDER BY '
. Util::backquote($table) . '.'
. Util::backquote($primaryKey) . ' '
. $GLOBALS['cfg']['TablePrimaryKeyOrder'];
}
}
}
return 'SELECT * FROM ' . Util::backquote($table) . $defaultOrderByClause;
}
/**
* Responds an error when an error happens when executing the query
*
* @param bool $isGotoFile whether goto file or not
* @param string $error error after executing the query
* @param string $fullSqlQuery full sql query
*/
private function handleQueryExecuteError($isGotoFile, $error, $fullSqlQuery): void
{
if ($isGotoFile) {
$message = Message::rawError($error);
$response = ResponseRenderer::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', $message);
} else {
Generator::mysqlDie($error, $fullSqlQuery, false);
}
exit;
}
/**
* Function to store the query as a bookmark
*
* @param string $db the current database
* @param string $bookmarkUser the bookmarking user
* @param string $sqlQueryForBookmark the query to be stored in bookmark
* @param string $bookmarkLabel bookmark label
* @param bool $bookmarkReplace whether to replace existing bookmarks
*/
public function storeTheQueryAsBookmark(
?BookmarkFeature $bookmarkFeature,
$db,
$bookmarkUser,
$sqlQueryForBookmark,
$bookmarkLabel,
bool $bookmarkReplace
): void {
$bfields = [
'bkm_database' => $db,
'bkm_user' => $bookmarkUser,
'bkm_sql_query' => $sqlQueryForBookmark,
'bkm_label' => $bookmarkLabel,
];
// Should we replace bookmark?
if ($bookmarkReplace && $bookmarkFeature !== null) {
$bookmarks = Bookmark::getList($bookmarkFeature, $this->dbi, $GLOBALS['cfg']['Server']['user'], $db);
foreach ($bookmarks as $bookmark) {
if ($bookmark->getLabel() != $bookmarkLabel) {
continue;
}
$bookmark->delete();
}
}
$bookmark = Bookmark::createBookmark(
$this->dbi,
$bfields,
isset($_POST['bkm_all_users'])
);
if ($bookmark === false) {
return;
}
$bookmark->save();
}
/**
* Function to get the affected or changed number of rows after executing a query
*
* @param bool $isAffected whether the query affected a table
* @param ResultInterface|false $result results of executing the query
*
* @return int|string number of rows affected or changed
* @psalm-return int|numeric-string
*/
private function getNumberOfRowsAffectedOrChanged($isAffected, $result)
{
if ($isAffected) {
return $this->dbi->affectedRows();
}
if ($result) {
return $result->numRows();
}
return 0;
}
/**
* Checks if the current database has changed
* This could happen if the user sends a query like "USE `database`;"
*
* @param string $db the database in the query
*
* @return bool whether to reload the navigation(1) or not(0)
*/
private function hasCurrentDbChanged(string $db): bool
{
if ($db === '') {
return false;
}
$currentDb = $this->dbi->fetchValue('SELECT DATABASE()');
// $current_db is false, except when a USE statement was sent
return ($currentDb != false) && ($db !== $currentDb);
}
/**
* If a table, database or column gets dropped, clean comments.
*
* @param string $db current database
* @param string $table current table
* @param string|null $column current column
* @param bool $purge whether purge set or not
*/
private function cleanupRelations(string $db, string $table, ?string $column, bool $purge): void
{
if (! $purge || $db === '') {
return;
}
if ($table !== '') {
if ($column !== null && $column !== '') {
$this->relationCleanup->column($db, $table, $column);
} else {
$this->relationCleanup->table($db, $table);
}
} else {
$this->relationCleanup->database($db);
}
}
/**
* Function to count the total number of rows for the same 'SELECT' query without
* the 'LIMIT' clause that may have been programmatically added
*
* @param int|string $numRows number of rows affected/changed by the query
* @param bool $justBrowsing whether just browsing or not
* @param string $db the current database
* @param string $table the current table
* @param array $analyzedSqlResults the analyzed query and other variables set after analyzing the query
* @psalm-param int|numeric-string $numRows
*
* @return int|string unlimited number of rows
* @psalm-return int|numeric-string
*/
private function countQueryResults(
$numRows,
bool $justBrowsing,
string $db,
string $table,
array $analyzedSqlResults
) {
/* Shortcut for not analyzed/empty query */
if ($analyzedSqlResults === []) {
return 0;
}
if (! $this->isAppendLimitClause($analyzedSqlResults)) {
// if we did not append a limit, set this to get a correct
// "Showing rows..." message
// $_SESSION['tmpval']['max_rows'] = 'all';
$unlimNumRows = $numRows;
} elseif ($_SESSION['tmpval']['max_rows'] > $numRows) {
// When user has not defined a limit in query and total rows in
// result are less than max_rows to display, there is no need
// to count total rows for that query again
$unlimNumRows = $_SESSION['tmpval']['pos'] + $numRows;
} elseif ($analyzedSqlResults['querytype'] === 'SELECT' || $analyzedSqlResults['is_subquery']) {
// c o u n t q u e r y
// If we are "just browsing", there is only one table (and no join),
// and no WHERE clause (or just 'WHERE 1 '),
// we do a quick count (which uses MaxExactCount) because
// SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
// However, do not count again if we did it previously
// due to $find_real_end == true
if ($justBrowsing) {
// Get row count (is approximate for InnoDB)
$unlimNumRows = $this->dbi->getTable($db, $table)->countRecords();
/**
* @todo Can we know at this point that this is InnoDB,
* (in this case there would be no need for getting
* an exact count)?
*/
if ($unlimNumRows < $GLOBALS['cfg']['MaxExactCount']) {
// Get the exact count if approximate count
// is less than MaxExactCount
/**
* @todo In countRecords(), MaxExactCount is also verified,
* so can we avoid checking it twice?
*/
$unlimNumRows = $this->dbi->getTable($db, $table)
->countRecords(true);
}
} else {
$statement = $analyzedSqlResults['statement'];
$tokenList = $analyzedSqlResults['parser']->list;
$replaces = [
// Remove ORDER BY to decrease unnecessary sorting time
[
'ORDER BY',
'',
],
// Removes LIMIT clause that might have been added
[
'LIMIT',
'',
],
];
$countQuery = 'SELECT COUNT(*) FROM (' . Query::replaceClauses(
$statement,
$tokenList,
$replaces
) . ') as cnt';
$unlimNumRows = $this->dbi->fetchValue($countQuery);
if ($unlimNumRows === false) {
$unlimNumRows = 0;
}
}
} else {// not $is_select
$unlimNumRows = 0;
}
return $unlimNumRows;
}
/**
* Function to handle all aspects relating to executing the query
*
* @param array $analyzedSqlResults analyzed sql results
* @param string $fullSqlQuery full sql query
* @param bool $isGotoFile whether to go to a file
* @param string $db current database
* @param string|null $table current table
* @param bool|null $findRealEnd whether to find the real end
* @param string|null $sqlQueryForBookmark sql query to be stored as bookmark
* @param array|null $extraData extra data
*
* @psalm-return array{
* ResultInterface|false|null,
* int|numeric-string,
* int|numeric-string,
* array<string, string>|null,
* array|null
* }
*/
private function executeTheQuery(
array $analyzedSqlResults,
$fullSqlQuery,
$isGotoFile,
string $db,
?string $table,
?bool $findRealEnd,
?string $sqlQueryForBookmark,
$extraData
): array {
$response = ResponseRenderer::getInstance();
$response->getHeader()->getMenu()->setTable($table ?? '');
// Only if we ask to see the php code
if (isset($GLOBALS['show_as_php'])) {
$result = null;
$numRows = 0;
$unlimNumRows = 0;
$profilingResults = null;
} else { // If we don't ask to see the php code
Profiling::enable($this->dbi);
if (! defined('TESTSUITE')) {
// close session in case the query takes too long
session_write_close();
}
$result = $this->dbi->tryQuery($fullSqlQuery);
$GLOBALS['querytime'] = $this->dbi->lastQueryExecutionTime;
if (! defined('TESTSUITE')) {
// reopen session
session_start();
}
// Displays an error message if required and stop parsing the script
$error = $this->dbi->getError();
if ($error && $GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
$extraData['error'] = $error;
} elseif ($error) {
$this->handleQueryExecuteError($isGotoFile, $error, $fullSqlQuery);
}
// If there are no errors and bookmarklabel was given,
// store the query as a bookmark
if (! empty($_POST['bkm_label']) && $sqlQueryForBookmark) {
$bookmarkFeature = $this->relation->getRelationParameters()->bookmarkFeature;
$this->storeTheQueryAsBookmark(
$bookmarkFeature,
$db,
$bookmarkFeature !== null ? $GLOBALS['cfg']['Server']['user'] : '',
$sqlQueryForBookmark,
$_POST['bkm_label'],
isset($_POST['bkm_replace'])
);
}
// Gets the number of rows affected/returned
// (This must be done immediately after the query because
// mysql_affected_rows() reports about the last query done)
$numRows = $this->getNumberOfRowsAffectedOrChanged($analyzedSqlResults['is_affected'], $result);
$profilingResults = Profiling::getInformation($this->dbi);
$justBrowsing = self::isJustBrowsing($analyzedSqlResults, $findRealEnd ?? null);
$unlimNumRows = $this->countQueryResults($numRows, $justBrowsing, $db, $table ?? '', $analyzedSqlResults);
$this->cleanupRelations($db, $table ?? '', $_POST['dropped_column'] ?? null, ! empty($_POST['purge']));
if (
isset($_POST['dropped_column'])
&& $db !== '' && $table !== null && $table !== ''
) {
// to refresh the list of indexes (Ajax mode)
$indexes = Index::getFromTable($table, $db);
$indexesDuplicates = Index::findDuplicates($table, $db);
$template = new Template();
$extraData['indexes_list'] = $template->render('indexes', [
'url_params' => $GLOBALS['urlParams'],
'indexes' => $indexes,
'indexes_duplicates' => $indexesDuplicates,
]);
}
}
return [
$result,
$numRows,
$unlimNumRows,
$profilingResults,
$extraData,
];
}
/**
* Delete related transformation information
*
* @param string $db current database
* @param string $table current table
* @param array $analyzedSqlResults analyzed sql results
*/
private function deleteTransformationInfo(string $db, string $table, array $analyzedSqlResults): void
{
if (! isset($analyzedSqlResults['statement'])) {
return;
}
$statement = $analyzedSqlResults['statement'];
if ($statement instanceof AlterStatement) {
if (
! empty($statement->altered[0])
&& $statement->altered[0]->options->has('DROP')
&& ! empty($statement->altered[0]->field->column)
) {
$this->transformations->clear($db, $table, $statement->altered[0]->field->column);
}
} elseif ($statement instanceof DropStatement) {
$this->transformations->clear($db, $table);
}
}
/**
* Function to get the message for the no rows returned case
*
* @param string|null $messageToShow message to show
* @param array $analyzedSqlResults analyzed sql results
* @param int|string $numRows number of rows
*/
private function getMessageForNoRowsReturned(
?string $messageToShow,
array $analyzedSqlResults,
$numRows
): Message {
if ($analyzedSqlResults['querytype'] === 'DELETE') {
$message = Message::getMessageForDeletedRows($numRows);
} elseif ($analyzedSqlResults['is_insert']) {
if ($analyzedSqlResults['querytype'] === 'REPLACE') {
// For REPLACE we get DELETED + INSERTED row count,
// so we have to call it affected
$message = Message::getMessageForAffectedRows($numRows);
} else {
$message = Message::getMessageForInsertedRows($numRows);
}
$insertId = $this->dbi->insertId();
if ($insertId !== 0) {
// insert_id is id of FIRST record inserted in one insert,
// so if we inserted multiple rows, we had to increment this
$message->addText('[br]');
// need to use a temporary because the Message class
// currently supports adding parameters only to the first
// message
$inserted = Message::notice(__('Inserted row id: %1$d'));
$inserted->addParam($insertId + $numRows - 1);
$message->addMessage($inserted);
}
} elseif ($analyzedSqlResults['is_affected']) {
$message = Message::getMessageForAffectedRows($numRows);
// Ok, here is an explanation for the !$is_select.
// The form generated by PhpMyAdmin\SqlQueryForm
// and /database/sql has many submit buttons
// on the same form, and some confusion arises from the
// fact that $message_to_show is sent for every case.
// The $message_to_show containing a success message and sent with
// the form should not have priority over errors
} elseif ($messageToShow && $analyzedSqlResults['querytype'] !== 'SELECT') {
$message = Message::rawSuccess(htmlspecialchars($messageToShow));
} elseif (! empty($GLOBALS['show_as_php'])) {
$message = Message::success(__('Showing as PHP code'));
} elseif (isset($GLOBALS['show_as_php'])) {
/* User disable showing as PHP, query is only displayed */
$message = Message::notice(__('Showing SQL query'));
} else {
$message = Message::success(
__('MySQL returned an empty result set (i.e. zero rows).')
);
}
if (isset($GLOBALS['querytime'])) {
$queryTime = Message::notice(
'(' . __('Query took %01.4f seconds.') . ')'
);
$queryTime->addParam($GLOBALS['querytime']);
$message->addMessage($queryTime);
}
// In case of ROLLBACK, notify the user.
if (isset($_POST['rollback_query'])) {
$message->addText(__('[ROLLBACK occurred.]'));
}
return $message;
}
/**
* Function to respond back when the query returns zero rows
* This method is called
* 1-> When browsing an empty table
* 2-> When executing a query on a non empty table which returns zero results
* 3-> When executing a query on an empty table
* 4-> When executing an INSERT, UPDATE, DELETE query from the SQL tab
* 5-> When deleting a row from BROWSE tab
* 6-> When searching using the SEARCH tab which returns zero results
* 7-> When changing the structure of the table except change operation
*
* @param array $analyzedSqlResults analyzed sql results
* @param string $db current database
* @param string|null $table current table
* @param string|null $messageToShow message to show
* @param int|string $numRows number of rows
* @param DisplayResults $displayResultsObject DisplayResult instance
* @param array|null $extraData extra data
* @param array|null $profilingResults profiling results
* @param ResultInterface|false|null $result executed query results
* @param string $sqlQuery sql query
* @param string|null $completeQuery complete sql query
* @psalm-param int|numeric-string $numRows
*
* @return string html
*/
private function getQueryResponseForNoResultsReturned(
array $analyzedSqlResults,
string $db,
?string $table,
?string $messageToShow,
$numRows,
$displayResultsObject,
?array $extraData,
?array $profilingResults,
$result,
$sqlQuery,
?string $completeQuery
): string {
if ($this->isDeleteTransformationInfo($analyzedSqlResults)) {
$this->deleteTransformationInfo($db, $table ?? '', $analyzedSqlResults);
}
if (isset($extraData['error'])) {
$message = Message::rawError($extraData['error']);
} else {
$message = $this->getMessageForNoRowsReturned($messageToShow, $analyzedSqlResults, $numRows);
}
$queryMessage = Generator::getMessage($message, $GLOBALS['sql_query'], 'success');
if (isset($GLOBALS['show_as_php'])) {
return $queryMessage;
}
if (! empty($GLOBALS['reload'])) {
$extraData['reload'] = 1;
$extraData['db'] = $GLOBALS['db'];
}
// For ajax requests add message and sql_query as JSON
if (empty($_REQUEST['ajax_page_request'])) {
$extraData['message'] = $message;
if ($GLOBALS['cfg']['ShowSQL']) {
$extraData['sql_query'] = $queryMessage;
}
}
$response = ResponseRenderer::getInstance();
$response->addJSON($extraData ?? []);
if (empty($analyzedSqlResults['is_select']) || isset($extraData['error'])) {
return $queryMessage;
}
$displayParts = [
'edit_lnk' => null,
'del_lnk' => null,
'sort_lnk' => '1',
'nav_bar' => '0',
'bkm_form' => '1',
'text_btn' => '1',
'pview_lnk' => '1',
];
$sqlQueryResultsTable = $this->getHtmlForSqlQueryResultsTable(
$displayResultsObject,
$displayParts,
false,
0,
$numRows,
null,
$result,
$analyzedSqlResults,
true
);
$profilingChart = '';
if ($profilingResults !== null) {
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('sql.js');
$profiling = $this->getDetailedProfilingStats($profilingResults);
$profilingChart = $this->template->render('sql/profiling_chart', ['profiling' => $profiling]);
}
$bookmark = '';
$bookmarkFeature = $this->relation->getRelationParameters()->bookmarkFeature;
if (
$bookmarkFeature !== null
&& empty($_GET['id_bookmark'])
&& $sqlQuery
) {
$bookmark = $this->template->render('sql/bookmark', [
'db' => $db,
'goto' => Url::getFromRoute('/sql', [
'db' => $db,
'table' => $table,
'sql_query' => $sqlQuery,
'id_bookmark' => 1,
]),
'user' => $GLOBALS['cfg']['Server']['user'],
'sql_query' => $completeQuery ?? $sqlQuery,
]);
}
return $this->template->render('sql/no_results_returned', [
'message' => $queryMessage,
'sql_query_results_table' => $sqlQueryResultsTable,
'profiling_chart' => $profilingChart,
'bookmark' => $bookmark,
'db' => $db,
'table' => $table,
'sql_query' => $sqlQuery,
'is_procedure' => ! empty($analyzedSqlResults['procedure']),
]);
}
/**
* Function to send response for ajax grid edit
*
* @param ResultInterface $result result of the executed query
*/
private function getResponseForGridEdit(ResultInterface $result): void
{
$row = $result->fetchRow();
$fieldsMeta = $this->dbi->getFieldsMeta($result);
if (isset($fieldsMeta[0]) && $fieldsMeta[0]->isBinary()) {
$row[0] = bin2hex($row[0]);
}
$response = ResponseRenderer::getInstance();
$response->addJSON('value', $row[0]);
}
/**
* Returns a message for successful creation of a bookmark or null if a bookmark
* was not created
*/
private function getBookmarkCreatedMessage(): string
{
$output = '';
if (isset($_GET['label'])) {
$message = Message::success(
__('Bookmark %s has been created.')
);
$message->addParam($_GET['label']);
$output = $message->getDisplay();
}
return $output;
}
/**
* Function to get html for the sql query results table
*
* @param DisplayResults $displayResultsObject instance of DisplayResult
* @param array $displayParts the parts to display
* @param bool $editable whether the result table is
* editable or not
* @param int|string $unlimNumRows unlimited number of rows
* @param int|string $numRows number of rows
* @param array|null $showTable table definitions
* @param ResultInterface|false|null $result result of the executed query
* @param array $analyzedSqlResults analyzed sql results
* @param bool $isLimitedDisplay Show only limited operations or not
* @psalm-param int|numeric-string $unlimNumRows
* @psalm-param int|numeric-string $numRows
*/
private function getHtmlForSqlQueryResultsTable(
$displayResultsObject,
array $displayParts,
$editable,
$unlimNumRows,
$numRows,
?array $showTable,
$result,
array $analyzedSqlResults,
$isLimitedDisplay = false
): string {
$printView = isset($_POST['printview']) && $_POST['printview'] == '1' ? '1' : null;
$tableHtml = '';
$isBrowseDistinct = ! empty($_POST['is_browse_distinct']);
if ($analyzedSqlResults['is_procedure']) {
do {
if ($result === null) {
$result = $this->dbi->storeResult();
}
if ($result === false) {
$result = null;
continue;
}
$numRows = $result->numRows();
if ($numRows > 0) {
$fieldsMeta = $this->dbi->getFieldsMeta($result);
$fieldsCount = count($fieldsMeta);
$displayResultsObject->setProperties(
$numRows,
$fieldsMeta,
$analyzedSqlResults['is_count'],
$analyzedSqlResults['is_export'],
$analyzedSqlResults['is_func'],
$analyzedSqlResults['is_analyse'],
$numRows,
$fieldsCount,
$GLOBALS['querytime'],
$GLOBALS['text_dir'],
$analyzedSqlResults['is_maint'],
$analyzedSqlResults['is_explain'],
$analyzedSqlResults['is_show'],
$showTable,
$printView,
$editable,
$isBrowseDistinct
);
$displayParts = [
'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'sort_lnk' => '1',
'nav_bar' => '1',
'bkm_form' => '1',
'text_btn' => '1',
'pview_lnk' => '1',
];
$tableHtml .= $displayResultsObject->getTable(
$result,
$displayParts,
$analyzedSqlResults,
$isLimitedDisplay
);
}
$result = null;
} while ($this->dbi->moreResults() && $this->dbi->nextResult());
} else {
$fieldsMeta = [];
if (isset($result) && ! is_bool($result)) {
$fieldsMeta = $this->dbi->getFieldsMeta($result);
}
$fieldsCount = count($fieldsMeta);
$_SESSION['is_multi_query'] = false;
$displayResultsObject->setProperties(
$unlimNumRows,
$fieldsMeta,
$analyzedSqlResults['is_count'],
$analyzedSqlResults['is_export'],
$analyzedSqlResults['is_func'],
$analyzedSqlResults['is_analyse'],
$numRows,
$fieldsCount,
$GLOBALS['querytime'],
$GLOBALS['text_dir'],
$analyzedSqlResults['is_maint'],
$analyzedSqlResults['is_explain'],
$analyzedSqlResults['is_show'],
$showTable,
$printView,
$editable,
$isBrowseDistinct
);
if (! is_bool($result)) {
$tableHtml .= $displayResultsObject->getTable(
$result,
$displayParts,
$analyzedSqlResults,
$isLimitedDisplay
);
}
}
return $tableHtml;
}
/**
* Function to get html for the previous query if there is such.
*
* @param string|null $displayQuery display query
* @param bool $showSql whether to show sql
* @param array $sqlData sql data
* @param Message|string $displayMessage display message
*/
private function getHtmlForPreviousUpdateQuery(
?string $displayQuery,
bool $showSql,
array $sqlData,
$displayMessage
): string {
$output = '';
if ($displayQuery !== null && $showSql && $sqlData === []) {
$output = Generator::getMessage($displayMessage, $displayQuery, 'success');
}
return $output;
}
/**
* To get the message if a column index is missing. If not will return null
*
* @param string|null $table current table
* @param string $database current database
* @param bool $editable whether the results table can be editable or not
* @param bool $hasUniqueKey whether there is a unique key
*/
private function getMessageIfMissingColumnIndex(
?string $table,
string $database,
bool $editable,
bool $hasUniqueKey
): string {
if ($table === null) {
return '';
}
$output = '';
if (Utilities::isSystemSchema($database) || ! $editable) {
$output = Message::notice(
sprintf(
__(
'Current selection does not contain a unique column.'
. ' Grid edit, checkbox, Edit, Copy and Delete features'
. ' are not available. %s'
),
MySQLDocumentation::showDocumentation(
'config',
'cfg_RowActionLinksWithoutUnique'
)
)
)->getDisplay();
} elseif (! $hasUniqueKey) {
$output = Message::notice(
sprintf(
__(
'Current selection does not contain a unique column.'
. ' Grid edit, Edit, Copy and Delete features may result in'
. ' undesired behavior. %s'
),
MySQLDocumentation::showDocumentation(
'config',
'cfg_RowActionLinksWithoutUnique'
)
)
)->getDisplay();
}
return $output;
}
/**
* Function to display results when the executed query returns non empty results
*
* @param ResultInterface|false|null $result executed query results
* @param array $analyzedSqlResults analysed sql results
* @param string $db current database
* @param string|null $table current table
* @param array|null $sqlData sql data
* @param DisplayResults $displayResultsObject Instance of DisplayResults
* @param int|string $unlimNumRows unlimited number of rows
* @param int|string $numRows number of rows
* @param string|null $dispQuery display query
* @param Message|string|null $dispMessage display message
* @param array|null $profilingResults profiling results
* @param string $sqlQuery sql query
* @param string|null $completeQuery complete sql query
* @psalm-param int|numeric-string $unlimNumRows
* @psalm-param int|numeric-string $numRows
*
* @return string html
*/
private function getQueryResponseForResultsReturned(
$result,
array $analyzedSqlResults,
string $db,
?string $table,
?array $sqlData,
$displayResultsObject,
$unlimNumRows,
$numRows,
?string $dispQuery,
$dispMessage,
?array $profilingResults,
$sqlQuery,
?string $completeQuery
): string {
global $showtable;
// If we are retrieving the full value of a truncated field or the original
// value of a transformed field, show it here
if (isset($_POST['grid_edit']) && $_POST['grid_edit'] == true && is_object($result)) {
$this->getResponseForGridEdit($result);
exit;
}
// Gets the list of fields properties
$fieldsMeta = [];
if ($result !== null && ! is_bool($result)) {
$fieldsMeta = $this->dbi->getFieldsMeta($result);
}
// Should be initialized these parameters before parsing
if (! is_array($showtable)) {
$showtable = null;
}
$response = ResponseRenderer::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$justOneTable = $this->resultSetHasJustOneTable($fieldsMeta);
// hide edit and delete links:
// - for information_schema
// - if the result set does not contain all the columns of a unique key
// (unless this is an updatable view)
// - if the SELECT query contains a join or a subquery
$updatableView = false;
$statement = $analyzedSqlResults['statement'] ?? null;
if ($statement instanceof SelectStatement) {
if ($statement->expr && $statement->expr[0]->expr === '*' && $table) {
$_table = new Table($table, $db);
$updatableView = $_table->isUpdatableView();
}
if (
$analyzedSqlResults['join']
|| $analyzedSqlResults['is_subquery']
|| count($analyzedSqlResults['select_tables']) !== 1
) {
$justOneTable = false;
}
}
$hasUnique = $table !== null && $this->resultSetContainsUniqueKey($db, $table, $fieldsMeta);
$editable = ($hasUnique
|| $GLOBALS['cfg']['RowActionLinksWithoutUnique']
|| $updatableView)
&& $justOneTable
&& ! Utilities::isSystemSchema($db);
$_SESSION['tmpval']['possible_as_geometry'] = $editable;
$displayParts = [
'edit_lnk' => $displayResultsObject::UPDATE_ROW,
'del_lnk' => $displayResultsObject::DELETE_ROW,
'sort_lnk' => '1',
'nav_bar' => '1',
'bkm_form' => '1',
'text_btn' => '0',
'pview_lnk' => '1',
];
if (! $editable) {
$displayParts = [
'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'sort_lnk' => '1',
'nav_bar' => '1',
'bkm_form' => '1',
'text_btn' => '1',
'pview_lnk' => '1',
];
}
if (isset($_POST['printview']) && $_POST['printview'] == '1') {
$displayParts = [
'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
'sort_lnk' => '0',
'nav_bar' => '0',
'bkm_form' => '0',
'text_btn' => '0',
'pview_lnk' => '0',
];
}
if (! isset($_POST['printview']) || $_POST['printview'] != '1') {
$scripts->addFile('makegrid.js');
$scripts->addFile('sql.js');
unset($GLOBALS['message']);
//we don't need to buffer the output in getMessage here.
//set a global variable and check against it in the function
$GLOBALS['buffer_message'] = false;
}
$previousUpdateQueryHtml = $this->getHtmlForPreviousUpdateQuery(
$dispQuery,
(bool) $GLOBALS['cfg']['ShowSQL'],
$sqlData ?? [],
$dispMessage ?? ''
);
$profilingChartHtml = '';
if ($profilingResults) {
$profiling = $this->getDetailedProfilingStats($profilingResults);
$profilingChartHtml = $this->template->render('sql/profiling_chart', ['profiling' => $profiling]);
}
$missingUniqueColumnMessage = $this->getMessageIfMissingColumnIndex($table, $db, $editable, $hasUnique);
$bookmarkCreatedMessage = $this->getBookmarkCreatedMessage();
$tableHtml = $this->getHtmlForSqlQueryResultsTable(
$displayResultsObject,
$displayParts,
$editable,
$unlimNumRows,
$numRows,
$showtable,
$result,
$analyzedSqlResults
);
$bookmarkSupportHtml = '';
$bookmarkFeature = $this->relation->getRelationParameters()->bookmarkFeature;
if (
$bookmarkFeature !== null
&& $displayParts['bkm_form'] == '1'
&& empty($_GET['id_bookmark'])
&& $sqlQuery
) {
$bookmarkSupportHtml = $this->template->render('sql/bookmark', [
'db' => $db,
'goto' => Url::getFromRoute('/sql', [
'db' => $db,
'table' => $table,
'sql_query' => $sqlQuery,
'id_bookmark' => 1,
]),
'user' => $GLOBALS['cfg']['Server']['user'],
'sql_query' => $completeQuery ?? $sqlQuery,
]);
}
return $this->template->render('sql/sql_query_results', [
'previous_update_query' => $previousUpdateQueryHtml,
'profiling_chart' => $profilingChartHtml,
'missing_unique_column_message' => $missingUniqueColumnMessage,
'bookmark_created_message' => $bookmarkCreatedMessage,
'table' => $tableHtml,
'bookmark_support' => $bookmarkSupportHtml,
]);
}
/**
* Function to execute the query and send the response
*
* @param array|null $analyzedSqlResults analysed sql results
* @param bool $isGotoFile whether goto file or not
* @param string $db current database
* @param string|null $table current table
* @param bool|null $findRealEnd whether to find real end or not
* @param string|null $sqlQueryForBookmark the sql query to be stored as bookmark
* @param array|null $extraData extra data
* @param string|null $messageToShow message to show
* @param array|null $sqlData sql data
* @param string $goto goto page url
* @param string|null $dispQuery display query
* @param Message|string|null $dispMessage display message
* @param string $sqlQuery sql query
* @param string|null $completeQuery complete query
*/
public function executeQueryAndSendQueryResponse(
$analyzedSqlResults,
$isGotoFile,
string $db,
?string $table,
$findRealEnd,
$sqlQueryForBookmark,
$extraData,
$messageToShow,
$sqlData,
$goto,
$dispQuery,
$dispMessage,
$sqlQuery,
$completeQuery
): string {
if ($analyzedSqlResults == null) {
// Parse and analyze the query
[
$analyzedSqlResults,
$db,
$tableFromSql,
] = ParseAnalyze::sqlQuery($sqlQuery, $db);
$table = $tableFromSql ?: $table;
}
return $this->executeQueryAndGetQueryResponse(
$analyzedSqlResults, // analyzed_sql_results
$isGotoFile, // is_gotofile
$db, // db
$table, // table
$findRealEnd, // find_real_end
$sqlQueryForBookmark, // sql_query_for_bookmark
$extraData, // extra_data
$messageToShow, // message_to_show
$sqlData, // sql_data
$goto, // goto
$dispQuery, // disp_query
$dispMessage, // disp_message
$sqlQuery, // sql_query
$completeQuery // complete_query
);
}
/**
* Function to execute the query and send the response
*
* @param array $analyzedSqlResults analysed sql results
* @param bool $isGotoFile whether goto file or not
* @param string $db current database
* @param string|null $table current table
* @param bool|null $findRealEnd whether to find real end or not
* @param string|null $sqlQueryForBookmark the sql query to be stored as bookmark
* @param array|null $extraData extra data
* @param string|null $messageToShow message to show
* @param array|null $sqlData sql data
* @param string $goto goto page url
* @param string|null $dispQuery display query
* @param Message|string|null $dispMessage display message
* @param string $sqlQuery sql query
* @param string|null $completeQuery complete query
*
* @return string html
*/
public function executeQueryAndGetQueryResponse(
array $analyzedSqlResults,
$isGotoFile,
string $db,
?string $table,
$findRealEnd,
?string $sqlQueryForBookmark,
$extraData,
?string $messageToShow,
$sqlData,
$goto,
?string $dispQuery,
$dispMessage,
$sqlQuery,
?string $completeQuery
): string {
// Handle disable/enable foreign key checks
$defaultFkCheck = ForeignKey::handleDisableCheckInit();
// Handle remembered sorting order, only for single table query.
// Handling is not required when it's a union query
// (the parser never sets the 'union' key to 0).
// Handling is also not required if we came from the "Sort by key"
// drop-down.
if (
$analyzedSqlResults !== []
&& $this->isRememberSortingOrder($analyzedSqlResults)
&& empty($analyzedSqlResults['union'])
&& ! isset($_POST['sort_by_key'])
) {
if (! isset($_SESSION['sql_from_query_box'])) {
$this->handleSortOrder($db, $table, $analyzedSqlResults, $sqlQuery);
} else {
unset($_SESSION['sql_from_query_box']);
}
}
$displayResultsObject = new DisplayResults(
$GLOBALS['dbi'],
$GLOBALS['db'],
$GLOBALS['table'],
$GLOBALS['server'],
$goto,
$sqlQuery
);
$displayResultsObject->setConfigParamsForDisplayTable($analyzedSqlResults);
// assign default full_sql_query
$fullSqlQuery = $sqlQuery;
// Do append a "LIMIT" clause?
if ($this->isAppendLimitClause($analyzedSqlResults)) {
$fullSqlQuery = $this->getSqlWithLimitClause($analyzedSqlResults);
}
$GLOBALS['reload'] = $this->hasCurrentDbChanged($db);
$this->dbi->selectDb($db);
[
$result,
$numRows,
$unlimNumRows,
$profilingResults,
$extraData,
] = $this->executeTheQuery(
$analyzedSqlResults,
$fullSqlQuery,
$isGotoFile,
$db,
$table,
$findRealEnd,
$sqlQueryForBookmark,
$extraData
);
if ($this->dbi->moreResults()) {
$this->dbi->nextResult();
}
$warningMessages = $this->operations->getWarningMessagesArray();
// No rows returned -> move back to the calling page
if (($numRows == 0 && $unlimNumRows == 0) || $analyzedSqlResults['is_affected']) {
$htmlOutput = $this->getQueryResponseForNoResultsReturned(
$analyzedSqlResults,
$db,
$table,
$messageToShow,
$numRows,
$displayResultsObject,
$extraData,
$profilingResults,
$result,
$sqlQuery,
$completeQuery
);
} else {
// At least one row is returned -> displays a table with results
$htmlOutput = $this->getQueryResponseForResultsReturned(
$result,
$analyzedSqlResults,
$db,
$table,
$sqlData,
$displayResultsObject,
$unlimNumRows,
$numRows,
$dispQuery,
$dispMessage,
$profilingResults,
$sqlQuery,
$completeQuery
);
}
// Handle disable/enable foreign key checks
ForeignKey::handleDisableCheckCleanup($defaultFkCheck);
foreach ($warningMessages as $warning) {
$message = Message::notice(Message::sanitize($warning));
$htmlOutput .= $message->getDisplay();
}
return $htmlOutput;
}
/**
* Function to define pos to display a row
*
* @param int $numberOfLine Number of the line to display
*
* @return int Start position to display the line
*/
private function getStartPosToDisplayRow($numberOfLine)
{
$maxRows = $_SESSION['tmpval']['max_rows'];
return @((int) ceil($numberOfLine / $maxRows) - 1) * $maxRows;
}
/**
* Function to calculate new pos if pos is higher than number of rows
* of displayed table
*
* @param string $db Database name
* @param string $table Table name
* @param int|null $pos Initial position
*
* @return int Number of pos to display last page
*/
public function calculatePosForLastPage($db, $table, $pos)
{
if ($pos === null) {
$pos = $_SESSION['tmpval']['pos'];
}
$tableObject = new Table($table, $db);
$unlimNumRows = $tableObject->countRecords(true);
//If position is higher than number of rows
if ($unlimNumRows <= $pos && $pos != 0) {
$pos = $this->getStartPosToDisplayRow($unlimNumRows);
}
return $pos;
}
}
|