1. Check existence of mb_string, mysql and xml extensions before installation.
[openemr.git] / phpmyadmin / libraries / export.lib.php
blobe7ebb13392be0c0cc8cbd89e562edfd472300fd2
1 <?php
3 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 /**
5 * function for the main export logic
7 * @package PhpMyAdmin
8 */
10 if (! defined('PHPMYADMIN')) {
11 exit;
14 /**
15 * Sets a session variable upon a possible fatal error during export
17 * @return void
19 function PMA_shutdownDuringExport()
21 $a = error_get_last();
22 if ($a != null
23 && /*overload*/mb_strpos($a['message'], "execution time")
24 ) {
25 //write in partially downloaded file for future reference of user
26 print_r($a);
27 //set session variable to check if there was error while exporting
28 $_SESSION['pma_export_error'] = $a['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 = PMA_Kanji_strConv(
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 += /*overload*/mb_strlen($line);
101 if ($dump_buffer_len > $GLOBALS['memory_limit']) {
102 if ($GLOBALS['output_charset_conversion']) {
103 $dump_buffer = PMA_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'] = PMA_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 = PMA_convertString(
144 'utf-8',
145 $GLOBALS['charset'],
146 $line
149 if ($GLOBALS['save_on_server'] && /*overload*/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'] = PMA_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 array 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_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 = PMA_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 = /*overload*/mb_strlen($filename) - /*overload*/mb_strlen(
291 $export_plugin->getProperties()->getExtension()
292 ) - 1;
293 $user_extension = /*overload*/mb_substr(
294 $filename, $extension_start_pos, /*overload*/mb_strlen($filename)
296 $required_extension = "." . $export_plugin->getProperties()->getExtension();
297 if (/*overload*/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_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 = PMA_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 = PMA_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 = PMA_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 object $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 (/*overload*/mb_strlen($dump_buffer) > 0
378 && (! $write_result || $write_result != strlen($dump_buffer))
380 $message = new PMA_Message(
381 __('Insufficient space to save the file %s.'),
382 PMA_Message::ERROR,
383 array($save_filename)
385 } else {
386 $message = new PMA_Message(
387 __('Dump has been saved to file %s.'),
388 PMA_Message::SUCCESS,
389 array($save_filename)
392 return $message;
396 * Compress the export buffer
398 * @param 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 array 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' . PMA_URL_getCommon();
481 } elseif ($export_type == 'database') {
482 $back_button .= 'db_export.php' . PMA_URL_getCommon(array('db' => $db));
483 } else {
484 $back_button .= 'tbl_export.php' . PMA_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['pma']->databases as $current_db) {
557 if (isset($tmp_select)
558 && /*overload*/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 PMA_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 = "' . $db . '"
661 AND table_name = "' . $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'
684 || $whatStrucOrData == 'structure_and_data')
685 && in_array($table, $table_data)
686 && ! ($is_view)
688 $local_query = 'SELECT * FROM ' . PMA_Util::backquote($db)
689 . '.' . PMA_Util::backquote($table);
690 if (! $export_plugin->exportData(
691 $db, $table, $crlf, $err_url, $local_query, $aliases
692 )) {
693 break;
697 // this buffer was filled, we save it and go to the next one
698 if ($separate_files == 'database') {
699 PMA_saveObjectInBuffer('table_' . $table);
702 // now export the triggers (needs to be done after the data because
703 // triggers can modify already imported tables)
704 if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
705 || $whatStrucOrData == 'structure_and_data')
706 && in_array($table, $table_structure)
708 if (! $export_plugin->exportStructure(
709 $db, $table, $crlf, $err_url, 'triggers',
710 $export_type, $do_relation, $do_comments,
711 $do_mime, $do_dates, $aliases
712 )) {
713 break;
716 if ($separate_files == 'database') {
717 PMA_saveObjectInBuffer('table_' . $table, true);
723 if (isset($GLOBALS['sql_create_view'])) {
725 foreach ($views as $view) {
726 // no data export for a view
727 if ($whatStrucOrData == 'structure'
728 || $whatStrucOrData == 'structure_and_data'
730 if (! $export_plugin->exportStructure(
731 $db, $view, $crlf, $err_url, 'create_view',
732 $export_type, $do_relation, $do_comments,
733 $do_mime, $do_dates, $aliases
734 )) {
735 break;
738 if ($separate_files == 'database') {
739 PMA_saveObjectInBuffer('view_' . $view);
746 if (! $export_plugin->exportDBFooter($db)) {
747 return;
750 // export metadata related to this db
751 if (isset($GLOBALS['sql_metadata'])) {
752 // Types of metadata to export.
753 // In the future these can be allowed to be selected by the user
754 $metadataTypes = PMA_getMetadataTypesToExport();
755 $export_plugin->exportMetadata($db, $tables, $metadataTypes);
757 if ($separate_files == 'database') {
758 PMA_saveObjectInBuffer('metadata');
762 if ($separate_files == 'database') {
763 PMA_saveObjectInBuffer('extra');
766 if (($GLOBALS['sql_structure_or_data'] == 'structure'
767 || $GLOBALS['sql_structure_or_data'] == 'structure_and_data')
768 && isset($GLOBALS['sql_procedure_function'])
770 $export_plugin->exportEvents($db);
772 if ($separate_files == 'database') {
773 PMA_saveObjectInBuffer('events');
779 * Export at the table level
781 * @param string $db the database to export
782 * @param string $table the table to export
783 * @param string $whatStrucOrData structure or data or both
784 * @param ExportPlugin $export_plugin the selected export plugin
785 * @param string $crlf end of line character(s)
786 * @param string $err_url the URL in case of error
787 * @param string $export_type the export type
788 * @param bool $do_relation whether to export relation info
789 * @param bool $do_comments whether to add comments
790 * @param bool $do_mime whether to add MIME info
791 * @param bool $do_dates whether to add dates
792 * @param string $allrows whether "dump all rows" was ticked
793 * @param string $limit_to upper limit
794 * @param string $limit_from starting limit
795 * @param string $sql_query query for which exporting is requested
796 * @param array $aliases Alias information for db/table/column
798 * @return void
800 function PMA_exportTable(
801 $db, $table, $whatStrucOrData, $export_plugin, $crlf, $err_url,
802 $export_type, $do_relation, $do_comments, $do_mime, $do_dates,
803 $allrows, $limit_to, $limit_from, $sql_query, $aliases
805 $db_alias = !empty($aliases[$db]['alias'])
806 ? $aliases[$db]['alias'] : '';
807 if (! $export_plugin->exportDBHeader($db, $db_alias)) {
808 return;
810 if (isset($allrows)
811 && $allrows == '0'
812 && $limit_to > 0
813 && $limit_from >= 0
815 $add_query = ' LIMIT '
816 . (($limit_from > 0) ? $limit_from . ', ' : '')
817 . $limit_to;
818 } else {
819 $add_query = '';
822 $_table = new PMA_Table($table, $db);
823 $is_view = $_table->isView();
824 if ($whatStrucOrData == 'structure'
825 || $whatStrucOrData == 'structure_and_data'
828 if ($is_view) {
830 if (isset($GLOBALS['sql_create_view'])) {
831 if (! $export_plugin->exportStructure(
832 $db, $table, $crlf, $err_url, 'create_view',
833 $export_type, $do_relation, $do_comments,
834 $do_mime, $do_dates, $aliases
835 )) {
836 return;
840 } else if (isset($GLOBALS['sql_create_table'])) {
842 if (! $export_plugin->exportStructure(
843 $db, $table, $crlf, $err_url, 'create_table',
844 $export_type, $do_relation, $do_comments,
845 $do_mime, $do_dates, $aliases
846 )) {
847 return;
853 // If this is an export of a single view, we have to export data;
854 // for example, a PDF report
855 // if it is a merge table, no data is exported
856 if ($whatStrucOrData == 'data'
857 || $whatStrucOrData == 'structure_and_data'
859 if (! empty($sql_query)) {
860 // only preg_replace if needed
861 if (! empty($add_query)) {
862 // remove trailing semicolon before adding a LIMIT
863 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
865 $local_query = $sql_query . $add_query;
866 $GLOBALS['dbi']->selectDb($db);
867 } else {
868 $local_query = 'SELECT * FROM ' . PMA_Util::backquote($db)
869 . '.' . PMA_Util::backquote($table) . $add_query;
871 if (! $export_plugin->exportData(
872 $db, $table, $crlf, $err_url, $local_query, $aliases
873 )) {
874 return;
877 // now export the triggers (needs to be done after the data because
878 // triggers can modify already imported tables)
879 if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
880 || $whatStrucOrData == 'structure_and_data')
882 if (! $export_plugin->exportStructure(
883 $db, $table, $crlf, $err_url, 'triggers',
884 $export_type, $do_relation, $do_comments,
885 $do_mime, $do_dates, $aliases
886 )) {
887 return;
890 if (! $export_plugin->exportDBFooter($db)) {
891 return;
894 if (isset($GLOBALS['sql_metadata'])) {
895 // Types of metadata to export.
896 // In the future these can be allowed to be selected by the user
897 $metadataTypes = PMA_getMetadataTypesToExport();
898 $export_plugin->exportMetadata($db, $table, $metadataTypes);
903 * Loads correct page after doing export
905 * @param string $db the database name
906 * @param string $table the table name
907 * @param string $export_type Export type
909 * @return void
911 function PMA_showExportPage($db, $table, $export_type)
913 global $cfg;
914 if ($export_type == 'server') {
915 $active_page = 'server_export.php';
916 include_once 'server_export.php';
917 } elseif ($export_type == 'database') {
918 $active_page = 'db_export.php';
919 include_once 'db_export.php';
920 } else {
921 $active_page = 'tbl_export.php';
922 include_once 'tbl_export.php';
924 exit();
928 * Merge two alias arrays, if array1 and array2 have
929 * conflicting alias then array2 value is used if it
930 * is non empty otherwise array1 value.
932 * @param array $aliases1 first array of aliases
933 * @param array $aliases2 second array of aliases
935 * @return array resultant merged aliases info
937 function PMA_mergeAliases($aliases1, $aliases2)
939 // First do a recursive array merge
940 // on aliases arrays.
941 $aliases = array_merge_recursive($aliases1, $aliases2);
942 // Now, resolve conflicts in aliases, if any
943 foreach ($aliases as $db_name => $db) {
944 // If alias key is an array then
945 // it is a merge conflict.
946 if (isset($db['alias']) && is_array($db['alias'])) {
947 $val1 = $db['alias'][0];
948 $val2 = $db['alias'][1];
949 // Use aliases2 alias if non empty
950 $aliases[$db_name]['alias']
951 = empty($val2) ? $val1 : $val2;
953 if (!isset($db['tables'])) {
954 continue;
956 foreach ($db['tables'] as $tbl_name => $tbl) {
957 if (isset($tbl['alias']) && is_array($tbl['alias'])) {
958 $val1 = $tbl['alias'][0];
959 $val2 = $tbl['alias'][1];
960 // Use aliases2 alias if non empty
961 $aliases[$db_name]['tables'][$tbl_name]['alias']
962 = empty($val2) ? $val1 : $val2;
964 if (!isset($tbl['columns'])) {
965 continue;
967 foreach ($tbl['columns'] as $col => $col_as) {
968 if (isset($col_as) && is_array($col_as)) {
969 $val1 = $col_as[0];
970 $val2 = $col_as[1];
971 // Use aliases2 alias if non empty
972 $aliases[$db_name]['tables'][$tbl_name]['columns'][$col]
973 = empty($val2) ? $val1 : $val2;
978 return $aliases;
982 * Locks tables
984 * @param string $db database name
985 * @param array $tables list of table names
986 * @param string $lockType lock type; "[LOW_PRIORITY] WRITE" or "READ [LOCAL]"
988 * @return mixed result of the query
990 function PMA_lockTables($db, $tables, $lockType = "WRITE")
992 $locks = array();
993 foreach ($tables as $table) {
994 $locks[] = PMA_Util::backquote($db) . "." . PMA_Util::backquote($table)
995 . " " . $lockType;
998 $sql = "LOCK TABLES " . implode(", ", $locks);
999 return $GLOBALS['dbi']->tryQuery($sql);
1003 * Releases table locks
1005 * @return mixed result of the query
1007 function PMA_unlockTables()
1009 return $GLOBALS['dbi']->tryQuery("UNLOCK TABLES");
1013 * Returns all the metadata types that can be exported with a database or a table
1015 * @return array metadata types.
1017 function PMA_getMetadataTypesToExport()
1019 return array(
1020 'column_info',
1021 'table_uiprefs',
1022 'tracking',
1023 'bookmark',
1024 'relation',
1025 'table_coords',
1026 'pdf_pages',
1027 'savedsearches',
1028 'central_columns',
1029 'export_templates',
1034 * Returns the checked clause, depending on the presence of key in array
1036 * @param string $key the key to look for
1037 * @param array $array array to verify
1039 * @return string the checked clause
1041 function PMA_getCheckedClause($key, $array)
1043 if (in_array($key, $array)) {
1044 return ' checked="checked"';
1045 } else {
1046 return '';