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 PhpMyAdmin\Bookmark
;
11 use PhpMyAdmin\Encoding
;
13 use PhpMyAdmin\Plugins\ImportPlugin
;
14 use PhpMyAdmin\Response
;
19 /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
20 if (isset($_POST['format']) && $_POST['format'] == 'ldi') {
21 define('PMA_ENABLE_LDI', 1);
25 * Get the variables sent or posted to this script and a core script
27 require_once 'libraries/common.inc.php';
29 if (isset($_REQUEST['show_as_php'])) {
30 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
34 require_once 'libraries/import.lib.php';
36 // If there is a request to 'Simulate DML'.
37 if (isset($_REQUEST['simulate_dml'])) {
38 PMA_handleSimulateDMLRequest();
42 $response = Response
::getInstance();
44 // If it's a refresh console bookmarks request
45 if (isset($_REQUEST['console_bookmark_refresh'])) {
47 'console_message_bookmark', PhpMyAdmin\Console
::getBookmarkContent()
51 // If it's a console bookmark add request
52 if (isset($_REQUEST['console_bookmark_add'])) {
53 if (isset($_REQUEST['label']) && isset($_REQUEST['db'])
54 && isset($_REQUEST['bookmark_query']) && isset($_REQUEST['shared'])
56 $cfgBookmark = Bookmark
::getParams();
57 $bookmarkFields = array(
58 'bkm_database' => $_REQUEST['db'],
59 'bkm_user' => $cfgBookmark['user'],
60 'bkm_sql_query' => $_REQUEST['bookmark_query'],
61 'bkm_label' => $_REQUEST['label']
63 $isShared = ($_REQUEST['shared'] == 'true' ?
true : false);
64 $bookmark = Bookmark
::createBookmark($bookmarkFields, $isShared);
65 if ($bookmark !== false && $bookmark->save()) {
66 $response->addJSON('message', __('Succeeded'));
67 $response->addJSON('data', $bookmarkFields);
68 $response->addJSON('isShared', $isShared);
70 $response->addJSON('message', __('Failed'));
74 $response->addJSON('message', __('Incomplete params'));
82 * Sets globals from $_POST
96 foreach ($post_params as $one_post_param) {
97 if (isset($_POST[$one_post_param])) {
98 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
102 // reset import messages for ajax request
103 $_SESSION['Import_message']['message'] = null;
104 $_SESSION['Import_message']['go_back_url'] = null;
106 $GLOBALS['reload'] = false;
108 // Use to identify current cycle is executing
109 // a multiquery statement or stored routine
110 if (!isset($_SESSION['is_multi_query'])) {
111 $_SESSION['is_multi_query'] = false;
114 $ajax_reload = array();
115 // Are we just executing plain query or sql file?
116 // (eg. non import, but query box/window run)
117 if (! empty($sql_query)) {
119 // apply values for parameters
120 if (! empty($_REQUEST['parameterized'])
121 && ! empty($_REQUEST['parameters'])
122 && is_array($_REQUEST['parameters'])
124 $parameters = $_REQUEST['parameters'];
125 foreach ($parameters as $parameter => $replacement) {
126 $quoted = preg_quote($parameter, '/');
127 // making sure that :param does not apply values to :param1
128 $sql_query = preg_replace(
129 '/' . $quoted . '([^a-zA-Z0-9_])/',
130 $GLOBALS['dbi']->escapeString($replacement) . '${1}',
133 // for parameters the appear at the end of the string
134 $sql_query = preg_replace(
135 '/' . $quoted . '$/',
136 $GLOBALS['dbi']->escapeString($replacement),
143 $import_text = $sql_query;
144 $import_type = 'query';
146 $_SESSION['sql_from_query_box'] = true;
148 // If there is a request to ROLLBACK when finished.
149 if (isset($_REQUEST['rollback_query'])) {
150 PMA_handleRollbackRequest($import_text);
153 // refresh navigation and main panels
154 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
155 $GLOBALS['reload'] = true;
156 $ajax_reload['reload'] = true;
159 // refresh navigation panel only
161 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
164 $ajax_reload['reload'] = true;
167 // do a dynamic reload if table is RENAMED
168 // (by sending the instruction to the AJAX response handler)
170 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
174 $ajax_reload['reload'] = true;
175 $ajax_reload['table_name'] = PhpMyAdmin\Util
::unQuote(
176 $rename_table_names[2]
181 } elseif (! empty($sql_file)) {
182 // run uploaded SQL file
183 $import_file = $sql_file;
184 $import_type = 'queryfile';
187 } elseif (! empty($_REQUEST['id_bookmark'])) {
189 $import_type = 'query';
193 // If we didn't get any parameters, either user called this directly, or
194 // upload limit has been reached, let's assume the second possibility.
195 if ($_POST == array() && $_GET == array()) {
196 $message = PhpMyAdmin\Message
::error(
198 'You probably tried to upload a file that is too large. Please refer ' .
199 'to %sdocumentation%s for a workaround for this limit.'
202 $message->addParam('[doc@faq1-16]');
203 $message->addParam('[/doc]');
205 // so we can obtain the message
206 $_SESSION['Import_message']['message'] = $message->getDisplay();
207 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
209 $response->setRequestStatus(false);
210 $response->addJSON('message', $message);
212 exit; // the footer is displayed automatically
215 // Add console message id to response output
216 if (isset($_POST['console_message_id'])) {
217 $response->addJSON('console_message_id', $_POST['console_message_id']);
221 * Sets globals from $_POST patterns, for import plugins
222 * We only need to load the selected plugin
238 // this should not happen for a normal user
239 // but only during an attack
240 Core
::fatalError('Incorrect format parameter');
243 $post_patterns = array(
245 '/^' . $format . '_/'
248 Core
::setPostAsGlobal($post_patterns);
250 // Check needed parameters
251 PhpMyAdmin\Util
::checkParameters(array('import_type', 'format'));
253 // We don't want anything special in format
254 $format = Core
::securePath($format);
256 if (strlen($table) > 0 && strlen($db) > 0) {
257 $urlparams = array('db' => $db, 'table' => $table);
258 } elseif (strlen($db) > 0) {
259 $urlparams = array('db' => $db);
261 $urlparams = array();
264 // Create error and goto url
265 if ($import_type == 'table') {
266 $goto = 'tbl_import.php';
267 } elseif ($import_type == 'database') {
268 $goto = 'db_import.php';
269 } elseif ($import_type == 'server') {
270 $goto = 'server_import.php';
272 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
273 if (strlen($table) > 0 && strlen($db) > 0) {
274 $goto = 'tbl_structure.php';
275 } elseif (strlen($db) > 0) {
276 $goto = 'db_structure.php';
278 $goto = 'server_sql.php';
282 $err_url = $goto . Url
::getCommon($urlparams);
283 $_SESSION['Import_message']['go_back_url'] = $err_url;
284 // Avoid setting selflink to 'import.php'
285 // problem similar to bug 4276
286 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
287 $_SERVER['SCRIPT_NAME'] = $goto;
291 if (strlen($db) > 0) {
292 $GLOBALS['dbi']->selectDb($db);
295 Util
::setTimeLimit();
296 if (! empty($cfg['MemoryLimit'])) {
297 @ini_set
('memory_limit', $cfg['MemoryLimit']);
301 if (isset($_REQUEST['allow_interrupt'])) {
302 $maximum_time = ini_get('max_execution_time');
307 // set default values
308 $timeout_passed = false;
314 $file_to_unlink = '';
316 $sql_query_disabled = false;
318 $executed_queries = 0;
320 $charset_conversion = false;
321 $reset_charset = false;
322 $bookmark_created = false;
324 $msg = 'Sorry an unexpected error happened!';
326 // Bookmark Support: get a query back from bookmark if required
327 if (! empty($_REQUEST['id_bookmark'])) {
328 $id_bookmark = (int)$_REQUEST['id_bookmark'];
329 switch ($_REQUEST['action_bookmark']) {
330 case 0: // bookmarked query that have to be run
331 $bookmark = Bookmark
::get(
335 isset($_REQUEST['action_bookmark_all'])
338 if (! empty($_REQUEST['bookmark_variable'])) {
339 $import_text = $bookmark->applyVariables(
340 $_REQUEST['bookmark_variable']
343 $import_text = $bookmark->getQuery();
346 // refresh navigation and main panels
348 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
351 $GLOBALS['reload'] = true;
352 $ajax_reload['reload'] = true;
355 // refresh navigation panel only
357 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
361 $ajax_reload['reload'] = true;
364 case 1: // bookmarked query that have to be displayed
365 $bookmark = Bookmark
::get($db, $id_bookmark);
366 $import_text = $bookmark->getQuery();
367 if ($response->isAjax()) {
368 $message = PhpMyAdmin\Message
::success(__('Showing bookmark'));
369 $response->setRequestStatus($message->isSuccess());
370 $response->addJSON('message', $message);
371 $response->addJSON('sql_query', $import_text);
372 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
378 case 2: // bookmarked query that have to be deleted
379 $bookmark = Bookmark
::get($db, $id_bookmark);
380 if (! empty($bookmark)) {
382 if ($response->isAjax()) {
383 $message = PhpMyAdmin\Message
::success(
384 __('The bookmark has been deleted.')
386 $response->setRequestStatus($message->isSuccess());
387 $response->addJSON('message', $message);
388 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
389 $response->addJSON('id_bookmark', $id_bookmark);
393 $error = true; // this is kind of hack to skip processing the query
399 } // end bookmarks reading
401 // Do no run query if we show PHP code
402 if (isset($GLOBALS['show_as_php'])) {
407 // We can not read all at once, otherwise we can run out of memory
408 $memory_limit = trim(@ini_get
('memory_limit'));
410 if (empty($memory_limit)) {
411 $memory_limit = 2 * 1024 * 1024;
413 // In case no memory limit we work on 10MB chunks
414 if ($memory_limit == -1) {
415 $memory_limit = 10 * 1024 * 1024;
418 // Calculate value of the limit
419 $memoryUnit = mb_strtolower(substr($memory_limit, -1));
420 if ('m' == $memoryUnit) {
421 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
422 } elseif ('k' == $memoryUnit) {
423 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
424 } elseif ('g' == $memoryUnit) {
425 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
427 $memory_limit = (int)$memory_limit;
430 // Just to be sure, there might be lot of memory needed for uncompression
431 $read_limit = $memory_limit / 8;
434 if (isset($_FILES['import_file'])) {
435 $import_file = $_FILES['import_file']['tmp_name'];
437 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
439 // sanitize $local_import_file as it comes from a POST
440 $local_import_file = Core
::securePath($local_import_file);
442 $import_file = PhpMyAdmin\Util
::userDir($cfg['UploadDir'])
443 . $local_import_file;
446 * Do not allow symlinks to avoid security issues
447 * (user can create symlink to file he can not access,
448 * but phpMyAdmin can).
450 if (@is_link
($import_file)) {
451 $import_file = 'none';
454 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
455 $import_file = 'none';
458 // Do we have file to import?
460 if ($import_file != 'none' && ! $error) {
462 * Handle file compression
464 $import_handle = new File($import_file);
465 $import_handle->checkUploadedFile();
466 if ($import_handle->isError()) {
467 PMA_stopImport($import_handle->getError());
469 $import_handle->setDecompressContent(true);
470 $import_handle->open();
471 if ($import_handle->isError()) {
472 PMA_stopImport($import_handle->getError());
474 } elseif (! $error) {
475 if (! isset($import_text) ||
empty($import_text)) {
476 $message = PhpMyAdmin\Message
::error(
478 'No data was received to import. Either no file name was ' .
479 'submitted, or the file size exceeded the maximum size permitted ' .
480 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
483 PMA_stopImport($message);
487 // so we can obtain the message
488 //$_SESSION['Import_message'] = $message->getDisplay();
490 // Convert the file's charset if necessary
491 if (Encoding
::isSupported() && isset($charset_of_file)) {
492 if ($charset_of_file != 'utf-8') {
493 $charset_conversion = true;
495 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
496 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
497 // We can not show query in this case, it is in different charset
498 $sql_query_disabled = true;
499 $reset_charset = true;
502 // Something to skip? (because timeout has passed)
503 if (! $error && isset($_POST['skip'])) {
504 $original_skip = $skip = intval($_POST['skip']);
505 while ($skip > 0 && ! $finished) {
506 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
507 // Disable read progressivity, otherwise we eat all memory!
509 $skip -= $read_limit;
514 // This array contain the data like numberof valid sql queries in the statement
515 // and complete valid sql statement (which affected for rows)
516 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
519 // Check for file existence
520 include_once "libraries/plugin_interface.lib.php";
521 /* @var $import_plugin ImportPlugin */
522 $import_plugin = PMA_getPlugin(
525 'libraries/classes/Plugins/Import/',
528 if ($import_plugin == null) {
529 $message = PhpMyAdmin\Message
::error(
530 __('Could not load import plugins, please check your installation!')
532 PMA_stopImport($message);
534 // Do the real import
536 $default_fk_check = PhpMyAdmin\Util
::handleDisableFKCheckInit();
537 $import_plugin->doImport($sql_data);
538 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
539 } catch (Exception
$e) {
540 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
546 if (isset($import_handle)) {
547 $import_handle->close();
550 // Cleanup temporary file
551 if ($file_to_unlink != '') {
552 unlink($file_to_unlink);
555 // Reset charset back, if we did some changes
556 if ($reset_charset) {
557 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
558 $GLOBALS['dbi']->query(
559 'SET SESSION collation_connection =\'' . $collation_connection . '\''
563 // Show correct message
564 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
565 $message = PhpMyAdmin\Message
::success(__('The bookmark has been deleted.'));
566 $display_query = $import_text;
567 $error = false; // unset error marker, it was used just to skip processing
568 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
569 $message = PhpMyAdmin\Message
::notice(__('Showing bookmark'));
570 } elseif ($bookmark_created) {
571 $special_message = '[br]' . sprintf(
572 __('Bookmark %s has been created.'),
573 htmlspecialchars($_POST['bkm_label'])
575 } elseif ($finished && ! $error) {
576 // Do not display the query with message, we do it separately
577 $display_query = ';';
578 if ($import_type != 'query') {
579 $message = PhpMyAdmin\Message
::success(
582 'Import has been successfully finished, %d query executed.',
583 'Import has been successfully finished, %d queries executed.',
588 $message->addParam($executed_queries);
590 if ($import_notice) {
591 $message->addHtml($import_notice);
593 if (! empty($local_import_file)) {
594 $message->addText('(' . $local_import_file . ')');
596 $message->addText('(' . $_FILES['import_file']['name'] . ')');
601 // Did we hit timeout? Tell it user.
602 if ($timeout_passed) {
603 $urlparams['timeout_passed'] = '1';
604 $urlparams['offset'] = $GLOBALS['offset'];
605 if (isset($local_import_file)) {
606 $urlparams['local_import_file'] = $local_import_file;
609 $importUrl = $err_url = $goto . Url
::getCommon($urlparams);
611 $message = PhpMyAdmin\Message
::error(
613 'Script timeout passed, if you want to finish import,'
614 . ' please %sresubmit the same file%s and import will resume.'
617 $message->addParamHtml('<a href="' . $importUrl . '">');
618 $message->addParamHtml('</a>');
620 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
623 'However on last run no data has been parsed,'
624 . ' this usually means phpMyAdmin won\'t be able to'
625 . ' finish this import unless you increase php time limits.'
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();
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 <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
642 include_once 'libraries/parse_analyze.lib.php';
645 $analyzed_sql_results,
648 ) = PMA_parseAnalyze($sql_query, $db);
649 // @todo: possibly refactor
650 extract($analyzed_sql_results);
652 if ($table != $table_from_sql && !empty($table_from_sql)) {
653 $table = $table_from_sql;
657 // There was an error?
658 if (isset($my_die)) {
659 foreach ($my_die as $key => $die) {
660 PhpMyAdmin\Util
::mysqlDie(
661 $die['error'], $die['sql'], false, $err_url, $error
668 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
669 $_SESSION['is_multi_query'] = true;
670 $sql_queries = $sql_data['valid_sql'];
672 $sql_queries = array($sql_query);
677 foreach ($sql_queries as $sql_query) {
680 include_once 'libraries/parse_analyze.lib.php';
682 $analyzed_sql_results,
685 ) = PMA_parseAnalyze($sql_query, $db);
686 // @todo: possibly refactor
687 extract($analyzed_sql_results);
689 // Check if User is allowed to issue a 'DROP DATABASE' Statement
690 if (Sql
::hasNoRightsToDropDatabase(
691 $analyzed_sql_results, $cfg['AllowUserDropDatabase'], $GLOBALS['is_superuser']
693 PhpMyAdmin\Util
::mysqlDie(
694 __('"DROP DATABASE" statements are disabled.'),
697 $_SESSION['Import_message']['go_back_url']
702 if ($table != $table_from_sql && !empty($table_from_sql)) {
703 $table = $table_from_sql;
706 $html_output .= Sql
::executeQueryAndGetQueryResponse(
707 $analyzed_sql_results, // analyzed_sql_results
708 false, // is_gotofile
711 null, // find_real_end
712 null, // sql_query_for_bookmark - see below
714 null, // message_to_show
718 $pmaThemeImage, // pmaThemeImage
720 null, // disp_message
722 $sql_query, // sql_query
723 null, // selectedTables
724 null // complete_query
728 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
729 // since only one bookmark has to be added for all the queries submitted through
731 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
732 $cfgBookmark = Bookmark
::getParams();
733 Sql
::storeTheQueryAsBookmark(
734 $db, $cfgBookmark['user'],
735 $_REQUEST['sql_query'], $_POST['bkm_label'],
736 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
740 $response->addJSON('ajax_reload', $ajax_reload);
741 $response->addHTML($html_output);
744 } else if ($result) {
745 // Save a Bookmark with more than one queries (if Bookmark label given).
746 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
747 $cfgBookmark = Bookmark
::getParams();
748 Sql
::storeTheQueryAsBookmark(
749 $db, $cfgBookmark['user'],
750 $_REQUEST['sql_query'], $_POST['bkm_label'],
751 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
755 $response->setRequestStatus(true);
756 $response->addJSON('message', PhpMyAdmin\Message
::success($msg));
759 PhpMyAdmin\Util
::getMessage($msg, $sql_query, 'success')
761 } else if ($result == false) {
762 $response->setRequestStatus(false);
763 $response->addJSON('message', PhpMyAdmin\Message
::error($msg));
765 $active_page = $goto;
769 // If there is request for ROLLBACK in the end.
770 if (isset($_REQUEST['rollback_query'])) {
771 $GLOBALS['dbi']->query('ROLLBACK');