ImportController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Controllers;
  4. use PhpMyAdmin\Bookmark;
  5. use PhpMyAdmin\Console;
  6. use PhpMyAdmin\Core;
  7. use PhpMyAdmin\DatabaseInterface;
  8. use PhpMyAdmin\Encoding;
  9. use PhpMyAdmin\File;
  10. use PhpMyAdmin\Html\Generator;
  11. use PhpMyAdmin\Import;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\ParseAnalyze;
  14. use PhpMyAdmin\Plugins;
  15. use PhpMyAdmin\Plugins\ImportPlugin;
  16. use PhpMyAdmin\Response;
  17. use PhpMyAdmin\Sql;
  18. use PhpMyAdmin\Template;
  19. use PhpMyAdmin\Url;
  20. use PhpMyAdmin\Util;
  21. use Throwable;
  22. use function define;
  23. use function htmlspecialchars;
  24. use function in_array;
  25. use function ini_get;
  26. use function ini_set;
  27. use function intval;
  28. use function is_array;
  29. use function is_link;
  30. use function is_uploaded_file;
  31. use function mb_strlen;
  32. use function mb_strtolower;
  33. use function preg_match;
  34. use function preg_quote;
  35. use function preg_replace;
  36. use function sprintf;
  37. use function strlen;
  38. use function substr;
  39. use function time;
  40. use function trim;
  41. final class ImportController extends AbstractController
  42. {
  43. /** @var Import */
  44. private $import;
  45. /** @var Sql */
  46. private $sql;
  47. /** @var DatabaseInterface */
  48. private $dbi;
  49. /**
  50. * @param Response $response
  51. * @param DatabaseInterface $dbi
  52. */
  53. public function __construct($response, Template $template, Import $import, Sql $sql, $dbi)
  54. {
  55. parent::__construct($response, $template);
  56. $this->import = $import;
  57. $this->sql = $sql;
  58. $this->dbi = $dbi;
  59. }
  60. public function index(): void
  61. {
  62. global $cfg, $collation_connection, $db, $import_type, $table, $goto, $display_query, $PMA_Theme;
  63. global $format, $local_import_file, $ajax_reload, $import_text, $sql_query, $message, $err_url, $url_params;
  64. global $memory_limit, $read_limit, $finished, $offset, $charset_conversion, $charset_of_file;
  65. global $timestamp, $maximum_time, $timeout_passed, $import_file, $go_sql, $sql_file, $error, $max_sql_len, $msg;
  66. global $sql_query_disabled, $executed_queries, $run_query, $reset_charset, $bookmark_created;
  67. global $result, $import_file_name, $sql_data, $import_notice, $read_multiply, $my_die, $active_page;
  68. global $show_as_php, $reload, $charset_connection, $is_js_confirmed, $MAX_FILE_SIZE, $message_to_show;
  69. global $noplugin, $skip_queries;
  70. $charset_of_file = $_POST['charset_of_file'] ?? null;
  71. $format = $_POST['format'] ?? '';
  72. $import_type = $_POST['import_type'] ?? null;
  73. $is_js_confirmed = $_POST['is_js_confirmed'] ?? null;
  74. $MAX_FILE_SIZE = $_POST['MAX_FILE_SIZE'] ?? null;
  75. $message_to_show = $_POST['message_to_show'] ?? null;
  76. $noplugin = $_POST['noplugin'] ?? null;
  77. $skip_queries = $_POST['skip_queries'] ?? null;
  78. $local_import_file = $_POST['local_import_file'] ?? null;
  79. $show_as_php = $_POST['show_as_php'] ?? null;
  80. /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
  81. if ($format === 'ldi') {
  82. define('PMA_ENABLE_LDI', 1);
  83. }
  84. // If there is a request to 'Simulate DML'.
  85. if (isset($_POST['simulate_dml'])) {
  86. $this->import->handleSimulateDmlRequest();
  87. return;
  88. }
  89. // If it's a refresh console bookmarks request
  90. if (isset($_GET['console_bookmark_refresh'])) {
  91. $this->response->addJSON(
  92. 'console_message_bookmark',
  93. Console::getBookmarkContent()
  94. );
  95. return;
  96. }
  97. // If it's a console bookmark add request
  98. if (isset($_POST['console_bookmark_add'])) {
  99. if (! isset($_POST['label'], $_POST['db'], $_POST['bookmark_query'], $_POST['shared'])) {
  100. $this->response->addJSON('message', __('Incomplete params'));
  101. return;
  102. }
  103. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  104. if (! is_array($cfgBookmark)) {
  105. $cfgBookmark = [];
  106. }
  107. $bookmarkFields = [
  108. 'bkm_database' => $_POST['db'],
  109. 'bkm_user' => $cfgBookmark['user'],
  110. 'bkm_sql_query' => $_POST['bookmark_query'],
  111. 'bkm_label' => $_POST['label'],
  112. ];
  113. $isShared = ($_POST['shared'] === 'true');
  114. $bookmark = Bookmark::createBookmark(
  115. $this->dbi,
  116. $cfg['Server']['user'],
  117. $bookmarkFields,
  118. $isShared
  119. );
  120. if ($bookmark !== false && $bookmark->save()) {
  121. $this->response->addJSON('message', __('Succeeded'));
  122. $this->response->addJSON('data', $bookmarkFields);
  123. $this->response->addJSON('isShared', $isShared);
  124. } else {
  125. $this->response->addJSON('message', __('Failed'));
  126. }
  127. return;
  128. }
  129. // reset import messages for ajax request
  130. $_SESSION['Import_message']['message'] = null;
  131. $_SESSION['Import_message']['go_back_url'] = null;
  132. // default values
  133. $reload = false;
  134. // Use to identify current cycle is executing
  135. // a multiquery statement or stored routine
  136. if (! isset($_SESSION['is_multi_query'])) {
  137. $_SESSION['is_multi_query'] = false;
  138. }
  139. $ajax_reload = [];
  140. $import_text = '';
  141. // Are we just executing plain query or sql file?
  142. // (eg. non import, but query box/window run)
  143. if (! empty($sql_query)) {
  144. // apply values for parameters
  145. if (! empty($_POST['parameterized'])
  146. && ! empty($_POST['parameters'])
  147. && is_array($_POST['parameters'])
  148. ) {
  149. $parameters = $_POST['parameters'];
  150. foreach ($parameters as $parameter => $replacement) {
  151. $quoted = preg_quote($parameter, '/');
  152. // making sure that :param does not apply values to :param1
  153. $sql_query = preg_replace(
  154. '/' . $quoted . '([^a-zA-Z0-9_])/',
  155. $this->dbi->escapeString($replacement) . '${1}',
  156. $sql_query
  157. );
  158. // for parameters the appear at the end of the string
  159. $sql_query = preg_replace(
  160. '/' . $quoted . '$/',
  161. $this->dbi->escapeString($replacement),
  162. $sql_query
  163. );
  164. }
  165. }
  166. // run SQL query
  167. $import_text = $sql_query;
  168. $import_type = 'query';
  169. $format = 'sql';
  170. $_SESSION['sql_from_query_box'] = true;
  171. // If there is a request to ROLLBACK when finished.
  172. if (isset($_POST['rollback_query'])) {
  173. $this->import->handleRollbackRequest($import_text);
  174. }
  175. // refresh navigation and main panels
  176. if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
  177. $reload = true;
  178. $ajax_reload['reload'] = true;
  179. }
  180. // refresh navigation panel only
  181. if (preg_match(
  182. '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
  183. $sql_query
  184. )) {
  185. $ajax_reload['reload'] = true;
  186. }
  187. // do a dynamic reload if table is RENAMED
  188. // (by sending the instruction to the AJAX response handler)
  189. if (preg_match(
  190. '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
  191. $sql_query,
  192. $rename_table_names
  193. )) {
  194. $ajax_reload['reload'] = true;
  195. $ajax_reload['table_name'] = Util::unQuote(
  196. $rename_table_names[2]
  197. );
  198. }
  199. $sql_query = '';
  200. } elseif (! empty($sql_file)) {
  201. // run uploaded SQL file
  202. $import_file = $sql_file;
  203. $import_type = 'queryfile';
  204. $format = 'sql';
  205. unset($sql_file);
  206. } elseif (! empty($_POST['id_bookmark'])) {
  207. // run bookmark
  208. $import_type = 'query';
  209. $format = 'sql';
  210. }
  211. // If we didn't get any parameters, either user called this directly, or
  212. // upload limit has been reached, let's assume the second possibility.
  213. if ($_POST == [] && $_GET == []) {
  214. $message = Message::error(
  215. __(
  216. 'You probably tried to upload a file that is too large. Please refer ' .
  217. 'to %sdocumentation%s for a workaround for this limit.'
  218. )
  219. );
  220. $message->addParam('[doc@faq1-16]');
  221. $message->addParam('[/doc]');
  222. // so we can obtain the message
  223. $_SESSION['Import_message']['message'] = $message->getDisplay();
  224. $_SESSION['Import_message']['go_back_url'] = $goto;
  225. $this->response->setRequestStatus(false);
  226. $this->response->addJSON('message', $message);
  227. return; // the footer is displayed automatically
  228. }
  229. // Add console message id to response output
  230. if (isset($_POST['console_message_id'])) {
  231. $this->response->addJSON('console_message_id', $_POST['console_message_id']);
  232. }
  233. /**
  234. * Sets globals from $_POST patterns, for import plugins
  235. * We only need to load the selected plugin
  236. */
  237. if (! in_array(
  238. $format,
  239. [
  240. 'csv',
  241. 'ldi',
  242. 'mediawiki',
  243. 'ods',
  244. 'shp',
  245. 'sql',
  246. 'xml',
  247. ]
  248. )
  249. ) {
  250. // this should not happen for a normal user
  251. // but only during an attack
  252. Core::fatalError('Incorrect format parameter');
  253. }
  254. $post_patterns = [
  255. '/^force_file_/',
  256. '/^' . $format . '_/',
  257. ];
  258. Core::setPostAsGlobal($post_patterns);
  259. // Check needed parameters
  260. Util::checkParameters(['import_type', 'format']);
  261. // We don't want anything special in format
  262. $format = Core::securePath($format);
  263. if (strlen($table) > 0 && strlen($db) > 0) {
  264. $url_params = [
  265. 'db' => $db,
  266. 'table' => $table,
  267. ];
  268. } elseif (strlen($db) > 0) {
  269. $url_params = ['db' => $db];
  270. } else {
  271. $url_params = [];
  272. }
  273. // Create error and goto url
  274. if ($import_type === 'table') {
  275. $goto = Url::getFromRoute('/table/import');
  276. } elseif ($import_type === 'database') {
  277. $goto = Url::getFromRoute('/database/import');
  278. } elseif ($import_type === 'server') {
  279. $goto = Url::getFromRoute('/server/import');
  280. } elseif (empty($goto) || ! preg_match('@^index\.php$@i', $goto)) {
  281. if (strlen($table) > 0 && strlen($db) > 0) {
  282. $goto = Url::getFromRoute('/table/structure');
  283. } elseif (strlen($db) > 0) {
  284. $goto = Url::getFromRoute('/database/structure');
  285. } else {
  286. $goto = Url::getFromRoute('/server/sql');
  287. }
  288. }
  289. $err_url = $goto . Url::getCommon($url_params, '&');
  290. $_SESSION['Import_message']['go_back_url'] = $err_url;
  291. if (strlen($db) > 0) {
  292. $this->dbi->selectDb($db);
  293. }
  294. Util::setTimeLimit();
  295. if (! empty($cfg['MemoryLimit'])) {
  296. ini_set('memory_limit', $cfg['MemoryLimit']);
  297. }
  298. $timestamp = time();
  299. if (isset($_POST['allow_interrupt'])) {
  300. $maximum_time = ini_get('max_execution_time');
  301. } else {
  302. $maximum_time = 0;
  303. }
  304. // set default values
  305. $timeout_passed = false;
  306. $error = false;
  307. $read_multiply = 1;
  308. $finished = false;
  309. $offset = 0;
  310. $max_sql_len = 0;
  311. $sql_query = '';
  312. $sql_query_disabled = false;
  313. $go_sql = false;
  314. $executed_queries = 0;
  315. $run_query = true;
  316. $charset_conversion = false;
  317. $reset_charset = false;
  318. $bookmark_created = false;
  319. $msg = 'Sorry an unexpected error happened!';
  320. /** @var mixed|bool $result */
  321. $result = false;
  322. // Bookmark Support: get a query back from bookmark if required
  323. if (! empty($_POST['id_bookmark'])) {
  324. $id_bookmark = (int) $_POST['id_bookmark'];
  325. switch ($_POST['action_bookmark']) {
  326. case 0: // bookmarked query that have to be run
  327. $bookmark = Bookmark::get(
  328. $this->dbi,
  329. $cfg['Server']['user'],
  330. $db,
  331. $id_bookmark,
  332. 'id',
  333. isset($_POST['action_bookmark_all'])
  334. );
  335. if (! $bookmark instanceof Bookmark) {
  336. break;
  337. }
  338. if (! empty($_POST['bookmark_variable'])) {
  339. $import_text = $bookmark->applyVariables(
  340. $_POST['bookmark_variable']
  341. );
  342. } else {
  343. $import_text = $bookmark->getQuery();
  344. }
  345. // refresh navigation and main panels
  346. if (preg_match(
  347. '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
  348. $import_text
  349. )) {
  350. $reload = true;
  351. $ajax_reload['reload'] = true;
  352. }
  353. // refresh navigation panel only
  354. if (preg_match(
  355. '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
  356. $import_text
  357. )
  358. ) {
  359. $ajax_reload['reload'] = true;
  360. }
  361. break;
  362. case 1: // bookmarked query that have to be displayed
  363. $bookmark = Bookmark::get(
  364. $this->dbi,
  365. $cfg['Server']['user'],
  366. $db,
  367. $id_bookmark
  368. );
  369. if (! $bookmark instanceof Bookmark) {
  370. break;
  371. }
  372. $import_text = $bookmark->getQuery();
  373. if ($this->response->isAjax()) {
  374. $message = Message::success(__('Showing bookmark'));
  375. $this->response->setRequestStatus($message->isSuccess());
  376. $this->response->addJSON('message', $message);
  377. $this->response->addJSON('sql_query', $import_text);
  378. $this->response->addJSON('action_bookmark', $_POST['action_bookmark']);
  379. return;
  380. } else {
  381. $run_query = false;
  382. }
  383. break;
  384. case 2: // bookmarked query that have to be deleted
  385. $bookmark = Bookmark::get(
  386. $this->dbi,
  387. $cfg['Server']['user'],
  388. $db,
  389. $id_bookmark
  390. );
  391. if (! $bookmark instanceof Bookmark) {
  392. break;
  393. }
  394. $bookmark->delete();
  395. if ($this->response->isAjax()) {
  396. $message = Message::success(
  397. __('The bookmark has been deleted.')
  398. );
  399. $this->response->setRequestStatus($message->isSuccess());
  400. $this->response->addJSON('message', $message);
  401. $this->response->addJSON('action_bookmark', $_POST['action_bookmark']);
  402. $this->response->addJSON('id_bookmark', $id_bookmark);
  403. return;
  404. } else {
  405. $run_query = false;
  406. $error = true; // this is kind of hack to skip processing the query
  407. }
  408. break;
  409. }
  410. }
  411. // Do no run query if we show PHP code
  412. if (isset($show_as_php)) {
  413. $run_query = false;
  414. $go_sql = true;
  415. }
  416. // We can not read all at once, otherwise we can run out of memory
  417. $memory_limit = trim((string) ini_get('memory_limit'));
  418. // 2 MB as default
  419. if (empty($memory_limit)) {
  420. $memory_limit = 2 * 1024 * 1024;
  421. }
  422. // In case no memory limit we work on 10MB chunks
  423. if ($memory_limit == -1) {
  424. $memory_limit = 10 * 1024 * 1024;
  425. }
  426. // Calculate value of the limit
  427. $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
  428. if ($memoryUnit === 'm') {
  429. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
  430. } elseif ($memoryUnit === 'k') {
  431. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
  432. } elseif ($memoryUnit === 'g') {
  433. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
  434. } else {
  435. $memory_limit = (int) $memory_limit;
  436. }
  437. // Just to be sure, there might be lot of memory needed for uncompression
  438. $read_limit = $memory_limit / 8;
  439. // handle filenames
  440. if (isset($_FILES['import_file'])) {
  441. $import_file = $_FILES['import_file']['tmp_name'];
  442. $import_file_name = $_FILES['import_file']['name'];
  443. }
  444. if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
  445. // sanitize $local_import_file as it comes from a POST
  446. $local_import_file = Core::securePath($local_import_file);
  447. $import_file = Util::userDir($cfg['UploadDir'])
  448. . $local_import_file;
  449. /*
  450. * Do not allow symlinks to avoid security issues
  451. * (user can create symlink to file they can not access,
  452. * but phpMyAdmin can).
  453. */
  454. if (@is_link($import_file)) {
  455. $import_file = 'none';
  456. }
  457. } elseif (empty($import_file) || ! is_uploaded_file($import_file)) {
  458. $import_file = 'none';
  459. }
  460. // Do we have file to import?
  461. if ($import_file !== 'none' && ! $error) {
  462. /**
  463. * Handle file compression
  464. */
  465. $importHandle = new File($import_file);
  466. $importHandle->checkUploadedFile();
  467. if ($importHandle->isError()) {
  468. /** @var Message $errorMessage */
  469. $errorMessage = $importHandle->getError();
  470. $importHandle->close();
  471. $_SESSION['Import_message']['message'] = $errorMessage->getDisplay();
  472. $this->response->setRequestStatus(false);
  473. $this->response->addJSON('message', $errorMessage->getDisplay());
  474. $this->response->addHTML($errorMessage->getDisplay());
  475. return;
  476. }
  477. $importHandle->setDecompressContent(true);
  478. $importHandle->open();
  479. if ($importHandle->isError()) {
  480. /** @var Message $errorMessage */
  481. $errorMessage = $importHandle->getError();
  482. $importHandle->close();
  483. $_SESSION['Import_message']['message'] = $errorMessage->getDisplay();
  484. $this->response->setRequestStatus(false);
  485. $this->response->addJSON('message', $errorMessage->getDisplay());
  486. $this->response->addHTML($errorMessage->getDisplay());
  487. return;
  488. }
  489. } elseif (! $error && (! isset($import_text) || empty($import_text))) {
  490. $message = Message::error(
  491. __(
  492. 'No data was received to import. Either no file name was ' .
  493. 'submitted, or the file size exceeded the maximum size permitted ' .
  494. 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
  495. )
  496. );
  497. $_SESSION['Import_message']['message'] = $message->getDisplay();
  498. $this->response->setRequestStatus(false);
  499. $this->response->addJSON('message', $message->getDisplay());
  500. $this->response->addHTML($message->getDisplay());
  501. return;
  502. }
  503. // Convert the file's charset if necessary
  504. if (Encoding::isSupported() && isset($charset_of_file)) {
  505. if ($charset_of_file !== 'utf-8') {
  506. $charset_conversion = true;
  507. }
  508. } elseif (isset($charset_of_file) && $charset_of_file !== 'utf-8') {
  509. $this->dbi->query('SET NAMES \'' . $charset_of_file . '\'');
  510. // We can not show query in this case, it is in different charset
  511. $sql_query_disabled = true;
  512. $reset_charset = true;
  513. }
  514. // Something to skip? (because timeout has passed)
  515. if (! $error && isset($_POST['skip'])) {
  516. $original_skip = $skip = intval($_POST['skip']);
  517. while ($skip > 0 && ! $finished) {
  518. $this->import->getNextChunk($importHandle ?? null, $skip < $read_limit ? $skip : $read_limit);
  519. // Disable read progressivity, otherwise we eat all memory!
  520. $read_multiply = 1;
  521. $skip -= $read_limit;
  522. }
  523. unset($skip);
  524. }
  525. // This array contain the data like number of valid sql queries in the statement
  526. // and complete valid sql statement (which affected for rows)
  527. $sql_data = [
  528. 'valid_sql' => [],
  529. 'valid_queries' => 0,
  530. ];
  531. if (! $error) {
  532. /**
  533. * @var ImportPlugin $import_plugin
  534. */
  535. $import_plugin = Plugins::getPlugin(
  536. 'import',
  537. $format,
  538. 'libraries/classes/Plugins/Import/',
  539. $import_type
  540. );
  541. if ($import_plugin == null) {
  542. $message = Message::error(
  543. __('Could not load import plugins, please check your installation!')
  544. );
  545. $_SESSION['Import_message']['message'] = $message->getDisplay();
  546. $this->response->setRequestStatus(false);
  547. $this->response->addJSON('message', $message->getDisplay());
  548. $this->response->addHTML($message->getDisplay());
  549. return;
  550. }
  551. // Do the real import
  552. $default_fk_check = Util::handleDisableFKCheckInit();
  553. try {
  554. $import_plugin->doImport($importHandle ?? null, $sql_data);
  555. Util::handleDisableFKCheckCleanup($default_fk_check);
  556. } catch (Throwable $e) {
  557. Util::handleDisableFKCheckCleanup($default_fk_check);
  558. throw $e;
  559. }
  560. }
  561. if (isset($importHandle)) {
  562. $importHandle->close();
  563. }
  564. // Reset charset back, if we did some changes
  565. if ($reset_charset) {
  566. $this->dbi->query('SET CHARACTER SET ' . $charset_connection);
  567. $this->dbi->setCollation($collation_connection);
  568. }
  569. // Show correct message
  570. if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) {
  571. $message = Message::success(__('The bookmark has been deleted.'));
  572. $display_query = $import_text;
  573. $error = false; // unset error marker, it was used just to skip processing
  574. } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) {
  575. $message = Message::notice(__('Showing bookmark'));
  576. } elseif ($bookmark_created) {
  577. $special_message = '[br]' . sprintf(
  578. __('Bookmark %s has been created.'),
  579. htmlspecialchars($_POST['bkm_label'])
  580. );
  581. } elseif ($finished && ! $error) {
  582. // Do not display the query with message, we do it separately
  583. $display_query = ';';
  584. if ($import_type !== 'query') {
  585. $message = Message::success(
  586. '<em>'
  587. . _ngettext(
  588. 'Import has been successfully finished, %d query executed.',
  589. 'Import has been successfully finished, %d queries executed.',
  590. $executed_queries
  591. )
  592. . '</em>'
  593. );
  594. $message->addParam($executed_queries);
  595. if (! empty($import_notice)) {
  596. $message->addHtml($import_notice);
  597. }
  598. if (! empty($local_import_file)) {
  599. $message->addText('(' . $local_import_file . ')');
  600. } else {
  601. $message->addText('(' . $_FILES['import_file']['name'] . ')');
  602. }
  603. }
  604. }
  605. // Did we hit timeout? Tell it user.
  606. if ($timeout_passed) {
  607. $url_params['timeout_passed'] = '1';
  608. $url_params['offset'] = $offset;
  609. if (isset($local_import_file)) {
  610. $url_params['local_import_file'] = $local_import_file;
  611. }
  612. $importUrl = $err_url = $goto . Url::getCommon($url_params, '&');
  613. $message = Message::error(
  614. __(
  615. 'Script timeout passed, if you want to finish import,'
  616. . ' please %sresubmit the same file%s and import will resume.'
  617. )
  618. );
  619. $message->addParamHtml('<a href="' . $importUrl . '">');
  620. $message->addParamHtml('</a>');
  621. if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) {
  622. $message->addText(
  623. __(
  624. 'However on last run no data has been parsed,'
  625. . ' this usually means phpMyAdmin won\'t be able to'
  626. . ' finish this import unless you increase php time limits.'
  627. )
  628. );
  629. }
  630. }
  631. // if there is any message, copy it into $_SESSION as well,
  632. // so we can obtain it by AJAX call
  633. if (isset($message)) {
  634. $_SESSION['Import_message']['message'] = $message->getDisplay();
  635. }
  636. // Parse and analyze the query, for correct db and table name
  637. // in case of a query typed in the query window
  638. // (but if the query is too large, in case of an imported file, the parser
  639. // can choke on it so avoid parsing)
  640. $sqlLength = mb_strlen($sql_query);
  641. if ($sqlLength <= $cfg['MaxCharactersInDisplayedSQL']) {
  642. [
  643. $analyzed_sql_results,
  644. $db,
  645. $table_from_sql,
  646. ] = ParseAnalyze::sqlQuery($sql_query, $db);
  647. $reload = $analyzed_sql_results['reload'];
  648. $offset = $analyzed_sql_results['offset'];
  649. if ($table != $table_from_sql && ! empty($table_from_sql)) {
  650. $table = $table_from_sql;
  651. }
  652. }
  653. // There was an error?
  654. if (isset($my_die)) {
  655. foreach ($my_die as $key => $die) {
  656. Generator::mysqlDie(
  657. $die['error'],
  658. $die['sql'],
  659. false,
  660. $err_url,
  661. $error
  662. );
  663. }
  664. }
  665. if ($go_sql) {
  666. if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
  667. $_SESSION['is_multi_query'] = true;
  668. $sql_queries = $sql_data['valid_sql'];
  669. } else {
  670. $sql_queries = [$sql_query];
  671. }
  672. $html_output = '';
  673. foreach ($sql_queries as $sql_query) {
  674. // parse sql query
  675. [
  676. $analyzed_sql_results,
  677. $db,
  678. $table_from_sql,
  679. ] = ParseAnalyze::sqlQuery($sql_query, $db);
  680. $offset = $analyzed_sql_results['offset'];
  681. $reload = $analyzed_sql_results['reload'];
  682. // Check if User is allowed to issue a 'DROP DATABASE' Statement
  683. if ($this->sql->hasNoRightsToDropDatabase(
  684. $analyzed_sql_results,
  685. $cfg['AllowUserDropDatabase'],
  686. $this->dbi->isSuperUser()
  687. )) {
  688. Generator::mysqlDie(
  689. __('"DROP DATABASE" statements are disabled.'),
  690. '',
  691. false,
  692. $_SESSION['Import_message']['go_back_url']
  693. );
  694. return;
  695. }
  696. if ($table != $table_from_sql && ! empty($table_from_sql)) {
  697. $table = $table_from_sql;
  698. }
  699. $html_output .= $this->sql->executeQueryAndGetQueryResponse(
  700. $analyzed_sql_results, // analyzed_sql_results
  701. false, // is_gotofile
  702. $db, // db
  703. $table, // table
  704. null, // find_real_end
  705. null, // sql_query_for_bookmark - see below
  706. null, // extra_data
  707. null, // message_to_show
  708. null, // sql_data
  709. $goto, // goto
  710. $PMA_Theme->getImgPath(),
  711. null, // disp_query
  712. null, // disp_message
  713. $sql_query, // sql_query
  714. null // complete_query
  715. );
  716. }
  717. // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
  718. // since only one bookmark has to be added for all the queries submitted through
  719. // the SQL tab
  720. if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
  721. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  722. if (! is_array($cfgBookmark)) {
  723. $cfgBookmark = [];
  724. }
  725. $this->sql->storeTheQueryAsBookmark(
  726. $db,
  727. $cfgBookmark['user'],
  728. $_POST['sql_query'],
  729. $_POST['bkm_label'],
  730. isset($_POST['bkm_replace'])
  731. );
  732. }
  733. $this->response->addJSON('ajax_reload', $ajax_reload);
  734. $this->response->addHTML($html_output);
  735. return;
  736. }
  737. if ($result) {
  738. // Save a Bookmark with more than one queries (if Bookmark label given).
  739. if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
  740. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  741. if (! is_array($cfgBookmark)) {
  742. $cfgBookmark = [];
  743. }
  744. $this->sql->storeTheQueryAsBookmark(
  745. $db,
  746. $cfgBookmark['user'],
  747. $_POST['sql_query'],
  748. $_POST['bkm_label'],
  749. isset($_POST['bkm_replace'])
  750. );
  751. }
  752. $this->response->setRequestStatus(true);
  753. $this->response->addJSON('message', Message::success($msg));
  754. $this->response->addJSON(
  755. 'sql_query',
  756. Generator::getMessage($msg, $sql_query, 'success')
  757. );
  758. } elseif ($result === false) {
  759. $this->response->setRequestStatus(false);
  760. $this->response->addJSON('message', Message::error($msg));
  761. } else {
  762. $active_page = $goto;
  763. include ROOT_PATH . $goto;
  764. }
  765. // If there is request for ROLLBACK in the end.
  766. if (! isset($_POST['rollback_query'])) {
  767. return;
  768. }
  769. $this->dbi->query('ROLLBACK');
  770. }
  771. }