2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Core script for import, this is just the glue around all other stuff
9 use PMA\libraries\Bookmark
;
10 use PMA\libraries\Core
;
11 use PMA\libraries\Encoding
;
12 use PMA\libraries\File
;
13 use PMA\libraries\plugins\ImportPlugin
;
14 use PMA\libraries\Response
;
15 use PMA\libraries\Sql
;
16 use PMA\libraries\URL
;
18 /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
19 if (isset($_POST['format']) && $_POST['format'] == 'ldi') {
20 define('PMA_ENABLE_LDI', 1);
24 * Get the variables sent or posted to this script and a core script
26 require_once 'libraries/common.inc.php';
28 if (isset($_REQUEST['show_as_php'])) {
29 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
33 require_once 'libraries/import.lib.php';
35 // If there is a request to 'Simulate DML'.
36 if (isset($_REQUEST['simulate_dml'])) {
37 PMA_handleSimulateDMLRequest();
41 $response = Response
::getInstance();
43 // If it's a refresh console bookmarks request
44 if (isset($_REQUEST['console_bookmark_refresh'])) {
46 'console_message_bookmark', PMA\libraries\Console
::getBookmarkContent()
50 // If it's a console bookmark add request
51 if (isset($_REQUEST['console_bookmark_add'])) {
52 if (isset($_REQUEST['label']) && isset($_REQUEST['db'])
53 && isset($_REQUEST['bookmark_query']) && isset($_REQUEST['shared'])
55 $cfgBookmark = Bookmark
::getParams();
56 $bookmarkFields = array(
57 'bkm_database' => $_REQUEST['db'],
58 'bkm_user' => $cfgBookmark['user'],
59 'bkm_sql_query' => $_REQUEST['bookmark_query'],
60 'bkm_label' => $_REQUEST['label']
62 $isShared = ($_REQUEST['shared'] == 'true' ?
true : false);
63 $bookmark = Bookmark
::createBookmark($bookmarkFields, $isShared);
64 if ($bookmark !== false && $bookmark->save()) {
65 $response->addJSON('message', __('Succeeded'));
66 $response->addJSON('data', $bookmarkFields);
67 $response->addJSON('isShared', $isShared);
69 $response->addJSON('message', __('Failed'));
73 $response->addJSON('message', __('Incomplete params'));
81 * Sets globals from $_POST
95 foreach ($post_params as $one_post_param) {
96 if (isset($_POST[$one_post_param])) {
97 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
101 // reset import messages for ajax request
102 $_SESSION['Import_message']['message'] = null;
103 $_SESSION['Import_message']['go_back_url'] = null;
105 $GLOBALS['reload'] = false;
107 // Use to identify current cycle is executing
108 // a multiquery statement or stored routine
109 if (!isset($_SESSION['is_multi_query'])) {
110 $_SESSION['is_multi_query'] = false;
113 $ajax_reload = array();
114 // Are we just executing plain query or sql file?
115 // (eg. non import, but query box/window run)
116 if (! empty($sql_query)) {
118 // apply values for parameters
119 if (! empty($_REQUEST['parameterized'])
120 && ! empty($_REQUEST['parameters'])
121 && is_array($_REQUEST['parameters'])
123 $parameters = $_REQUEST['parameters'];
124 foreach ($parameters as $parameter => $replacement) {
125 $quoted = preg_quote($parameter, '/');
126 // making sure that :param does not apply values to :param1
127 $sql_query = preg_replace(
128 '/' . $quoted . '([^a-zA-Z0-9_])/',
129 $GLOBALS['dbi']->escapeString($replacement) . '${1}',
132 // for parameters the appear at the end of the string
133 $sql_query = preg_replace(
134 '/' . $quoted . '$/',
135 $GLOBALS['dbi']->escapeString($replacement),
142 $import_text = $sql_query;
143 $import_type = 'query';
145 $_SESSION['sql_from_query_box'] = true;
147 // If there is a request to ROLLBACK when finished.
148 if (isset($_REQUEST['rollback_query'])) {
149 PMA_handleRollbackRequest($import_text);
152 // refresh navigation and main panels
153 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
154 $GLOBALS['reload'] = true;
155 $ajax_reload['reload'] = true;
158 // refresh navigation panel only
160 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
163 $ajax_reload['reload'] = true;
166 // do a dynamic reload if table is RENAMED
167 // (by sending the instruction to the AJAX response handler)
169 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
173 $ajax_reload['reload'] = true;
174 $ajax_reload['table_name'] = PMA\libraries\Util
::unQuote(
175 $rename_table_names[2]
180 } elseif (! empty($sql_file)) {
181 // run uploaded SQL file
182 $import_file = $sql_file;
183 $import_type = 'queryfile';
186 } elseif (! empty($_REQUEST['id_bookmark'])) {
188 $import_type = 'query';
192 // If we didn't get any parameters, either user called this directly, or
193 // upload limit has been reached, let's assume the second possibility.
194 if ($_POST == array() && $_GET == array()) {
195 $message = PMA\libraries\Message
::error(
197 'You probably tried to upload a file that is too large. Please refer ' .
198 'to %sdocumentation%s for a workaround for this limit.'
201 $message->addParam('[doc@faq1-16]');
202 $message->addParam('[/doc]');
204 // so we can obtain the message
205 $_SESSION['Import_message']['message'] = $message->getDisplay();
206 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
208 $response->setRequestStatus(false);
209 $response->addJSON('message', $message);
211 exit; // the footer is displayed automatically
214 // Add console message id to response output
215 if (isset($_POST['console_message_id'])) {
216 $response->addJSON('console_message_id', $_POST['console_message_id']);
220 * Sets globals from $_POST patterns, for import plugins
221 * We only need to load the selected plugin
237 // this should not happen for a normal user
238 // but only during an attack
239 Core
::fatalError('Incorrect format parameter');
242 $post_patterns = array(
244 '/^' . $format . '_/'
247 Core
::setPostAsGlobal($post_patterns);
249 // Check needed parameters
250 PMA\libraries\Util
::checkParameters(array('import_type', 'format'));
252 // We don't want anything special in format
253 $format = Core
::securePath($format);
255 if (strlen($table) > 0 && strlen($db) > 0) {
256 $urlparams = array('db' => $db, 'table' => $table);
257 } elseif (strlen($db) > 0) {
258 $urlparams = array('db' => $db);
260 $urlparams = array();
263 // Create error and goto url
264 if ($import_type == 'table') {
265 $goto = 'tbl_import.php';
266 } elseif ($import_type == 'database') {
267 $goto = 'db_import.php';
268 } elseif ($import_type == 'server') {
269 $goto = 'server_import.php';
271 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
272 if (strlen($table) > 0 && strlen($db) > 0) {
273 $goto = 'tbl_structure.php';
274 } elseif (strlen($db) > 0) {
275 $goto = 'db_structure.php';
277 $goto = 'server_sql.php';
281 $err_url = $goto . URL
::getCommon($urlparams);
282 $_SESSION['Import_message']['go_back_url'] = $err_url;
283 // Avoid setting selflink to 'import.php'
284 // problem similar to bug 4276
285 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
286 $_SERVER['SCRIPT_NAME'] = $goto;
290 if (strlen($db) > 0) {
291 $GLOBALS['dbi']->selectDb($db);
294 @set_time_limit
($cfg['ExecTimeLimit']);
295 if (! empty($cfg['MemoryLimit'])) {
296 @ini_set
('memory_limit', $cfg['MemoryLimit']);
300 if (isset($_REQUEST['allow_interrupt'])) {
301 $maximum_time = ini_get('max_execution_time');
306 // set default values
307 $timeout_passed = false;
313 $file_to_unlink = '';
315 $sql_query_disabled = false;
317 $executed_queries = 0;
319 $charset_conversion = false;
320 $reset_charset = false;
321 $bookmark_created = false;
323 $msg = 'Sorry an unexpected error happened!';
325 // Bookmark Support: get a query back from bookmark if required
326 if (! empty($_REQUEST['id_bookmark'])) {
327 $id_bookmark = (int)$_REQUEST['id_bookmark'];
328 switch ($_REQUEST['action_bookmark']) {
329 case 0: // bookmarked query that have to be run
330 $bookmark = Bookmark
::get(
334 isset($_REQUEST['action_bookmark_all'])
337 if (! empty($_REQUEST['bookmark_variable'])) {
338 $import_text = $bookmark->applyVariables(
339 $_REQUEST['bookmark_variable']
342 $import_text = $bookmark->getQuery();
345 // refresh navigation and main panels
347 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
350 $GLOBALS['reload'] = true;
351 $ajax_reload['reload'] = true;
354 // refresh navigation panel only
356 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
360 $ajax_reload['reload'] = true;
363 case 1: // bookmarked query that have to be displayed
364 $bookmark = Bookmark
::get($db, $id_bookmark);
365 $import_text = $bookmark->getQuery();
366 if ($response->isAjax()) {
367 $message = PMA\libraries\Message
::success(__('Showing bookmark'));
368 $response->setRequestStatus($message->isSuccess());
369 $response->addJSON('message', $message);
370 $response->addJSON('sql_query', $import_text);
371 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
377 case 2: // bookmarked query that have to be deleted
378 $bookmark = Bookmark
::get($db, $id_bookmark);
379 if (! empty($bookmark)) {
381 if ($response->isAjax()) {
382 $message = PMA\libraries\Message
::success(
383 __('The bookmark has been deleted.')
385 $response->setRequestStatus($message->isSuccess());
386 $response->addJSON('message', $message);
387 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
388 $response->addJSON('id_bookmark', $id_bookmark);
392 $error = true; // this is kind of hack to skip processing the query
398 } // end bookmarks reading
400 // Do no run query if we show PHP code
401 if (isset($GLOBALS['show_as_php'])) {
406 // We can not read all at once, otherwise we can run out of memory
407 $memory_limit = trim(@ini_get
('memory_limit'));
409 if (empty($memory_limit)) {
410 $memory_limit = 2 * 1024 * 1024;
412 // In case no memory limit we work on 10MB chunks
413 if ($memory_limit == -1) {
414 $memory_limit = 10 * 1024 * 1024;
417 // Calculate value of the limit
418 $memoryUnit = mb_strtolower(substr($memory_limit, -1));
419 if ('m' == $memoryUnit) {
420 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
421 } elseif ('k' == $memoryUnit) {
422 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
423 } elseif ('g' == $memoryUnit) {
424 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
426 $memory_limit = (int)$memory_limit;
429 // Just to be sure, there might be lot of memory needed for uncompression
430 $read_limit = $memory_limit / 8;
433 if (isset($_FILES['import_file'])) {
434 $import_file = $_FILES['import_file']['tmp_name'];
436 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
438 // sanitize $local_import_file as it comes from a POST
439 $local_import_file = Core
::securePath($local_import_file);
441 $import_file = PMA\libraries\Util
::userDir($cfg['UploadDir'])
442 . $local_import_file;
445 * Do not allow symlinks to avoid security issues
446 * (user can create symlink to file he can not access,
447 * but phpMyAdmin can).
449 if (@is_link
($import_file)) {
450 $import_file = 'none';
453 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
454 $import_file = 'none';
457 // Do we have file to import?
459 if ($import_file != 'none' && ! $error) {
461 * Handle file compression
463 $import_handle = new File($import_file);
464 $import_handle->checkUploadedFile();
465 if ($import_handle->isError()) {
466 PMA_stopImport($import_handle->getError());
468 $import_handle->setDecompressContent(true);
469 $import_handle->open();
470 if ($import_handle->isError()) {
471 PMA_stopImport($import_handle->getError());
473 } elseif (! $error) {
474 if (! isset($import_text) ||
empty($import_text)) {
475 $message = PMA\libraries\Message
::error(
477 'No data was received to import. Either no file name was ' .
478 'submitted, or the file size exceeded the maximum size permitted ' .
479 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
482 PMA_stopImport($message);
486 // so we can obtain the message
487 //$_SESSION['Import_message'] = $message->getDisplay();
489 // Convert the file's charset if necessary
490 if (Encoding
::isSupported() && isset($charset_of_file)) {
491 if ($charset_of_file != 'utf-8') {
492 $charset_conversion = true;
494 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
495 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
496 // We can not show query in this case, it is in different charset
497 $sql_query_disabled = true;
498 $reset_charset = true;
501 // Something to skip? (because timeout has passed)
502 if (! $error && isset($_POST['skip'])) {
503 $original_skip = $skip = intval($_POST['skip']);
504 while ($skip > 0 && ! $finished) {
505 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
506 // Disable read progressivity, otherwise we eat all memory!
508 $skip -= $read_limit;
513 // This array contain the data like numberof valid sql queries in the statement
514 // and complete valid sql statement (which affected for rows)
515 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
518 // Check for file existence
519 include_once "libraries/plugin_interface.lib.php";
520 /* @var $import_plugin ImportPlugin */
521 $import_plugin = PMA_getPlugin(
524 'libraries/plugins/import/',
527 if ($import_plugin == null) {
528 $message = PMA\libraries\Message
::error(
529 __('Could not load import plugins, please check your installation!')
531 PMA_stopImport($message);
533 // Do the real import
535 $default_fk_check = PMA\libraries\Util
::handleDisableFKCheckInit();
536 $import_plugin->doImport($sql_data);
537 PMA\libraries\Util
::handleDisableFKCheckCleanup($default_fk_check);
538 } catch (Exception
$e) {
539 PMA\libraries\Util
::handleDisableFKCheckCleanup($default_fk_check);
545 if (isset($import_handle)) {
546 $import_handle->close();
549 // Cleanup temporary file
550 if ($file_to_unlink != '') {
551 unlink($file_to_unlink);
554 // Reset charset back, if we did some changes
555 if ($reset_charset) {
556 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
557 $GLOBALS['dbi']->query(
558 'SET SESSION collation_connection =\'' . $collation_connection . '\''
562 // Show correct message
563 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
564 $message = PMA\libraries\Message
::success(__('The bookmark has been deleted.'));
565 $display_query = $import_text;
566 $error = false; // unset error marker, it was used just to skip processing
567 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
568 $message = PMA\libraries\Message
::notice(__('Showing bookmark'));
569 } elseif ($bookmark_created) {
570 $special_message = '[br]' . sprintf(
571 __('Bookmark %s has been created.'),
572 htmlspecialchars($_POST['bkm_label'])
574 } elseif ($finished && ! $error) {
575 // Do not display the query with message, we do it separately
576 $display_query = ';';
577 if ($import_type != 'query') {
578 $message = PMA\libraries\Message
::success(
581 'Import has been successfully finished, %d query executed.',
582 'Import has been successfully finished, %d queries executed.',
587 $message->addParam($executed_queries);
589 if ($import_notice) {
590 $message->addHtml($import_notice);
592 if (! empty($local_import_file)) {
593 $message->addText('(' . $local_import_file . ')');
595 $message->addText('(' . $_FILES['import_file']['name'] . ')');
600 // Did we hit timeout? Tell it user.
601 if ($timeout_passed) {
602 $urlparams['timeout_passed'] = '1';
603 $urlparams['offset'] = $GLOBALS['offset'];
604 if (isset($local_import_file)) {
605 $urlparams['local_import_file'] = $local_import_file;
608 $importUrl = $err_url = $goto . URL
::getCommon($urlparams);
610 $message = PMA\libraries\Message
::error(
612 'Script timeout passed, if you want to finish import,'
613 . ' please %sresubmit the same file%s and import will resume.'
616 $message->addParamHtml('<a href="' . $importUrl . '">');
617 $message->addParamHtml('</a>');
619 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
622 'However on last run no data has been parsed,'
623 . ' this usually means phpMyAdmin won\'t be able to'
624 . ' finish this import unless you increase php time limits.'
630 // if there is any message, copy it into $_SESSION as well,
631 // so we can obtain it by AJAX call
632 if (isset($message)) {
633 $_SESSION['Import_message']['message'] = $message->getDisplay();
635 // Parse and analyze the query, for correct db and table name
636 // in case of a query typed in the query window
637 // (but if the query is too large, in case of an imported file, the parser
638 // can choke on it so avoid parsing)
639 $sqlLength = mb_strlen($sql_query);
640 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
641 include_once 'libraries/parse_analyze.lib.php';
644 $analyzed_sql_results,
647 ) = PMA_parseAnalyze($sql_query, $db);
648 // @todo: possibly refactor
649 extract($analyzed_sql_results);
651 if ($table != $table_from_sql && !empty($table_from_sql)) {
652 $table = $table_from_sql;
656 // There was an error?
657 if (isset($my_die)) {
658 foreach ($my_die as $key => $die) {
659 PMA\libraries\Util
::mysqlDie(
660 $die['error'], $die['sql'], false, $err_url, $error
667 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
668 $_SESSION['is_multi_query'] = true;
669 $sql_queries = $sql_data['valid_sql'];
671 $sql_queries = array($sql_query);
676 foreach ($sql_queries as $sql_query) {
679 include_once 'libraries/parse_analyze.lib.php';
681 $analyzed_sql_results,
684 ) = PMA_parseAnalyze($sql_query, $db);
685 // @todo: possibly refactor
686 extract($analyzed_sql_results);
688 // Check if User is allowed to issue a 'DROP DATABASE' Statement
689 if (Sql
::hasNoRightsToDropDatabase(
690 $analyzed_sql_results, $cfg['AllowUserDropDatabase'], $GLOBALS['is_superuser']
692 PMA\libraries\Util
::mysqlDie(
693 __('"DROP DATABASE" statements are disabled.'),
696 $_SESSION['Import_message']['go_back_url']
701 if ($table != $table_from_sql && !empty($table_from_sql)) {
702 $table = $table_from_sql;
705 $html_output .= Sql
::executeQueryAndGetQueryResponse(
706 $analyzed_sql_results, // analyzed_sql_results
707 false, // is_gotofile
710 null, // find_real_end
711 null, // sql_query_for_bookmark - see below
713 null, // message_to_show
717 $pmaThemeImage, // pmaThemeImage
719 null, // disp_message
721 $sql_query, // sql_query
722 null, // selectedTables
723 null // complete_query
727 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
728 // since only one bookmark has to be added for all the queries submitted through
730 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
731 $cfgBookmark = Bookmark
::getParams();
732 Sql
::storeTheQueryAsBookmark(
733 $db, $cfgBookmark['user'],
734 $_REQUEST['sql_query'], $_POST['bkm_label'],
735 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
739 $response->addJSON('ajax_reload', $ajax_reload);
740 $response->addHTML($html_output);
743 } else if ($result) {
744 // Save a Bookmark with more than one queries (if Bookmark label given).
745 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
746 $cfgBookmark = Bookmark
::getParams();
747 Sql
::storeTheQueryAsBookmark(
748 $db, $cfgBookmark['user'],
749 $_REQUEST['sql_query'], $_POST['bkm_label'],
750 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
754 $response->setRequestStatus(true);
755 $response->addJSON('message', PMA\libraries\Message
::success($msg));
758 PMA\libraries\Util
::getMessage($msg, $sql_query, 'success')
760 } else if ($result == false) {
761 $response->setRequestStatus(false);
762 $response->addJSON('message', PMA\libraries\Message
::error($msg));
764 $active_page = $goto;
768 // If there is request for ROLLBACK in the end.
769 if (isset($_REQUEST['rollback_query'])) {
770 $GLOBALS['dbi']->query('ROLLBACK');