Operations.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use PhpMyAdmin\Engines\Innodb;
  5. use PhpMyAdmin\Plugins\Export\ExportSql;
  6. use function array_merge;
  7. use function count;
  8. use function explode;
  9. use function implode;
  10. use function mb_strtolower;
  11. use function str_replace;
  12. use function strlen;
  13. use function strtolower;
  14. use function urldecode;
  15. /**
  16. * Set of functions with the operations section in phpMyAdmin
  17. */
  18. class Operations
  19. {
  20. /** @var Relation */
  21. private $relation;
  22. /** @var DatabaseInterface */
  23. private $dbi;
  24. /**
  25. * @param DatabaseInterface $dbi DatabaseInterface object
  26. * @param Relation $relation Relation object
  27. */
  28. public function __construct(DatabaseInterface $dbi, Relation $relation)
  29. {
  30. $this->dbi = $dbi;
  31. $this->relation = $relation;
  32. }
  33. /**
  34. * Run the Procedure definitions and function definitions
  35. *
  36. * to avoid selecting alternatively the current and new db
  37. * we would need to modify the CREATE definitions to qualify
  38. * the db name
  39. *
  40. * @param string $db database name
  41. *
  42. * @return void
  43. */
  44. public function runProcedureAndFunctionDefinitions($db)
  45. {
  46. $procedure_names = $this->dbi->getProceduresOrFunctions($db, 'PROCEDURE');
  47. if ($procedure_names) {
  48. foreach ($procedure_names as $procedure_name) {
  49. $this->dbi->selectDb($db);
  50. $tmp_query = $this->dbi->getDefinition(
  51. $db,
  52. 'PROCEDURE',
  53. $procedure_name
  54. );
  55. if ($tmp_query === null) {
  56. continue;
  57. }
  58. // collect for later display
  59. $GLOBALS['sql_query'] .= "\n" . $tmp_query;
  60. $this->dbi->selectDb($_POST['newname']);
  61. $this->dbi->query($tmp_query);
  62. }
  63. }
  64. $function_names = $this->dbi->getProceduresOrFunctions($db, 'FUNCTION');
  65. if (! $function_names) {
  66. return;
  67. }
  68. foreach ($function_names as $function_name) {
  69. $this->dbi->selectDb($db);
  70. $tmp_query = $this->dbi->getDefinition(
  71. $db,
  72. 'FUNCTION',
  73. $function_name
  74. );
  75. if ($tmp_query === null) {
  76. continue;
  77. }
  78. // collect for later display
  79. $GLOBALS['sql_query'] .= "\n" . $tmp_query;
  80. $this->dbi->selectDb($_POST['newname']);
  81. $this->dbi->query($tmp_query);
  82. }
  83. }
  84. /**
  85. * Create database before copy
  86. *
  87. * @return void
  88. */
  89. public function createDbBeforeCopy()
  90. {
  91. $local_query = 'CREATE DATABASE IF NOT EXISTS '
  92. . Util::backquote($_POST['newname']);
  93. if (isset($_POST['db_collation'])) {
  94. $local_query .= ' DEFAULT'
  95. . Util::getCharsetQueryPart($_POST['db_collation'] ?? '');
  96. }
  97. $local_query .= ';';
  98. $GLOBALS['sql_query'] .= $local_query;
  99. // save the original db name because Tracker.php which
  100. // may be called under $this->dbi->query() changes $GLOBALS['db']
  101. // for some statements, one of which being CREATE DATABASE
  102. $original_db = $GLOBALS['db'];
  103. $this->dbi->query($local_query);
  104. $GLOBALS['db'] = $original_db;
  105. // Set the SQL mode to NO_AUTO_VALUE_ON_ZERO to prevent MySQL from creating
  106. // export statements it cannot import
  107. $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
  108. $this->dbi->query($sql_set_mode);
  109. // rebuild the database list because Table::moveCopy
  110. // checks in this list if the target db exists
  111. $GLOBALS['dblist']->databases->build();
  112. }
  113. /**
  114. * Get views as an array and create SQL view stand-in
  115. *
  116. * @param array $tables_full array of all tables in given db or dbs
  117. * @param ExportSql $export_sql_plugin export plugin instance
  118. * @param string $db database name
  119. *
  120. * @return array
  121. */
  122. public function getViewsAndCreateSqlViewStandIn(
  123. array $tables_full,
  124. $export_sql_plugin,
  125. $db
  126. ) {
  127. $views = [];
  128. foreach ($tables_full as $each_table => $tmp) {
  129. // to be able to rename a db containing views,
  130. // first all the views are collected and a stand-in is created
  131. // the real views are created after the tables
  132. if (! $this->dbi->getTable($db, (string) $each_table)->isView()) {
  133. continue;
  134. }
  135. // If view exists, and 'add drop view' is selected: Drop it!
  136. if ($_POST['what'] !== 'nocopy'
  137. && isset($_POST['drop_if_exists'])
  138. && $_POST['drop_if_exists'] === 'true'
  139. ) {
  140. $drop_query = 'DROP VIEW IF EXISTS '
  141. . Util::backquote($_POST['newname']) . '.'
  142. . Util::backquote($each_table);
  143. $this->dbi->query($drop_query);
  144. $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
  145. }
  146. $views[] = $each_table;
  147. // Create stand-in definition to resolve view dependencies
  148. $sql_view_standin = $export_sql_plugin->getTableDefStandIn(
  149. $db,
  150. $each_table,
  151. "\n"
  152. );
  153. $this->dbi->selectDb($_POST['newname']);
  154. $this->dbi->query($sql_view_standin);
  155. $GLOBALS['sql_query'] .= "\n" . $sql_view_standin;
  156. }
  157. return $views;
  158. }
  159. /**
  160. * Get sql query for copy/rename table and boolean for whether copy/rename or not
  161. *
  162. * @param array $tables_full array of all tables in given db or dbs
  163. * @param bool $move whether database name is empty or not
  164. * @param string $db database name
  165. *
  166. * @return array SQL queries for the constraints
  167. */
  168. public function copyTables(array $tables_full, $move, $db)
  169. {
  170. $sqlContraints = [];
  171. foreach ($tables_full as $each_table => $tmp) {
  172. // skip the views; we have created stand-in definitions
  173. if ($this->dbi->getTable($db, (string) $each_table)->isView()) {
  174. continue;
  175. }
  176. // value of $what for this table only
  177. $this_what = $_POST['what'];
  178. // do not copy the data from a Merge table
  179. // note: on the calling FORM, 'data' means 'structure and data'
  180. if ($this->dbi->getTable($db, (string) $each_table)->isMerge()) {
  181. if ($this_what === 'data') {
  182. $this_what = 'structure';
  183. }
  184. if ($this_what === 'dataonly') {
  185. $this_what = 'nocopy';
  186. }
  187. }
  188. if ($this_what === 'nocopy') {
  189. continue;
  190. }
  191. // keep the triggers from the original db+table
  192. // (third param is empty because delimiters are only intended
  193. // for importing via the mysql client or our Import feature)
  194. $triggers = $this->dbi->getTriggers($db, (string) $each_table, '');
  195. if (! Table::moveCopy(
  196. $db,
  197. $each_table,
  198. $_POST['newname'],
  199. $each_table,
  200. ($this_what ?? 'data'),
  201. $move,
  202. 'db_copy'
  203. )) {
  204. $GLOBALS['_error'] = true;
  205. break;
  206. }
  207. // apply the triggers to the destination db+table
  208. if ($triggers) {
  209. $this->dbi->selectDb($_POST['newname']);
  210. foreach ($triggers as $trigger) {
  211. $this->dbi->query($trigger['create']);
  212. $GLOBALS['sql_query'] .= "\n" . $trigger['create'] . ';';
  213. }
  214. }
  215. // this does not apply to a rename operation
  216. if (! isset($_POST['add_constraints'])
  217. || empty($GLOBALS['sql_constraints_query'])
  218. ) {
  219. continue;
  220. }
  221. $sqlContraints[] = $GLOBALS['sql_constraints_query'];
  222. unset($GLOBALS['sql_constraints_query']);
  223. }
  224. return $sqlContraints;
  225. }
  226. /**
  227. * Run the EVENT definition for selected database
  228. *
  229. * to avoid selecting alternatively the current and new db
  230. * we would need to modify the CREATE definitions to qualify
  231. * the db name
  232. *
  233. * @param string $db database name
  234. *
  235. * @return void
  236. */
  237. public function runEventDefinitionsForDb($db)
  238. {
  239. $event_names = $this->dbi->fetchResult(
  240. 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \''
  241. . $this->dbi->escapeString($db) . '\';'
  242. );
  243. if (! $event_names) {
  244. return;
  245. }
  246. foreach ($event_names as $event_name) {
  247. $this->dbi->selectDb($db);
  248. $tmp_query = $this->dbi->getDefinition($db, 'EVENT', $event_name);
  249. // collect for later display
  250. $GLOBALS['sql_query'] .= "\n" . $tmp_query;
  251. $this->dbi->selectDb($_POST['newname']);
  252. $this->dbi->query($tmp_query);
  253. }
  254. }
  255. /**
  256. * Handle the views, return the boolean value whether table rename/copy or not
  257. *
  258. * @param array $views views as an array
  259. * @param bool $move whether database name is empty or not
  260. * @param string $db database name
  261. *
  262. * @return void
  263. */
  264. public function handleTheViews(array $views, $move, $db)
  265. {
  266. // temporarily force to add DROP IF EXIST to CREATE VIEW query,
  267. // to remove stand-in VIEW that was created earlier
  268. // ( $_POST['drop_if_exists'] is used in moveCopy() )
  269. if (isset($_POST['drop_if_exists'])) {
  270. $temp_drop_if_exists = $_POST['drop_if_exists'];
  271. }
  272. $_POST['drop_if_exists'] = 'true';
  273. foreach ($views as $view) {
  274. $copying_succeeded = Table::moveCopy(
  275. $db,
  276. $view,
  277. $_POST['newname'],
  278. $view,
  279. 'structure',
  280. $move,
  281. 'db_copy'
  282. );
  283. if (! $copying_succeeded) {
  284. $GLOBALS['_error'] = true;
  285. break;
  286. }
  287. }
  288. unset($_POST['drop_if_exists']);
  289. if (! isset($temp_drop_if_exists)) {
  290. return;
  291. }
  292. // restore previous value
  293. $_POST['drop_if_exists'] = $temp_drop_if_exists;
  294. }
  295. /**
  296. * Adjust the privileges after Renaming the db
  297. *
  298. * @param string $oldDb Database name before renaming
  299. * @param string $newname New Database name requested
  300. *
  301. * @return void
  302. */
  303. public function adjustPrivilegesMoveDb($oldDb, $newname)
  304. {
  305. if (! $GLOBALS['db_priv'] || ! $GLOBALS['table_priv']
  306. || ! $GLOBALS['col_priv'] || ! $GLOBALS['proc_priv']
  307. || ! $GLOBALS['is_reload_priv']
  308. ) {
  309. return;
  310. }
  311. $this->dbi->selectDb('mysql');
  312. $newname = str_replace('_', '\_', $newname);
  313. $oldDb = str_replace('_', '\_', $oldDb);
  314. // For Db specific privileges
  315. $query_db_specific = 'UPDATE ' . Util::backquote('db')
  316. . 'SET Db = \'' . $this->dbi->escapeString($newname)
  317. . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
  318. $this->dbi->query($query_db_specific);
  319. // For table specific privileges
  320. $query_table_specific = 'UPDATE ' . Util::backquote('tables_priv')
  321. . 'SET Db = \'' . $this->dbi->escapeString($newname)
  322. . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
  323. $this->dbi->query($query_table_specific);
  324. // For column specific privileges
  325. $query_col_specific = 'UPDATE ' . Util::backquote('columns_priv')
  326. . 'SET Db = \'' . $this->dbi->escapeString($newname)
  327. . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
  328. $this->dbi->query($query_col_specific);
  329. // For procedures specific privileges
  330. $query_proc_specific = 'UPDATE ' . Util::backquote('procs_priv')
  331. . 'SET Db = \'' . $this->dbi->escapeString($newname)
  332. . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
  333. $this->dbi->query($query_proc_specific);
  334. // Finally FLUSH the new privileges
  335. $flush_query = 'FLUSH PRIVILEGES;';
  336. $this->dbi->query($flush_query);
  337. }
  338. /**
  339. * Adjust the privileges after Copying the db
  340. *
  341. * @param string $oldDb Database name before copying
  342. * @param string $newname New Database name requested
  343. *
  344. * @return void
  345. */
  346. public function adjustPrivilegesCopyDb($oldDb, $newname)
  347. {
  348. if (! $GLOBALS['db_priv'] || ! $GLOBALS['table_priv']
  349. || ! $GLOBALS['col_priv'] || ! $GLOBALS['proc_priv']
  350. || ! $GLOBALS['is_reload_priv']
  351. ) {
  352. return;
  353. }
  354. $this->dbi->selectDb('mysql');
  355. $newname = str_replace('_', '\_', $newname);
  356. $oldDb = str_replace('_', '\_', $oldDb);
  357. $query_db_specific_old = 'SELECT * FROM '
  358. . Util::backquote('db') . ' WHERE '
  359. . 'Db = "' . $oldDb . '";';
  360. $old_privs_db = $this->dbi->fetchResult($query_db_specific_old, 0);
  361. foreach ($old_privs_db as $old_priv) {
  362. $newDb_db_privs_query = 'INSERT INTO ' . Util::backquote('db')
  363. . ' VALUES("' . $old_priv[0] . '", "' . $newname . '"';
  364. $privCount = count($old_priv);
  365. for ($i = 2; $i < $privCount; $i++) {
  366. $newDb_db_privs_query .= ', "' . $old_priv[$i] . '"';
  367. }
  368. $newDb_db_privs_query .= ')';
  369. $this->dbi->query($newDb_db_privs_query);
  370. }
  371. // For Table Specific privileges
  372. $query_table_specific_old = 'SELECT * FROM '
  373. . Util::backquote('tables_priv') . ' WHERE '
  374. . 'Db = "' . $oldDb . '";';
  375. $old_privs_table = $this->dbi->fetchResult(
  376. $query_table_specific_old,
  377. 0
  378. );
  379. foreach ($old_privs_table as $old_priv) {
  380. $newDb_table_privs_query = 'INSERT INTO ' . Util::backquote(
  381. 'tables_priv'
  382. ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
  383. . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
  384. . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '", "'
  385. . $old_priv[7] . '");';
  386. $this->dbi->query($newDb_table_privs_query);
  387. }
  388. // For Column Specific privileges
  389. $query_col_specific_old = 'SELECT * FROM '
  390. . Util::backquote('columns_priv') . ' WHERE '
  391. . 'Db = "' . $oldDb . '";';
  392. $old_privs_col = $this->dbi->fetchResult(
  393. $query_col_specific_old,
  394. 0
  395. );
  396. foreach ($old_privs_col as $old_priv) {
  397. $newDb_col_privs_query = 'INSERT INTO ' . Util::backquote(
  398. 'columns_priv'
  399. ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
  400. . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
  401. . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '");';
  402. $this->dbi->query($newDb_col_privs_query);
  403. }
  404. // For Procedure Specific privileges
  405. $query_proc_specific_old = 'SELECT * FROM '
  406. . Util::backquote('procs_priv') . ' WHERE '
  407. . 'Db = "' . $oldDb . '";';
  408. $old_privs_proc = $this->dbi->fetchResult(
  409. $query_proc_specific_old,
  410. 0
  411. );
  412. foreach ($old_privs_proc as $old_priv) {
  413. $newDb_proc_privs_query = 'INSERT INTO ' . Util::backquote(
  414. 'procs_priv'
  415. ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
  416. . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
  417. . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '", "'
  418. . $old_priv[7] . '");';
  419. $this->dbi->query($newDb_proc_privs_query);
  420. }
  421. // Finally FLUSH the new privileges
  422. $flush_query = 'FLUSH PRIVILEGES;';
  423. $this->dbi->query($flush_query);
  424. }
  425. /**
  426. * Create all accumulated constraints
  427. *
  428. * @param array $sqlConstratints array of sql constraints for the database
  429. *
  430. * @return void
  431. */
  432. public function createAllAccumulatedConstraints(array $sqlConstratints)
  433. {
  434. $this->dbi->selectDb($_POST['newname']);
  435. foreach ($sqlConstratints as $one_query) {
  436. $this->dbi->query($one_query);
  437. // and prepare to display them
  438. $GLOBALS['sql_query'] .= "\n" . $one_query;
  439. }
  440. }
  441. /**
  442. * Duplicate the bookmarks for the db (done once for each db)
  443. *
  444. * @param bool $_error whether table rename/copy or not
  445. * @param string $db database name
  446. *
  447. * @return void
  448. */
  449. public function duplicateBookmarks($_error, $db)
  450. {
  451. if ($_error || $db == $_POST['newname']) {
  452. return;
  453. }
  454. $get_fields = [
  455. 'user',
  456. 'label',
  457. 'query',
  458. ];
  459. $where_fields = ['dbase' => $db];
  460. $new_fields = ['dbase' => $_POST['newname']];
  461. Table::duplicateInfo(
  462. 'bookmarkwork',
  463. 'bookmark',
  464. $get_fields,
  465. $where_fields,
  466. $new_fields
  467. );
  468. }
  469. /**
  470. * Get array of possible row formats
  471. *
  472. * @return array
  473. */
  474. public function getPossibleRowFormat()
  475. {
  476. // the outer array is for engines, the inner array contains the dropdown
  477. // option values as keys then the dropdown option labels
  478. $possible_row_formats = [
  479. 'ARCHIVE' => ['COMPRESSED' => 'COMPRESSED'],
  480. 'ARIA' => [
  481. 'FIXED' => 'FIXED',
  482. 'DYNAMIC' => 'DYNAMIC',
  483. 'PAGE' => 'PAGE',
  484. ],
  485. 'MARIA' => [
  486. 'FIXED' => 'FIXED',
  487. 'DYNAMIC' => 'DYNAMIC',
  488. 'PAGE' => 'PAGE',
  489. ],
  490. 'MYISAM' => [
  491. 'FIXED' => 'FIXED',
  492. 'DYNAMIC' => 'DYNAMIC',
  493. ],
  494. 'PBXT' => [
  495. 'FIXED' => 'FIXED',
  496. 'DYNAMIC' => 'DYNAMIC',
  497. ],
  498. 'INNODB' => [
  499. 'COMPACT' => 'COMPACT',
  500. 'REDUNDANT' => 'REDUNDANT',
  501. ],
  502. ];
  503. /** @var Innodb $innodbEnginePlugin */
  504. $innodbEnginePlugin = StorageEngine::getEngine('Innodb');
  505. $innodbPluginVersion = $innodbEnginePlugin->getInnodbPluginVersion();
  506. if (! empty($innodbPluginVersion)) {
  507. $innodb_file_format = $innodbEnginePlugin->getInnodbFileFormat();
  508. } else {
  509. $innodb_file_format = '';
  510. }
  511. /**
  512. * Newer MySQL/MariaDB always return empty a.k.a '' on $innodb_file_format otherwise
  513. * old versions of MySQL/MariaDB must be returning something or not empty.
  514. * This patch is to support newer MySQL/MariaDB while also for backward compatibilities.
  515. */
  516. if (($innodb_file_format === 'Barracuda') || ($innodb_file_format == '')
  517. && $innodbEnginePlugin->supportsFilePerTable()
  518. ) {
  519. $possible_row_formats['INNODB']['DYNAMIC'] = 'DYNAMIC';
  520. $possible_row_formats['INNODB']['COMPRESSED'] = 'COMPRESSED';
  521. }
  522. return $possible_row_formats;
  523. }
  524. /**
  525. * @return array<string, string>
  526. */
  527. public function getPartitionMaintenanceChoices(): array
  528. {
  529. global $db, $table;
  530. $choices = [
  531. 'ANALYZE' => __('Analyze'),
  532. 'CHECK' => __('Check'),
  533. 'OPTIMIZE' => __('Optimize'),
  534. 'REBUILD' => __('Rebuild'),
  535. 'REPAIR' => __('Repair'),
  536. 'TRUNCATE' => __('Truncate'),
  537. ];
  538. $partitionMethod = Partition::getPartitionMethod($db, $table);
  539. // add COALESCE or DROP option to choices array depending on Partition method
  540. if ($partitionMethod === 'RANGE'
  541. || $partitionMethod === 'RANGE COLUMNS'
  542. || $partitionMethod === 'LIST'
  543. || $partitionMethod === 'LIST COLUMNS'
  544. ) {
  545. $choices['DROP'] = __('Drop');
  546. } else {
  547. $choices['COALESCE'] = __('Coalesce');
  548. }
  549. return $choices;
  550. }
  551. /**
  552. * @param array $urlParams Array of url parameters.
  553. * @param bool $hasRelationFeature If relation feature is enabled.
  554. *
  555. * @return array
  556. */
  557. public function getForeignersForReferentialIntegrityCheck(
  558. array $urlParams,
  559. $hasRelationFeature
  560. ): array {
  561. global $db, $table;
  562. if (! $hasRelationFeature) {
  563. return [];
  564. }
  565. $foreigners = [];
  566. $this->dbi->selectDb($db);
  567. $foreign = $this->relation->getForeigners($db, $table, '', 'internal');
  568. foreach ($foreign as $master => $arr) {
  569. $joinQuery = 'SELECT '
  570. . Util::backquote($table) . '.*'
  571. . ' FROM ' . Util::backquote($table)
  572. . ' LEFT JOIN '
  573. . Util::backquote($arr['foreign_db'])
  574. . '.'
  575. . Util::backquote($arr['foreign_table']);
  576. if ($arr['foreign_table'] == $table) {
  577. $foreignTable = $table . '1';
  578. $joinQuery .= ' AS ' . Util::backquote($foreignTable);
  579. } else {
  580. $foreignTable = $arr['foreign_table'];
  581. }
  582. $joinQuery .= ' ON '
  583. . Util::backquote($table) . '.'
  584. . Util::backquote($master)
  585. . ' = '
  586. . Util::backquote($arr['foreign_db'])
  587. . '.'
  588. . Util::backquote($foreignTable) . '.'
  589. . Util::backquote($arr['foreign_field'])
  590. . ' WHERE '
  591. . Util::backquote($arr['foreign_db'])
  592. . '.'
  593. . Util::backquote($foreignTable) . '.'
  594. . Util::backquote($arr['foreign_field'])
  595. . ' IS NULL AND '
  596. . Util::backquote($table) . '.'
  597. . Util::backquote($master)
  598. . ' IS NOT NULL';
  599. $thisUrlParams = array_merge(
  600. $urlParams,
  601. [
  602. 'sql_query' => $joinQuery,
  603. 'sql_signature' => Core::signSqlQuery($joinQuery),
  604. ]
  605. );
  606. $foreigners[] = [
  607. 'params' => $thisUrlParams,
  608. 'master' => $master,
  609. 'db' => $arr['foreign_db'],
  610. 'table' => $arr['foreign_table'],
  611. 'field' => $arr['foreign_field'],
  612. ];
  613. }
  614. return $foreigners;
  615. }
  616. /**
  617. * Reorder table based on request params
  618. *
  619. * @return array SQL query and result
  620. */
  621. public function getQueryAndResultForReorderingTable()
  622. {
  623. $sql_query = 'ALTER TABLE '
  624. . Util::backquote($GLOBALS['table'])
  625. . ' ORDER BY '
  626. . Util::backquote(urldecode($_POST['order_field']));
  627. if (isset($_POST['order_order'])
  628. && $_POST['order_order'] === 'desc'
  629. ) {
  630. $sql_query .= ' DESC';
  631. } else {
  632. $sql_query .= ' ASC';
  633. }
  634. $sql_query .= ';';
  635. $result = $this->dbi->query($sql_query);
  636. return [
  637. $sql_query,
  638. $result,
  639. ];
  640. }
  641. /**
  642. * Get table alters array
  643. *
  644. * @param Table $pma_table The Table object
  645. * @param string $pack_keys pack keys
  646. * @param string $checksum value of checksum
  647. * @param string $page_checksum value of page checksum
  648. * @param string $delay_key_write delay key write
  649. * @param string $row_format row format
  650. * @param string $newTblStorageEngine table storage engine
  651. * @param string $transactional value of transactional
  652. * @param string $tbl_collation collation of the table
  653. *
  654. * @return array
  655. */
  656. public function getTableAltersArray(
  657. $pma_table,
  658. $pack_keys,
  659. $checksum,
  660. $page_checksum,
  661. $delay_key_write,
  662. $row_format,
  663. $newTblStorageEngine,
  664. $transactional,
  665. $tbl_collation
  666. ) {
  667. global $auto_increment;
  668. $table_alters = [];
  669. if (isset($_POST['comment'])
  670. && urldecode($_POST['prev_comment']) !== $_POST['comment']
  671. ) {
  672. $table_alters[] = 'COMMENT = \''
  673. . $this->dbi->escapeString($_POST['comment']) . '\'';
  674. }
  675. if (! empty($newTblStorageEngine)
  676. && mb_strtolower($newTblStorageEngine) !== mb_strtolower($GLOBALS['tbl_storage_engine'])
  677. ) {
  678. $table_alters[] = 'ENGINE = ' . $newTblStorageEngine;
  679. }
  680. if (! empty($_POST['tbl_collation'])
  681. && $_POST['tbl_collation'] !== $tbl_collation
  682. ) {
  683. $table_alters[] = 'DEFAULT '
  684. . Util::getCharsetQueryPart($_POST['tbl_collation'] ?? '');
  685. }
  686. if ($pma_table->isEngine(['MYISAM', 'ARIA', 'ISAM'])
  687. && isset($_POST['new_pack_keys'])
  688. && $_POST['new_pack_keys'] != (string) $pack_keys
  689. ) {
  690. $table_alters[] = 'pack_keys = ' . $_POST['new_pack_keys'];
  691. }
  692. $_POST['new_checksum'] = empty($_POST['new_checksum']) ? '0' : '1';
  693. if ($pma_table->isEngine(['MYISAM', 'ARIA'])
  694. && $_POST['new_checksum'] !== $checksum
  695. ) {
  696. $table_alters[] = 'checksum = ' . $_POST['new_checksum'];
  697. }
  698. $_POST['new_transactional']
  699. = empty($_POST['new_transactional']) ? '0' : '1';
  700. if ($pma_table->isEngine('ARIA')
  701. && $_POST['new_transactional'] !== $transactional
  702. ) {
  703. $table_alters[] = 'TRANSACTIONAL = ' . $_POST['new_transactional'];
  704. }
  705. $_POST['new_page_checksum']
  706. = empty($_POST['new_page_checksum']) ? '0' : '1';
  707. if ($pma_table->isEngine('ARIA')
  708. && $_POST['new_page_checksum'] !== $page_checksum
  709. ) {
  710. $table_alters[] = 'PAGE_CHECKSUM = ' . $_POST['new_page_checksum'];
  711. }
  712. $_POST['new_delay_key_write']
  713. = empty($_POST['new_delay_key_write']) ? '0' : '1';
  714. if ($pma_table->isEngine(['MYISAM', 'ARIA'])
  715. && $_POST['new_delay_key_write'] !== $delay_key_write
  716. ) {
  717. $table_alters[] = 'delay_key_write = ' . $_POST['new_delay_key_write'];
  718. }
  719. if ($pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT', 'ROCKSDB'])
  720. && ! empty($_POST['new_auto_increment'])
  721. && (! isset($auto_increment)
  722. || $_POST['new_auto_increment'] !== $auto_increment)
  723. && $_POST['new_auto_increment'] !== $_POST['hidden_auto_increment']
  724. ) {
  725. $table_alters[] = 'auto_increment = '
  726. . $this->dbi->escapeString($_POST['new_auto_increment']);
  727. }
  728. if (! empty($_POST['new_row_format'])) {
  729. $newRowFormat = $_POST['new_row_format'];
  730. $newRowFormatLower = mb_strtolower($newRowFormat);
  731. if ($pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT'])
  732. && (strlen($row_format) === 0
  733. || $newRowFormatLower !== mb_strtolower($row_format))
  734. ) {
  735. $table_alters[] = 'ROW_FORMAT = '
  736. . $this->dbi->escapeString($newRowFormat);
  737. }
  738. }
  739. return $table_alters;
  740. }
  741. /**
  742. * Get warning messages array
  743. *
  744. * @return array
  745. */
  746. public function getWarningMessagesArray()
  747. {
  748. $warning_messages = [];
  749. foreach ($this->dbi->getWarnings() as $warning) {
  750. // In MariaDB 5.1.44, when altering a table from Maria to MyISAM
  751. // and if TRANSACTIONAL was set, the system reports an error;
  752. // I discussed with a Maria developer and he agrees that this
  753. // should not be reported with a Level of Error, so here
  754. // I just ignore it. But there are other 1478 messages
  755. // that it's better to show.
  756. if (isset($_POST['new_tbl_storage_engine'])
  757. && $_POST['new_tbl_storage_engine'] === 'MyISAM'
  758. && $warning['Code'] == '1478'
  759. && $warning['Level'] === 'Error'
  760. ) {
  761. continue;
  762. }
  763. $warning_messages[] = $warning['Level'] . ': #' . $warning['Code']
  764. . ' ' . $warning['Message'];
  765. }
  766. return $warning_messages;
  767. }
  768. /**
  769. * Get SQL query and result after ran this SQL query for a partition operation
  770. * has been requested by the user
  771. *
  772. * @return array $sql_query, $result
  773. */
  774. public function getQueryAndResultForPartition()
  775. {
  776. $sql_query = 'ALTER TABLE '
  777. . Util::backquote($GLOBALS['table']) . ' '
  778. . $_POST['partition_operation']
  779. . ' PARTITION ';
  780. if ($_POST['partition_operation'] === 'COALESCE') {
  781. $sql_query .= count($_POST['partition_name']);
  782. } else {
  783. $sql_query .= implode(', ', $_POST['partition_name']) . ';';
  784. }
  785. $result = $this->dbi->query($sql_query);
  786. return [
  787. $sql_query,
  788. $result,
  789. ];
  790. }
  791. /**
  792. * Adjust the privileges after renaming/moving a table
  793. *
  794. * @param string $oldDb Database name before table renaming/moving table
  795. * @param string $oldTable Table name before table renaming/moving table
  796. * @param string $newDb Database name after table renaming/ moving table
  797. * @param string $newTable Table name after table renaming/moving table
  798. *
  799. * @return void
  800. */
  801. public function adjustPrivilegesRenameOrMoveTable($oldDb, $oldTable, $newDb, $newTable)
  802. {
  803. if (! $GLOBALS['table_priv'] || ! $GLOBALS['col_priv']
  804. || ! $GLOBALS['is_reload_priv']
  805. ) {
  806. return;
  807. }
  808. $this->dbi->selectDb('mysql');
  809. // For table specific privileges
  810. $query_table_specific = 'UPDATE ' . Util::backquote('tables_priv')
  811. . 'SET Db = \'' . $this->dbi->escapeString($newDb)
  812. . '\', Table_name = \'' . $this->dbi->escapeString($newTable)
  813. . '\' where Db = \'' . $this->dbi->escapeString($oldDb)
  814. . '\' AND Table_name = \'' . $this->dbi->escapeString($oldTable)
  815. . '\';';
  816. $this->dbi->query($query_table_specific);
  817. // For column specific privileges
  818. $query_col_specific = 'UPDATE ' . Util::backquote('columns_priv')
  819. . 'SET Db = \'' . $this->dbi->escapeString($newDb)
  820. . '\', Table_name = \'' . $this->dbi->escapeString($newTable)
  821. . '\' where Db = \'' . $this->dbi->escapeString($oldDb)
  822. . '\' AND Table_name = \'' . $this->dbi->escapeString($oldTable)
  823. . '\';';
  824. $this->dbi->query($query_col_specific);
  825. // Finally FLUSH the new privileges
  826. $flush_query = 'FLUSH PRIVILEGES;';
  827. $this->dbi->query($flush_query);
  828. }
  829. /**
  830. * Adjust the privileges after copying a table
  831. *
  832. * @param string $oldDb Database name before table copying
  833. * @param string $oldTable Table name before table copying
  834. * @param string $newDb Database name after table copying
  835. * @param string $newTable Table name after table copying
  836. *
  837. * @return void
  838. */
  839. public function adjustPrivilegesCopyTable($oldDb, $oldTable, $newDb, $newTable)
  840. {
  841. if (! $GLOBALS['table_priv'] || ! $GLOBALS['col_priv']
  842. || ! $GLOBALS['is_reload_priv']
  843. ) {
  844. return;
  845. }
  846. $this->dbi->selectDb('mysql');
  847. // For Table Specific privileges
  848. $query_table_specific_old = 'SELECT * FROM '
  849. . Util::backquote('tables_priv') . ' where '
  850. . 'Db = "' . $oldDb . '" AND Table_name = "' . $oldTable . '";';
  851. $old_privs_table = $this->dbi->fetchResult(
  852. $query_table_specific_old,
  853. 0
  854. );
  855. foreach ($old_privs_table as $old_priv) {
  856. $newDb_table_privs_query = 'INSERT INTO '
  857. . Util::backquote('tables_priv') . ' VALUES("'
  858. . $old_priv[0] . '", "' . $newDb . '", "' . $old_priv[2] . '", "'
  859. . $newTable . '", "' . $old_priv[4] . '", "' . $old_priv[5]
  860. . '", "' . $old_priv[6] . '", "' . $old_priv[7] . '");';
  861. $this->dbi->query($newDb_table_privs_query);
  862. }
  863. // For Column Specific privileges
  864. $query_col_specific_old = 'SELECT * FROM '
  865. . Util::backquote('columns_priv') . ' WHERE '
  866. . 'Db = "' . $oldDb . '" AND Table_name = "' . $oldTable . '";';
  867. $old_privs_col = $this->dbi->fetchResult(
  868. $query_col_specific_old,
  869. 0
  870. );
  871. foreach ($old_privs_col as $old_priv) {
  872. $newDb_col_privs_query = 'INSERT INTO '
  873. . Util::backquote('columns_priv') . ' VALUES("'
  874. . $old_priv[0] . '", "' . $newDb . '", "' . $old_priv[2] . '", "'
  875. . $newTable . '", "' . $old_priv[4] . '", "' . $old_priv[5]
  876. . '", "' . $old_priv[6] . '");';
  877. $this->dbi->query($newDb_col_privs_query);
  878. }
  879. // Finally FLUSH the new privileges
  880. $flush_query = 'FLUSH PRIVILEGES;';
  881. $this->dbi->query($flush_query);
  882. }
  883. /**
  884. * Change all collations and character sets of all columns in table
  885. *
  886. * @param string $db Database name
  887. * @param string $table Table name
  888. * @param string $tbl_collation Collation Name
  889. *
  890. * @return void
  891. */
  892. public function changeAllColumnsCollation($db, $table, $tbl_collation)
  893. {
  894. $this->dbi->selectDb($db);
  895. $change_all_collations_query = 'ALTER TABLE '
  896. . Util::backquote($table)
  897. . ' CONVERT TO';
  898. [$charset] = explode('_', $tbl_collation);
  899. $change_all_collations_query .= ' CHARACTER SET ' . $charset
  900. . ($charset == $tbl_collation ? '' : ' COLLATE ' . $tbl_collation);
  901. $this->dbi->query($change_all_collations_query);
  902. }
  903. /**
  904. * Move or copy a table
  905. *
  906. * @param string $db current database name
  907. * @param string $table current table name
  908. */
  909. public function moveOrCopyTable($db, $table): Message
  910. {
  911. /**
  912. * Selects the database to work with
  913. */
  914. $this->dbi->selectDb($db);
  915. /**
  916. * $_POST['target_db'] could be empty in case we came from an input field
  917. * (when there are many databases, no drop-down)
  918. */
  919. if (empty($_POST['target_db'])) {
  920. $_POST['target_db'] = $db;
  921. }
  922. /**
  923. * A target table name has been sent to this script -> do the work
  924. */
  925. if (Core::isValid($_POST['new_name'])) {
  926. if ($db == $_POST['target_db'] && $table == $_POST['new_name']) {
  927. if (isset($_POST['submit_move'])) {
  928. $message = Message::error(__('Can\'t move table to same one!'));
  929. } else {
  930. $message = Message::error(__('Can\'t copy table to same one!'));
  931. }
  932. } else {
  933. Table::moveCopy(
  934. $db,
  935. $table,
  936. $_POST['target_db'],
  937. $_POST['new_name'],
  938. $_POST['what'],
  939. isset($_POST['submit_move']),
  940. 'one_table'
  941. );
  942. if (isset($_POST['adjust_privileges'])
  943. && ! empty($_POST['adjust_privileges'])
  944. ) {
  945. if (isset($_POST['submit_move'])) {
  946. $this->adjustPrivilegesRenameOrMoveTable(
  947. $db,
  948. $table,
  949. $_POST['target_db'],
  950. $_POST['new_name']
  951. );
  952. } else {
  953. $this->adjustPrivilegesCopyTable(
  954. $db,
  955. $table,
  956. $_POST['target_db'],
  957. $_POST['new_name']
  958. );
  959. }
  960. if (isset($_POST['submit_move'])) {
  961. $message = Message::success(
  962. __(
  963. 'Table %s has been moved to %s. Privileges have been '
  964. . 'adjusted.'
  965. )
  966. );
  967. } else {
  968. $message = Message::success(
  969. __(
  970. 'Table %s has been copied to %s. Privileges have been '
  971. . 'adjusted.'
  972. )
  973. );
  974. }
  975. } else {
  976. if (isset($_POST['submit_move'])) {
  977. $message = Message::success(
  978. __('Table %s has been moved to %s.')
  979. );
  980. } else {
  981. $message = Message::success(
  982. __('Table %s has been copied to %s.')
  983. );
  984. }
  985. }
  986. $old = Util::backquote($db) . '.'
  987. . Util::backquote($table);
  988. $message->addParam($old);
  989. $new_name = $_POST['new_name'];
  990. if ($this->dbi->getLowerCaseNames() === '1') {
  991. $new_name = strtolower($new_name);
  992. }
  993. $GLOBALS['table'] = $new_name;
  994. $new = Util::backquote($_POST['target_db']) . '.'
  995. . Util::backquote($new_name);
  996. $message->addParam($new);
  997. }
  998. } else {
  999. /**
  1000. * No new name for the table!
  1001. */
  1002. $message = Message::error(__('The table name is empty!'));
  1003. }
  1004. return $message;
  1005. }
  1006. }