Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / export.lib.php
blob5f8643ef339a37a013fc5c8ac2cda8ef1f232249
1 <?php
3 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 /**
5 * function for the main export logic
7 * @package PhpMyAdmin
8 */
9 use PMA\libraries\Encoding;
10 use PMA\libraries\Message;
11 use PMA\libraries\plugins\ExportPlugin;
12 use PMA\libraries\Table;
13 use PMA\libraries\ZipFile;
14 use PMA\libraries\URL;
15 use PMA\libraries\Sanitize;
18 /**
19 * Sets a session variable upon a possible fatal error during export
21 * @return void
23 function PMA_shutdownDuringExport()
25 $error = error_get_last();
26 if ($error != null && mb_strpos($error['message'], "execution time")) {
27 //set session variable to check if there was error while exporting
28 $_SESSION['pma_export_error'] = $error['message'];
32 /**
33 * Detect ob_gzhandler
35 * @return bool
37 function PMA_isGzHandlerEnabled()
39 return in_array('ob_gzhandler', ob_list_handlers());
42 /**
43 * Detect whether gzencode is needed; it might not be needed if
44 * the server is already compressing by itself
46 * @return bool Whether gzencode is needed
48 function PMA_gzencodeNeeded()
51 * We should gzencode only if the function exists
52 * but we don't want to compress twice, therefore
53 * gzencode only if transparent compression is not enabled
54 * and gz compression was not asked via $cfg['OBGzip']
55 * but transparent compression does not apply when saving to server
57 $chromeAndGreaterThan43 = PMA_USR_BROWSER_AGENT == 'CHROME'
58 && PMA_USR_BROWSER_VER >= 43; // see bug #4942
60 if (@function_exists('gzencode')
61 && ((! @ini_get('zlib.output_compression')
62 && ! PMA_isGzHandlerEnabled())
63 || $GLOBALS['save_on_server']
64 || $chromeAndGreaterThan43)
65 ) {
66 return true;
67 } else {
68 return false;
72 /**
73 * Output handler for all exports, if needed buffering, it stores data into
74 * $dump_buffer, otherwise it prints them out.
76 * @param string $line the insert statement
78 * @return bool Whether output succeeded
80 function PMA_exportOutputHandler($line)
82 global $time_start, $dump_buffer, $dump_buffer_len, $save_filename;
84 // Kanji encoding convert feature
85 if ($GLOBALS['output_kanji_conversion']) {
86 $line = Encoding::kanjiStrConv(
87 $line,
88 $GLOBALS['knjenc'],
89 isset($GLOBALS['xkana']) ? $GLOBALS['xkana'] : ''
93 // If we have to buffer data, we will perform everything at once at the end
94 if ($GLOBALS['buffer_needed']) {
96 $dump_buffer .= $line;
97 if ($GLOBALS['onfly_compression']) {
99 $dump_buffer_len += strlen($line);
101 if ($dump_buffer_len > $GLOBALS['memory_limit']) {
102 if ($GLOBALS['output_charset_conversion']) {
103 $dump_buffer = Encoding::convertString(
104 'utf-8',
105 $GLOBALS['charset'],
106 $dump_buffer
109 if ($GLOBALS['compression'] == 'gzip'
110 && PMA_gzencodeNeeded()
112 // as a gzipped file
113 // without the optional parameter level because it bugs
114 $dump_buffer = gzencode($dump_buffer);
116 if ($GLOBALS['save_on_server']) {
117 $write_result = @fwrite($GLOBALS['file_handle'], $dump_buffer);
118 // Here, use strlen rather than mb_strlen to get the length
119 // in bytes to compare against the number of bytes written.
120 if ($write_result != strlen($dump_buffer)) {
121 $GLOBALS['message'] = Message::error(
122 __('Insufficient space to save the file %s.')
124 $GLOBALS['message']->addParam($save_filename);
125 return false;
127 } else {
128 echo $dump_buffer;
130 $dump_buffer = '';
131 $dump_buffer_len = 0;
133 } else {
134 $time_now = time();
135 if ($time_start >= $time_now + 30) {
136 $time_start = $time_now;
137 header('X-pmaPing: Pong');
138 } // end if
140 } else {
141 if ($GLOBALS['asfile']) {
142 if ($GLOBALS['output_charset_conversion']) {
143 $line = Encoding::convertString(
144 'utf-8',
145 $GLOBALS['charset'],
146 $line
149 if ($GLOBALS['save_on_server'] && mb_strlen($line) > 0) {
150 $write_result = @fwrite($GLOBALS['file_handle'], $line);
151 // Here, use strlen rather than mb_strlen to get the length
152 // in bytes to compare against the number of bytes written.
153 if (! $write_result
154 || $write_result != strlen($line)
156 $GLOBALS['message'] = Message::error(
157 __('Insufficient space to save the file %s.')
159 $GLOBALS['message']->addParam($save_filename);
160 return false;
162 $time_now = time();
163 if ($time_start >= $time_now + 30) {
164 $time_start = $time_now;
165 header('X-pmaPing: Pong');
166 } // end if
167 } else {
168 // We export as file - output normally
169 echo $line;
171 } else {
172 // We export as html - replace special chars
173 echo htmlspecialchars($line);
176 return true;
177 } // end of the 'PMA_exportOutputHandler()' function
180 * Returns HTML containing the footer for a displayed export
182 * @param string $back_button the link for going Back
184 * @return string $html the HTML output
186 function PMA_getHtmlForDisplayedExportFooter($back_button)
189 * Close the html tags and add the footers for on-screen export
191 $html = '</textarea>'
192 . ' </form>'
193 // bottom back button
194 . $back_button
195 . '</div>'
196 . '<script type="text/javascript">' . "\n"
197 . '//<![CDATA[' . "\n"
198 . 'var $body = $("body");' . "\n"
199 . '$("#textSQLDUMP")' . "\n"
200 . '.width($body.width() - 50)' . "\n"
201 . '.height($body.height() - 100);' . "\n"
202 . '//]]>' . "\n"
203 . '</script>' . "\n";
204 return $html;
208 * Computes the memory limit for export
210 * @return int $memory_limit the memory limit
212 function PMA_getMemoryLimitForExport()
214 $memory_limit = trim(@ini_get('memory_limit'));
215 $memory_limit_num = (int)substr($memory_limit, 0, -1);
216 $lowerLastChar = strtolower(substr($memory_limit, -1));
217 // 2 MB as default
218 if (empty($memory_limit) || '-1' == $memory_limit) {
219 $memory_limit = 2 * 1024 * 1024;
220 } elseif ($lowerLastChar == 'm') {
221 $memory_limit = $memory_limit_num * 1024 * 1024;
222 } elseif ($lowerLastChar == 'k') {
223 $memory_limit = $memory_limit_num * 1024;
224 } elseif ($lowerLastChar == 'g') {
225 $memory_limit = $memory_limit_num * 1024 * 1024 * 1024;
226 } else {
227 $memory_limit = (int)$memory_limit;
230 // Some of memory is needed for other things and as threshold.
231 // During export I had allocated (see memory_get_usage function)
232 // approx 1.2MB so this comes from that.
233 if ($memory_limit > 1500000) {
234 $memory_limit -= 1500000;
237 // Some memory is needed for compression, assume 1/3
238 $memory_limit /= 8;
239 return $memory_limit;
243 * Return the filename and MIME type for export file
245 * @param string $export_type type of export
246 * @param string $remember_template whether to remember template
247 * @param ExportPlugin $export_plugin the export plugin
248 * @param string $compression compression asked
249 * @param string $filename_template the filename template
251 * @return string[] the filename template and mime type
253 function PMA_getExportFilenameAndMimetype(
254 $export_type, $remember_template, $export_plugin, $compression,
255 $filename_template
257 if ($export_type == 'server') {
258 if (! empty($remember_template)) {
259 $GLOBALS['PMA_Config']->setUserValue(
260 'pma_server_filename_template',
261 'Export/file_template_server',
262 $filename_template
265 } elseif ($export_type == 'database') {
266 if (! empty($remember_template)) {
267 $GLOBALS['PMA_Config']->setUserValue(
268 'pma_db_filename_template',
269 'Export/file_template_database',
270 $filename_template
273 } else {
274 if (! empty($remember_template)) {
275 $GLOBALS['PMA_Config']->setUserValue(
276 'pma_table_filename_template',
277 'Export/file_template_table',
278 $filename_template
282 $filename = PMA\libraries\Util::expandUserString($filename_template);
283 // remove dots in filename (coming from either the template or already
284 // part of the filename) to avoid a remote code execution vulnerability
285 $filename = Sanitize::sanitizeFilename($filename, $replaceDots = true);
287 // Grab basic dump extension and mime type
288 // Check if the user already added extension;
289 // get the substring where the extension would be if it was included
290 $extension_start_pos = mb_strlen($filename) - mb_strlen(
291 $export_plugin->getProperties()->getExtension()
292 ) - 1;
293 $user_extension = mb_substr(
294 $filename, $extension_start_pos, mb_strlen($filename)
296 $required_extension = "." . $export_plugin->getProperties()->getExtension();
297 if (mb_strtolower($user_extension) != $required_extension) {
298 $filename .= $required_extension;
300 $mime_type = $export_plugin->getProperties()->getMimeType();
302 // If dump is going to be compressed, set correct mime_type and add
303 // compression to extension
304 if ($compression == 'gzip') {
305 $filename .= '.gz';
306 $mime_type = 'application/x-gzip';
307 } elseif ($compression == 'zip') {
308 $filename .= '.zip';
309 $mime_type = 'application/zip';
311 return array($filename, $mime_type);
315 * Open the export file
317 * @param string $filename the export filename
318 * @param boolean $quick_export whether it's a quick export or not
320 * @return array the full save filename, possible message and the file handle
322 function PMA_openExportFile($filename, $quick_export)
324 $file_handle = null;
325 $message = '';
327 $save_filename = PMA\libraries\Util::userDir($GLOBALS['cfg']['SaveDir'])
328 . preg_replace('@[/\\\\]@', '_', $filename);
330 if (file_exists($save_filename)
331 && ((! $quick_export && empty($_REQUEST['onserver_overwrite']))
332 || ($quick_export
333 && $_REQUEST['quick_export_onserver_overwrite'] != 'saveitover'))
335 $message = Message::error(
337 'File %s already exists on server, '
338 . 'change filename or check overwrite option.'
341 $message->addParam($save_filename);
342 } elseif (@is_file($save_filename) && ! @is_writable($save_filename)) {
343 $message = Message::error(
345 'The web server does not have permission '
346 . 'to save the file %s.'
349 $message->addParam($save_filename);
350 } elseif (! $file_handle = @fopen($save_filename, 'w')) {
351 $message = Message::error(
353 'The web server does not have permission '
354 . 'to save the file %s.'
357 $message->addParam($save_filename);
359 return array($save_filename, $message, $file_handle);
363 * Close the export file
365 * @param resource $file_handle the export file handle
366 * @param string $dump_buffer the current dump buffer
367 * @param string $save_filename the export filename
369 * @return Message $message a message object (or empty string)
371 function PMA_closeExportFile($file_handle, $dump_buffer, $save_filename)
373 $write_result = @fwrite($file_handle, $dump_buffer);
374 fclose($file_handle);
375 // Here, use strlen rather than mb_strlen to get the length
376 // in bytes to compare against the number of bytes written.
377 if (strlen($dump_buffer) > 0
378 && (! $write_result || $write_result != strlen($dump_buffer))
380 $message = new Message(
381 __('Insufficient space to save the file %s.'),
382 Message::ERROR,
383 array($save_filename)
385 } else {
386 $message = new Message(
387 __('Dump has been saved to file %s.'),
388 Message::SUCCESS,
389 array($save_filename)
392 return $message;
396 * Compress the export buffer
398 * @param array|string $dump_buffer the current dump buffer
399 * @param string $compression the compression mode
400 * @param string $filename the filename
402 * @return object $message a message object (or empty string)
404 function PMA_compressExport($dump_buffer, $compression, $filename)
406 if ($compression == 'zip' && @function_exists('gzcompress')) {
407 $filename = substr($filename, 0, -4); // remove extension (.zip)
408 $zipfile = new ZipFile();
409 if (is_array($dump_buffer)) {
410 foreach ($dump_buffer as $table => $dump) {
411 $ext_pos = strpos($filename, '.');
412 $extension = substr($filename, $ext_pos);
413 $zipfile->addFile(
414 $dump,
415 str_replace(
416 $extension,
417 '_' . $table . $extension,
418 $filename
422 } else {
423 $zipfile->addFile($dump_buffer, $filename);
425 $dump_buffer = $zipfile->file();
426 } elseif ($compression == 'gzip' && PMA_gzencodeNeeded()) {
427 // without the optional parameter level because it bugs
428 $dump_buffer = gzencode($dump_buffer);
430 return $dump_buffer;
434 * Saves the dump_buffer for a particular table in an array
435 * Used in separate files export
437 * @param string $object_name the name of current object to be stored
438 * @param boolean $append optional boolean to append to an existing index or not
440 * @return void
442 function PMA_saveObjectInBuffer($object_name, $append = false)
445 global $dump_buffer_objects, $dump_buffer, $dump_buffer_len;
447 if (! empty($dump_buffer)) {
448 if ($append && isset($dump_buffer_objects[$object_name])) {
449 $dump_buffer_objects[$object_name] .= $dump_buffer;
450 } else {
451 $dump_buffer_objects[$object_name] = $dump_buffer;
455 // Re - initialize
456 $dump_buffer = '';
457 $dump_buffer_len = 0;
462 * Returns HTML containing the header for a displayed export
464 * @param string $export_type the export type
465 * @param string $db the database name
466 * @param string $table the table name
468 * @return string[] the generated HTML and back button
470 function PMA_getHtmlForDisplayedExportHeader($export_type, $db, $table)
472 $html = '<div style="text-align: ' . $GLOBALS['cell_align_left'] . '">';
475 * Displays a back button with all the $_REQUEST data in the URL
476 * (store in a variable to also display after the textarea)
478 $back_button = '<p>[ <a href="';
479 if ($export_type == 'server') {
480 $back_button .= 'server_export.php' . URL::getCommon();
481 } elseif ($export_type == 'database') {
482 $back_button .= 'db_export.php' . URL::getCommon(array('db' => $db));
483 } else {
484 $back_button .= 'tbl_export.php' . URL::getCommon(
485 array(
486 'db' => $db, 'table' => $table
491 // Convert the multiple select elements from an array to a string
492 if ($export_type == 'server' && isset($_REQUEST['db_select'])) {
493 $_REQUEST['db_select'] = implode(",", $_REQUEST['db_select']);
494 } elseif ($export_type == 'database') {
495 if (isset($_REQUEST['table_select'])) {
496 $_REQUEST['table_select'] = implode(",", $_REQUEST['table_select']);
498 if (isset($_REQUEST['table_structure'])) {
499 $_REQUEST['table_structure'] = implode(
500 ",",
501 $_REQUEST['table_structure']
503 } else if (empty($_REQUEST['structure_or_data_forced'])) {
504 $_REQUEST['table_structure'] = '';
506 if (isset($_REQUEST['table_data'])) {
507 $_REQUEST['table_data'] = implode(",", $_REQUEST['table_data']);
508 } else if (empty($_REQUEST['structure_or_data_forced'])) {
509 $_REQUEST['table_data'] = '';
513 foreach ($_REQUEST as $name => $value) {
514 if (!is_array($value)) {
515 $back_button .= '&amp;' . urlencode($name) . '=' . urlencode($value);
518 $back_button .= '&amp;repopulate=1">' . __('Back') . '</a> ]</p>';
520 $html .= $back_button
521 . '<form name="nofunction">'
522 . '<textarea name="sqldump" cols="50" rows="30" '
523 . 'id="textSQLDUMP" wrap="OFF">';
525 return array($html, $back_button);
529 * Export at the server level
531 * @param string $db_select the selected databases to export
532 * @param string $whatStrucOrData structure or data or both
533 * @param ExportPlugin $export_plugin the selected export plugin
534 * @param string $crlf end of line character(s)
535 * @param string $err_url the URL in case of error
536 * @param string $export_type the export type
537 * @param bool $do_relation whether to export relation info
538 * @param bool $do_comments whether to add comments
539 * @param bool $do_mime whether to add MIME info
540 * @param bool $do_dates whether to add dates
541 * @param array $aliases alias information for db/table/column
542 * @param string $separate_files whether it is a separate-files export
544 * @return void
546 function PMA_exportServer(
547 $db_select, $whatStrucOrData, $export_plugin, $crlf, $err_url,
548 $export_type, $do_relation, $do_comments, $do_mime, $do_dates,
549 $aliases, $separate_files
551 if (! empty($db_select)) {
552 $tmp_select = implode($db_select, '|');
553 $tmp_select = '|' . $tmp_select . '|';
555 // Walk over databases
556 foreach ($GLOBALS['dblist']->databases as $current_db) {
557 if (isset($tmp_select)
558 && mb_strpos(' ' . $tmp_select, '|' . $current_db . '|')
560 $tables = $GLOBALS['dbi']->getTables($current_db);
561 PMA_exportDatabase(
562 $current_db, $tables, $whatStrucOrData, $tables, $tables,
563 $export_plugin, $crlf, $err_url, $export_type, $do_relation,
564 $do_comments, $do_mime, $do_dates, $aliases,
565 $separate_files == 'database' ? $separate_files : ''
567 if ($separate_files == 'server') {
568 PMA_saveObjectInBuffer($current_db);
571 } // end foreach database
575 * Export at the database level
577 * @param string $db the database to export
578 * @param array $tables the tables to export
579 * @param string $whatStrucOrData structure or data or both
580 * @param array $table_structure whether to export structure for each table
581 * @param array $table_data whether to export data for each table
582 * @param ExportPlugin $export_plugin the selected export plugin
583 * @param string $crlf end of line character(s)
584 * @param string $err_url the URL in case of error
585 * @param string $export_type the export type
586 * @param bool $do_relation whether to export relation info
587 * @param bool $do_comments whether to add comments
588 * @param bool $do_mime whether to add MIME info
589 * @param bool $do_dates whether to add dates
590 * @param array $aliases Alias information for db/table/column
591 * @param string $separate_files whether it is a separate-files export
593 * @return void
595 function PMA_exportDatabase(
596 $db, $tables, $whatStrucOrData, $table_structure, $table_data,
597 $export_plugin, $crlf, $err_url, $export_type, $do_relation,
598 $do_comments, $do_mime, $do_dates, $aliases, $separate_files
600 $db_alias = !empty($aliases[$db]['alias'])
601 ? $aliases[$db]['alias'] : '';
603 if (! $export_plugin->exportDBHeader($db, $db_alias)) {
604 return;
606 if (! $export_plugin->exportDBCreate($db, $export_type, $db_alias)) {
607 return;
609 if ($separate_files == 'database') {
610 PMA_saveObjectInBuffer('database', true);
613 if (($GLOBALS['sql_structure_or_data'] == 'structure'
614 || $GLOBALS['sql_structure_or_data'] == 'structure_and_data')
615 && isset($GLOBALS['sql_procedure_function'])
617 $export_plugin->exportRoutines($db, $aliases);
619 if ($separate_files == 'database') {
620 PMA_saveObjectInBuffer('routines');
624 $views = array();
626 foreach ($tables as $table) {
627 $_table = new Table($table, $db);
628 // if this is a view, collect it for later;
629 // views must be exported after the tables
630 $is_view = $_table->isView();
631 if ($is_view) {
632 $views[] = $table;
634 if (($whatStrucOrData == 'structure'
635 || $whatStrucOrData == 'structure_and_data')
636 && in_array($table, $table_structure)
638 // for a view, export a stand-in definition of the table
639 // to resolve view dependencies (only when it's a single-file export)
640 if ($is_view) {
641 if ($separate_files == ''
642 && isset($GLOBALS['sql_create_view'])
643 && ! $export_plugin->exportStructure(
644 $db, $table, $crlf, $err_url, 'stand_in',
645 $export_type, $do_relation, $do_comments,
646 $do_mime, $do_dates, $aliases
649 break;
651 } else if (isset($GLOBALS['sql_create_table'])) {
653 $table_size = $GLOBALS['maxsize'];
654 // Checking if the maximum table size constrain has been set
655 // And if that constrain is a valid number or not
656 if ($table_size !== '' && is_numeric($table_size)) {
657 // This obtains the current table's size
658 $query = 'SELECT data_length + index_length
659 from information_schema.TABLES
660 WHERE table_schema = "' . $GLOBALS['dbi']->escapeString($db) . '"
661 AND table_name = "' . $GLOBALS['dbi']->escapeString($table) . '"';
663 $size = $GLOBALS['dbi']->fetchValue($query);
664 //Converting the size to MB
665 $size = ($size / 1024) / 1024;
666 if ($size > $table_size) {
667 continue;
671 if (! $export_plugin->exportStructure(
672 $db, $table, $crlf, $err_url, 'create_table',
673 $export_type, $do_relation, $do_comments,
674 $do_mime, $do_dates, $aliases
675 )) {
676 break;
682 // if this is a view or a merge table, don't export data
683 if (($whatStrucOrData == 'data' || $whatStrucOrData == 'structure_and_data')
684 && in_array($table, $table_data)
685 && ! ($is_view)
687 $tableObj = new PMA\libraries\Table($table, $db);
688 $nonGeneratedCols = $tableObj->getNonGeneratedColumns(true);
690 $local_query = 'SELECT ' . implode(', ', $nonGeneratedCols)
691 . ' FROM ' . PMA\libraries\Util::backquote($db)
692 . '.' . PMA\libraries\Util::backquote($table);
694 if (! $export_plugin->exportData(
695 $db, $table, $crlf, $err_url, $local_query, $aliases
696 )) {
697 break;
701 // this buffer was filled, we save it and go to the next one
702 if ($separate_files == 'database') {
703 PMA_saveObjectInBuffer('table_' . $table);
706 // now export the triggers (needs to be done after the data because
707 // triggers can modify already imported tables)
708 if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
709 || $whatStrucOrData == 'structure_and_data')
710 && in_array($table, $table_structure)
712 if (! $export_plugin->exportStructure(
713 $db, $table, $crlf, $err_url, 'triggers',
714 $export_type, $do_relation, $do_comments,
715 $do_mime, $do_dates, $aliases
716 )) {
717 break;
720 if ($separate_files == 'database') {
721 PMA_saveObjectInBuffer('table_' . $table, true);
727 if (isset($GLOBALS['sql_create_view'])) {
729 foreach ($views as $view) {
730 // no data export for a view
731 if ($whatStrucOrData == 'structure'
732 || $whatStrucOrData == 'structure_and_data'
734 if (! $export_plugin->exportStructure(
735 $db, $view, $crlf, $err_url, 'create_view',
736 $export_type, $do_relation, $do_comments,
737 $do_mime, $do_dates, $aliases
738 )) {
739 break;
742 if ($separate_files == 'database') {
743 PMA_saveObjectInBuffer('view_' . $view);
750 if (! $export_plugin->exportDBFooter($db)) {
751 return;
754 // export metadata related to this db
755 if (isset($GLOBALS['sql_metadata'])) {
756 // Types of metadata to export.
757 // In the future these can be allowed to be selected by the user
758 $metadataTypes = PMA_getMetadataTypesToExport();
759 $export_plugin->exportMetadata($db, $tables, $metadataTypes);
761 if ($separate_files == 'database') {
762 PMA_saveObjectInBuffer('metadata');
766 if ($separate_files == 'database') {
767 PMA_saveObjectInBuffer('extra');
770 if (($GLOBALS['sql_structure_or_data'] == 'structure'
771 || $GLOBALS['sql_structure_or_data'] == 'structure_and_data')
772 && isset($GLOBALS['sql_procedure_function'])
774 $export_plugin->exportEvents($db);
776 if ($separate_files == 'database') {
777 PMA_saveObjectInBuffer('events');
783 * Export at the table level
785 * @param string $db the database to export
786 * @param string $table the table to export
787 * @param string $whatStrucOrData structure or data or both
788 * @param ExportPlugin $export_plugin the selected export plugin
789 * @param string $crlf end of line character(s)
790 * @param string $err_url the URL in case of error
791 * @param string $export_type the export type
792 * @param bool $do_relation whether to export relation info
793 * @param bool $do_comments whether to add comments
794 * @param bool $do_mime whether to add MIME info
795 * @param bool $do_dates whether to add dates
796 * @param string $allrows whether "dump all rows" was ticked
797 * @param string $limit_to upper limit
798 * @param string $limit_from starting limit
799 * @param string $sql_query query for which exporting is requested
800 * @param array $aliases Alias information for db/table/column
802 * @return void
804 function PMA_exportTable(
805 $db, $table, $whatStrucOrData, $export_plugin, $crlf, $err_url,
806 $export_type, $do_relation, $do_comments, $do_mime, $do_dates,
807 $allrows, $limit_to, $limit_from, $sql_query, $aliases
809 $db_alias = !empty($aliases[$db]['alias'])
810 ? $aliases[$db]['alias'] : '';
811 if (! $export_plugin->exportDBHeader($db, $db_alias)) {
812 return;
814 if (isset($allrows)
815 && $allrows == '0'
816 && $limit_to > 0
817 && $limit_from >= 0
819 $add_query = ' LIMIT '
820 . (($limit_from > 0) ? $limit_from . ', ' : '')
821 . $limit_to;
822 } else {
823 $add_query = '';
826 $_table = new Table($table, $db);
827 $is_view = $_table->isView();
828 if ($whatStrucOrData == 'structure'
829 || $whatStrucOrData == 'structure_and_data'
832 if ($is_view) {
834 if (isset($GLOBALS['sql_create_view'])) {
835 if (! $export_plugin->exportStructure(
836 $db, $table, $crlf, $err_url, 'create_view',
837 $export_type, $do_relation, $do_comments,
838 $do_mime, $do_dates, $aliases
839 )) {
840 return;
844 } else if (isset($GLOBALS['sql_create_table'])) {
846 if (! $export_plugin->exportStructure(
847 $db, $table, $crlf, $err_url, 'create_table',
848 $export_type, $do_relation, $do_comments,
849 $do_mime, $do_dates, $aliases
850 )) {
851 return;
857 // If this is an export of a single view, we have to export data;
858 // for example, a PDF report
859 // if it is a merge table, no data is exported
860 if ($whatStrucOrData == 'data'
861 || $whatStrucOrData == 'structure_and_data'
863 if (! empty($sql_query)) {
864 // only preg_replace if needed
865 if (! empty($add_query)) {
866 // remove trailing semicolon before adding a LIMIT
867 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
869 $local_query = $sql_query . $add_query;
870 $GLOBALS['dbi']->selectDb($db);
871 } else {
872 // Data is exported only for Non-generated columns
873 $tableObj = new PMA\libraries\Table($table, $db);
874 $nonGeneratedCols = $tableObj->getNonGeneratedColumns(true);
876 $local_query = 'SELECT ' . implode(', ', $nonGeneratedCols)
877 . ' FROM ' . PMA\libraries\Util::backquote($db)
878 . '.' . PMA\libraries\Util::backquote($table) . $add_query;
880 if (! $export_plugin->exportData(
881 $db, $table, $crlf, $err_url, $local_query, $aliases
882 )) {
883 return;
886 // now export the triggers (needs to be done after the data because
887 // triggers can modify already imported tables)
888 if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
889 || $whatStrucOrData == 'structure_and_data')
891 if (! $export_plugin->exportStructure(
892 $db, $table, $crlf, $err_url, 'triggers',
893 $export_type, $do_relation, $do_comments,
894 $do_mime, $do_dates, $aliases
895 )) {
896 return;
899 if (! $export_plugin->exportDBFooter($db)) {
900 return;
903 if (isset($GLOBALS['sql_metadata'])) {
904 // Types of metadata to export.
905 // In the future these can be allowed to be selected by the user
906 $metadataTypes = PMA_getMetadataTypesToExport();
907 $export_plugin->exportMetadata($db, $table, $metadataTypes);
912 * Loads correct page after doing export
914 * @param string $db the database name
915 * @param string $table the table name
916 * @param string $export_type Export type
918 * @return void
920 function PMA_showExportPage($db, $table, $export_type)
922 global $cfg;
923 if ($export_type == 'server') {
924 $active_page = 'server_export.php';
925 include_once 'server_export.php';
926 } elseif ($export_type == 'database') {
927 $active_page = 'db_export.php';
928 include_once 'db_export.php';
929 } else {
930 $active_page = 'tbl_export.php';
931 include_once 'tbl_export.php';
933 exit();
937 * Merge two alias arrays, if array1 and array2 have
938 * conflicting alias then array2 value is used if it
939 * is non empty otherwise array1 value.
941 * @param array $aliases1 first array of aliases
942 * @param array $aliases2 second array of aliases
944 * @return array resultant merged aliases info
946 function PMA_mergeAliases($aliases1, $aliases2)
948 // First do a recursive array merge
949 // on aliases arrays.
950 $aliases = array_merge_recursive($aliases1, $aliases2);
951 // Now, resolve conflicts in aliases, if any
952 foreach ($aliases as $db_name => $db) {
953 // If alias key is an array then
954 // it is a merge conflict.
955 if (isset($db['alias']) && is_array($db['alias'])) {
956 $val1 = $db['alias'][0];
957 $val2 = $db['alias'][1];
958 // Use aliases2 alias if non empty
959 $aliases[$db_name]['alias']
960 = empty($val2) ? $val1 : $val2;
962 if (!isset($db['tables'])) {
963 continue;
965 foreach ($db['tables'] as $tbl_name => $tbl) {
966 if (isset($tbl['alias']) && is_array($tbl['alias'])) {
967 $val1 = $tbl['alias'][0];
968 $val2 = $tbl['alias'][1];
969 // Use aliases2 alias if non empty
970 $aliases[$db_name]['tables'][$tbl_name]['alias']
971 = empty($val2) ? $val1 : $val2;
973 if (!isset($tbl['columns'])) {
974 continue;
976 foreach ($tbl['columns'] as $col => $col_as) {
977 if (isset($col_as) && is_array($col_as)) {
978 $val1 = $col_as[0];
979 $val2 = $col_as[1];
980 // Use aliases2 alias if non empty
981 $aliases[$db_name]['tables'][$tbl_name]['columns'][$col]
982 = empty($val2) ? $val1 : $val2;
987 return $aliases;
991 * Locks tables
993 * @param string $db database name
994 * @param array $tables list of table names
995 * @param string $lockType lock type; "[LOW_PRIORITY] WRITE" or "READ [LOCAL]"
997 * @return mixed result of the query
999 function PMA_lockTables($db, $tables, $lockType = "WRITE")
1001 $locks = array();
1002 foreach ($tables as $table) {
1003 $locks[] = PMA\libraries\Util::backquote($db) . "."
1004 . PMA\libraries\Util::backquote($table) . " " . $lockType;
1007 $sql = "LOCK TABLES " . implode(", ", $locks);
1008 return $GLOBALS['dbi']->tryQuery($sql);
1012 * Releases table locks
1014 * @return mixed result of the query
1016 function PMA_unlockTables()
1018 return $GLOBALS['dbi']->tryQuery("UNLOCK TABLES");
1022 * Returns all the metadata types that can be exported with a database or a table
1024 * @return string[] metadata types.
1026 function PMA_getMetadataTypesToExport()
1028 return array(
1029 'column_info',
1030 'table_uiprefs',
1031 'tracking',
1032 'bookmark',
1033 'relation',
1034 'table_coords',
1035 'pdf_pages',
1036 'savedsearches',
1037 'central_columns',
1038 'export_templates',
1043 * Returns the checked clause, depending on the presence of key in array
1045 * @param string $key the key to look for
1046 * @param array $array array to verify
1048 * @return string the checked clause
1050 function PMA_getCheckedClause($key, $array)
1052 if (in_array($key, $array)) {
1053 return ' checked="checked"';
1054 } else {
1055 return '';