Export.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * function for the main export logic
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Core;
  10. use PhpMyAdmin\Encoding;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Plugins;
  13. use PhpMyAdmin\Plugins\ExportPlugin;
  14. use PhpMyAdmin\Sanitize;
  15. use PhpMyAdmin\Table;
  16. use PhpMyAdmin\Url;
  17. use PhpMyAdmin\Util;
  18. use PhpMyAdmin\ZipExtension;
  19. /**
  20. * PhpMyAdmin\Export class
  21. *
  22. * @package PhpMyAdmin
  23. */
  24. class Export
  25. {
  26. /**
  27. * Sets a session variable upon a possible fatal error during export
  28. *
  29. * @return void
  30. */
  31. public static function shutdown()
  32. {
  33. $error = error_get_last();
  34. if ($error != null && mb_strpos($error['message'], "execution time")) {
  35. //set session variable to check if there was error while exporting
  36. $_SESSION['pma_export_error'] = $error['message'];
  37. }
  38. }
  39. /**
  40. * Detect ob_gzhandler
  41. *
  42. * @return bool
  43. */
  44. public static function isGzHandlerEnabled()
  45. {
  46. return in_array('ob_gzhandler', ob_list_handlers());
  47. }
  48. /**
  49. * Detect whether gzencode is needed; it might not be needed if
  50. * the server is already compressing by itself
  51. *
  52. * @return bool Whether gzencode is needed
  53. */
  54. public static function gzencodeNeeded()
  55. {
  56. /*
  57. * We should gzencode only if the function exists
  58. * but we don't want to compress twice, therefore
  59. * gzencode only if transparent compression is not enabled
  60. * and gz compression was not asked via $cfg['OBGzip']
  61. * but transparent compression does not apply when saving to server
  62. */
  63. $chromeAndGreaterThan43 = PMA_USR_BROWSER_AGENT == 'CHROME'
  64. && PMA_USR_BROWSER_VER >= 43; // see bug #4942
  65. if (function_exists('gzencode')
  66. && ((! ini_get('zlib.output_compression')
  67. && ! self::isGzHandlerEnabled())
  68. || $GLOBALS['save_on_server']
  69. || $chromeAndGreaterThan43)
  70. ) {
  71. return true;
  72. }
  73. return false;
  74. }
  75. /**
  76. * Output handler for all exports, if needed buffering, it stores data into
  77. * $dump_buffer, otherwise it prints them out.
  78. *
  79. * @param string $line the insert statement
  80. *
  81. * @return bool Whether output succeeded
  82. */
  83. public static function outputHandler($line)
  84. {
  85. global $time_start, $dump_buffer, $dump_buffer_len, $save_filename;
  86. // Kanji encoding convert feature
  87. if ($GLOBALS['output_kanji_conversion']) {
  88. $line = Encoding::kanjiStrConv(
  89. $line,
  90. $GLOBALS['knjenc'],
  91. isset($GLOBALS['xkana']) ? $GLOBALS['xkana'] : ''
  92. );
  93. }
  94. // If we have to buffer data, we will perform everything at once at the end
  95. if ($GLOBALS['buffer_needed']) {
  96. $dump_buffer .= $line;
  97. if ($GLOBALS['onfly_compression']) {
  98. $dump_buffer_len += strlen($line);
  99. if ($dump_buffer_len > $GLOBALS['memory_limit']) {
  100. if ($GLOBALS['output_charset_conversion']) {
  101. $dump_buffer = Encoding::convertString(
  102. 'utf-8',
  103. $GLOBALS['charset'],
  104. $dump_buffer
  105. );
  106. }
  107. if ($GLOBALS['compression'] == 'gzip'
  108. && self::gzencodeNeeded()
  109. ) {
  110. // as a gzipped file
  111. // without the optional parameter level because it bugs
  112. $dump_buffer = gzencode($dump_buffer);
  113. }
  114. if ($GLOBALS['save_on_server']) {
  115. $write_result = @fwrite($GLOBALS['file_handle'], $dump_buffer);
  116. // Here, use strlen rather than mb_strlen to get the length
  117. // in bytes to compare against the number of bytes written.
  118. if ($write_result != strlen($dump_buffer)) {
  119. $GLOBALS['message'] = Message::error(
  120. __('Insufficient space to save the file %s.')
  121. );
  122. $GLOBALS['message']->addParam($save_filename);
  123. return false;
  124. }
  125. } else {
  126. echo $dump_buffer;
  127. }
  128. $dump_buffer = '';
  129. $dump_buffer_len = 0;
  130. }
  131. } else {
  132. $time_now = time();
  133. if ($time_start >= $time_now + 30) {
  134. $time_start = $time_now;
  135. header('X-pmaPing: Pong');
  136. } // end if
  137. }
  138. } else {
  139. if ($GLOBALS['asfile']) {
  140. if ($GLOBALS['output_charset_conversion']) {
  141. $line = Encoding::convertString(
  142. 'utf-8',
  143. $GLOBALS['charset'],
  144. $line
  145. );
  146. }
  147. if ($GLOBALS['save_on_server'] && mb_strlen($line) > 0) {
  148. $write_result = @fwrite($GLOBALS['file_handle'], $line);
  149. // Here, use strlen rather than mb_strlen to get the length
  150. // in bytes to compare against the number of bytes written.
  151. if (! $write_result
  152. || $write_result != strlen($line)
  153. ) {
  154. $GLOBALS['message'] = Message::error(
  155. __('Insufficient space to save the file %s.')
  156. );
  157. $GLOBALS['message']->addParam($save_filename);
  158. return false;
  159. }
  160. $time_now = time();
  161. if ($time_start >= $time_now + 30) {
  162. $time_start = $time_now;
  163. header('X-pmaPing: Pong');
  164. } // end if
  165. } else {
  166. // We export as file - output normally
  167. echo $line;
  168. }
  169. } else {
  170. // We export as html - replace special chars
  171. echo htmlspecialchars($line);
  172. }
  173. }
  174. return true;
  175. } // end of the 'self::outputHandler()' function
  176. /**
  177. * Returns HTML containing the footer for a displayed export
  178. *
  179. * @param string $back_button the link for going Back
  180. * @param string $refreshButton the link for refreshing page
  181. *
  182. * @return string $html the HTML output
  183. */
  184. public static function getHtmlForDisplayedExportFooter($back_button, $refreshButton)
  185. {
  186. /**
  187. * Close the html tags and add the footers for on-screen export
  188. */
  189. $html = '</textarea>'
  190. . ' </form>'
  191. . '<br />'
  192. // bottom back button
  193. . $back_button
  194. . $refreshButton
  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;
  205. }
  206. /**
  207. * Computes the memory limit for export
  208. *
  209. * @return int $memory_limit the memory limit
  210. */
  211. public static function getMemoryLimit()
  212. {
  213. $memory_limit = trim(ini_get('memory_limit'));
  214. $memory_limit_num = (int)substr($memory_limit, 0, -1);
  215. $lowerLastChar = strtolower(substr($memory_limit, -1));
  216. // 2 MB as default
  217. if (empty($memory_limit) || '-1' == $memory_limit) {
  218. $memory_limit = 2 * 1024 * 1024;
  219. } elseif ($lowerLastChar == 'm') {
  220. $memory_limit = $memory_limit_num * 1024 * 1024;
  221. } elseif ($lowerLastChar == 'k') {
  222. $memory_limit = $memory_limit_num * 1024;
  223. } elseif ($lowerLastChar == 'g') {
  224. $memory_limit = $memory_limit_num * 1024 * 1024 * 1024;
  225. } else {
  226. $memory_limit = (int)$memory_limit;
  227. }
  228. // Some of memory is needed for other things and as threshold.
  229. // During export I had allocated (see memory_get_usage function)
  230. // approx 1.2MB so this comes from that.
  231. if ($memory_limit > 1500000) {
  232. $memory_limit -= 1500000;
  233. }
  234. // Some memory is needed for compression, assume 1/3
  235. $memory_limit /= 8;
  236. return $memory_limit;
  237. }
  238. /**
  239. * Return the filename and MIME type for export file
  240. *
  241. * @param string $export_type type of export
  242. * @param string $remember_template whether to remember template
  243. * @param ExportPlugin $export_plugin the export plugin
  244. * @param string $compression compression asked
  245. * @param string $filename_template the filename template
  246. *
  247. * @return string[] the filename template and mime type
  248. */
  249. public static function getFilenameAndMimetype(
  250. $export_type, $remember_template, $export_plugin, $compression,
  251. $filename_template
  252. ) {
  253. if ($export_type == 'server') {
  254. if (! empty($remember_template)) {
  255. $GLOBALS['PMA_Config']->setUserValue(
  256. 'pma_server_filename_template',
  257. 'Export/file_template_server',
  258. $filename_template
  259. );
  260. }
  261. } elseif ($export_type == 'database') {
  262. if (! empty($remember_template)) {
  263. $GLOBALS['PMA_Config']->setUserValue(
  264. 'pma_db_filename_template',
  265. 'Export/file_template_database',
  266. $filename_template
  267. );
  268. }
  269. } else {
  270. if (! empty($remember_template)) {
  271. $GLOBALS['PMA_Config']->setUserValue(
  272. 'pma_table_filename_template',
  273. 'Export/file_template_table',
  274. $filename_template
  275. );
  276. }
  277. }
  278. $filename = Util::expandUserString($filename_template);
  279. // remove dots in filename (coming from either the template or already
  280. // part of the filename) to avoid a remote code execution vulnerability
  281. $filename = Sanitize::sanitizeFilename($filename, $replaceDots = true);
  282. // Grab basic dump extension and mime type
  283. // Check if the user already added extension;
  284. // get the substring where the extension would be if it was included
  285. $extension_start_pos = mb_strlen($filename) - mb_strlen(
  286. $export_plugin->getProperties()->getExtension()
  287. ) - 1;
  288. $user_extension = mb_substr(
  289. $filename, $extension_start_pos, mb_strlen($filename)
  290. );
  291. $required_extension = "." . $export_plugin->getProperties()->getExtension();
  292. if (mb_strtolower($user_extension) != $required_extension) {
  293. $filename .= $required_extension;
  294. }
  295. $mime_type = $export_plugin->getProperties()->getMimeType();
  296. // If dump is going to be compressed, set correct mime_type and add
  297. // compression to extension
  298. if ($compression == 'gzip') {
  299. $filename .= '.gz';
  300. $mime_type = 'application/x-gzip';
  301. } elseif ($compression == 'zip') {
  302. $filename .= '.zip';
  303. $mime_type = 'application/zip';
  304. }
  305. return array($filename, $mime_type);
  306. }
  307. /**
  308. * Open the export file
  309. *
  310. * @param string $filename the export filename
  311. * @param boolean $quick_export whether it's a quick export or not
  312. *
  313. * @return array the full save filename, possible message and the file handle
  314. */
  315. public static function openFile($filename, $quick_export)
  316. {
  317. $file_handle = null;
  318. $message = '';
  319. $doNotSaveItOver = true;
  320. if(isset($_POST['quick_export_onserver_overwrite'])) {
  321. $doNotSaveItOver = $_POST['quick_export_onserver_overwrite'] != 'saveitover';
  322. }
  323. $save_filename = Util::userDir($GLOBALS['cfg']['SaveDir'])
  324. . preg_replace('@[/\\\\]@', '_', $filename);
  325. if (@file_exists($save_filename)
  326. && ((! $quick_export && empty($_POST['onserver_overwrite']))
  327. || ($quick_export
  328. && $doNotSaveItOver))
  329. ) {
  330. $message = Message::error(
  331. __(
  332. 'File %s already exists on server, '
  333. . 'change filename or check overwrite option.'
  334. )
  335. );
  336. $message->addParam($save_filename);
  337. } elseif (@is_file($save_filename) && ! @is_writable($save_filename)) {
  338. $message = Message::error(
  339. __(
  340. 'The web server does not have permission '
  341. . 'to save the file %s.'
  342. )
  343. );
  344. $message->addParam($save_filename);
  345. } elseif (! $file_handle = @fopen($save_filename, 'w')) {
  346. $message = Message::error(
  347. __(
  348. 'The web server does not have permission '
  349. . 'to save the file %s.'
  350. )
  351. );
  352. $message->addParam($save_filename);
  353. }
  354. return array($save_filename, $message, $file_handle);
  355. }
  356. /**
  357. * Close the export file
  358. *
  359. * @param resource $file_handle the export file handle
  360. * @param string $dump_buffer the current dump buffer
  361. * @param string $save_filename the export filename
  362. *
  363. * @return Message $message a message object (or empty string)
  364. */
  365. public static function closeFile($file_handle, $dump_buffer, $save_filename)
  366. {
  367. $write_result = @fwrite($file_handle, $dump_buffer);
  368. fclose($file_handle);
  369. // Here, use strlen rather than mb_strlen to get the length
  370. // in bytes to compare against the number of bytes written.
  371. if (strlen($dump_buffer) > 0
  372. && (! $write_result || $write_result != strlen($dump_buffer))
  373. ) {
  374. $message = new Message(
  375. __('Insufficient space to save the file %s.'),
  376. Message::ERROR,
  377. array($save_filename)
  378. );
  379. } else {
  380. $message = new Message(
  381. __('Dump has been saved to file %s.'),
  382. Message::SUCCESS,
  383. array($save_filename)
  384. );
  385. }
  386. return $message;
  387. }
  388. /**
  389. * Compress the export buffer
  390. *
  391. * @param array|string $dump_buffer the current dump buffer
  392. * @param string $compression the compression mode
  393. * @param string $filename the filename
  394. *
  395. * @return object $message a message object (or empty string)
  396. */
  397. public static function compress($dump_buffer, $compression, $filename)
  398. {
  399. if ($compression == 'zip' && function_exists('gzcompress')) {
  400. $zipExtension = new ZipExtension();
  401. $filename = substr($filename, 0, -4); // remove extension (.zip)
  402. $dump_buffer = $zipExtension->createFile($dump_buffer, $filename);
  403. } elseif ($compression == 'gzip' && self::gzencodeNeeded()) {
  404. // without the optional parameter level because it bugs
  405. $dump_buffer = gzencode($dump_buffer);
  406. }
  407. return $dump_buffer;
  408. }
  409. /**
  410. * Saves the dump_buffer for a particular table in an array
  411. * Used in separate files export
  412. *
  413. * @param string $object_name the name of current object to be stored
  414. * @param boolean $append optional boolean to append to an existing index or not
  415. *
  416. * @return void
  417. */
  418. public static function saveObjectInBuffer($object_name, $append = false)
  419. {
  420. global $dump_buffer_objects, $dump_buffer, $dump_buffer_len;
  421. if (! empty($dump_buffer)) {
  422. if ($append && isset($dump_buffer_objects[$object_name])) {
  423. $dump_buffer_objects[$object_name] .= $dump_buffer;
  424. } else {
  425. $dump_buffer_objects[$object_name] = $dump_buffer;
  426. }
  427. }
  428. // Re - initialize
  429. $dump_buffer = '';
  430. $dump_buffer_len = 0;
  431. }
  432. /**
  433. * Returns HTML containing the header for a displayed export
  434. *
  435. * @param string $export_type the export type
  436. * @param string $db the database name
  437. * @param string $table the table name
  438. *
  439. * @return string[] the generated HTML and back button
  440. */
  441. public static function getHtmlForDisplayedExportHeader($export_type, $db, $table)
  442. {
  443. $html = '<div>';
  444. /**
  445. * Displays a back button with all the $_POST data in the URL
  446. * (store in a variable to also display after the textarea)
  447. */
  448. $back_button = '<p id="export_back_button">[ <a href="';
  449. if ($export_type == 'server') {
  450. $back_button .= 'server_export.php" data-post="' . Url::getCommon([], '', false);
  451. } elseif ($export_type == 'database') {
  452. $back_button .= 'db_export.php" data-post="' . Url::getCommon(array('db' => $db), '', false);
  453. } else {
  454. $back_button .= 'tbl_export.php" data-post="' . Url::getCommon(
  455. array(
  456. 'db' => $db, 'table' => $table
  457. ), '', false
  458. );
  459. }
  460. // Convert the multiple select elements from an array to a string
  461. if ($export_type == 'database') {
  462. $structOrDataForced = empty($_POST['structure_or_data_forced']);
  463. if ($structOrDataForced && ! isset($_POST['table_structure'])) {
  464. $_POST['table_structure'] = [];
  465. }
  466. if ($structOrDataForced && ! isset($_POST['table_data'])) {
  467. $_POST['table_data'] = [];
  468. }
  469. }
  470. foreach ($_POST as $name => $value) {
  471. if (!is_array($value)) {
  472. $back_button .= '&amp;' . urlencode($name) . '=' . urlencode($value);
  473. }
  474. }
  475. $back_button .= '&amp;repopulate=1">' . __('Back') . '</a> ]</p>';
  476. $html .= '<br />';
  477. $html .= $back_button;
  478. $refreshButton = '<form id="export_refresh_form" method="POST" action="export.php" class="disableAjax">';
  479. $refreshButton .= '[ <a class="disableAjax" onclick="$(this).parent().submit()">'. __('Refresh') .'</a> ]';
  480. foreach($_POST as $name => $value) {
  481. if (is_array($value)) {
  482. foreach($value as $val) {
  483. $refreshButton .= '<input type="hidden" name="' . htmlentities((string) $name) . '[]" value="' . htmlentities((string) $val) . '">';
  484. }
  485. }
  486. else {
  487. $refreshButton .= '<input type="hidden" name="' . htmlentities((string) $name) . '" value="' . htmlentities((string) $value) . '">';
  488. }
  489. }
  490. $refreshButton .= '</form>';
  491. $html .= $refreshButton
  492. . '<br />'
  493. . '<form name="nofunction">'
  494. . '<textarea name="sqldump" cols="50" rows="30" '
  495. . 'id="textSQLDUMP" wrap="OFF">';
  496. return array($html, $back_button, $refreshButton);
  497. }
  498. /**
  499. * Export at the server level
  500. *
  501. * @param string $db_select the selected databases to export
  502. * @param string $whatStrucOrData structure or data or both
  503. * @param ExportPlugin $export_plugin the selected export plugin
  504. * @param string $crlf end of line character(s)
  505. * @param string $err_url the URL in case of error
  506. * @param string $export_type the export type
  507. * @param bool $do_relation whether to export relation info
  508. * @param bool $do_comments whether to add comments
  509. * @param bool $do_mime whether to add MIME info
  510. * @param bool $do_dates whether to add dates
  511. * @param array $aliases alias information for db/table/column
  512. * @param string $separate_files whether it is a separate-files export
  513. *
  514. * @return void
  515. */
  516. public static function exportServer(
  517. $db_select, $whatStrucOrData, $export_plugin, $crlf, $err_url,
  518. $export_type, $do_relation, $do_comments, $do_mime, $do_dates,
  519. array $aliases, $separate_files
  520. ) {
  521. if (! empty($db_select)) {
  522. $tmp_select = implode($db_select, '|');
  523. $tmp_select = '|' . $tmp_select . '|';
  524. }
  525. // Walk over databases
  526. foreach ($GLOBALS['dblist']->databases as $current_db) {
  527. if (isset($tmp_select)
  528. && mb_strpos(' ' . $tmp_select, '|' . $current_db . '|')
  529. ) {
  530. $tables = $GLOBALS['dbi']->getTables($current_db);
  531. self::exportDatabase(
  532. $current_db, $tables, $whatStrucOrData, $tables, $tables,
  533. $export_plugin, $crlf, $err_url, $export_type, $do_relation,
  534. $do_comments, $do_mime, $do_dates, $aliases,
  535. $separate_files == 'database' ? $separate_files : ''
  536. );
  537. if ($separate_files == 'server') {
  538. self::saveObjectInBuffer($current_db);
  539. }
  540. }
  541. } // end foreach database
  542. }
  543. /**
  544. * Export at the database level
  545. *
  546. * @param string $db the database to export
  547. * @param array $tables the tables to export
  548. * @param string $whatStrucOrData structure or data or both
  549. * @param array $table_structure whether to export structure for each table
  550. * @param array $table_data whether to export data for each table
  551. * @param ExportPlugin $export_plugin the selected export plugin
  552. * @param string $crlf end of line character(s)
  553. * @param string $err_url the URL in case of error
  554. * @param string $export_type the export type
  555. * @param bool $do_relation whether to export relation info
  556. * @param bool $do_comments whether to add comments
  557. * @param bool $do_mime whether to add MIME info
  558. * @param bool $do_dates whether to add dates
  559. * @param array $aliases Alias information for db/table/column
  560. * @param string $separate_files whether it is a separate-files export
  561. *
  562. * @return void
  563. */
  564. public static function exportDatabase(
  565. $db, array $tables, $whatStrucOrData, array $table_structure, array $table_data,
  566. $export_plugin, $crlf, $err_url, $export_type, $do_relation,
  567. $do_comments, $do_mime, $do_dates, array $aliases, $separate_files
  568. ) {
  569. $db_alias = !empty($aliases[$db]['alias'])
  570. ? $aliases[$db]['alias'] : '';
  571. if (! $export_plugin->exportDBHeader($db, $db_alias)) {
  572. return;
  573. }
  574. if (! $export_plugin->exportDBCreate($db, $export_type, $db_alias)) {
  575. return;
  576. }
  577. if ($separate_files == 'database') {
  578. self::saveObjectInBuffer('database', true);
  579. }
  580. if (($GLOBALS['sql_structure_or_data'] == 'structure'
  581. || $GLOBALS['sql_structure_or_data'] == 'structure_and_data')
  582. && isset($GLOBALS['sql_procedure_function'])
  583. ) {
  584. $export_plugin->exportRoutines($db, $aliases);
  585. if ($separate_files == 'database') {
  586. self::saveObjectInBuffer('routines');
  587. }
  588. }
  589. $views = array();
  590. foreach ($tables as $table) {
  591. $_table = new Table($table, $db);
  592. // if this is a view, collect it for later;
  593. // views must be exported after the tables
  594. $is_view = $_table->isView();
  595. if ($is_view) {
  596. $views[] = $table;
  597. }
  598. if (($whatStrucOrData == 'structure'
  599. || $whatStrucOrData == 'structure_and_data')
  600. && in_array($table, $table_structure)
  601. ) {
  602. // for a view, export a stand-in definition of the table
  603. // to resolve view dependencies (only when it's a single-file export)
  604. if ($is_view) {
  605. if ($separate_files == ''
  606. && isset($GLOBALS['sql_create_view'])
  607. && ! $export_plugin->exportStructure(
  608. $db, $table, $crlf, $err_url, 'stand_in',
  609. $export_type, $do_relation, $do_comments,
  610. $do_mime, $do_dates, $aliases
  611. )
  612. ) {
  613. break;
  614. }
  615. } elseif (isset($GLOBALS['sql_create_table'])) {
  616. $table_size = $GLOBALS['maxsize'];
  617. // Checking if the maximum table size constrain has been set
  618. // And if that constrain is a valid number or not
  619. if ($table_size !== '' && is_numeric($table_size)) {
  620. // This obtains the current table's size
  621. $query = 'SELECT data_length + index_length
  622. from information_schema.TABLES
  623. WHERE table_schema = "' . $GLOBALS['dbi']->escapeString($db) . '"
  624. AND table_name = "' . $GLOBALS['dbi']->escapeString($table) . '"';
  625. $size = $GLOBALS['dbi']->fetchValue($query);
  626. //Converting the size to MB
  627. $size = ($size / 1024) / 1024;
  628. if ($size > $table_size) {
  629. continue;
  630. }
  631. }
  632. if (! $export_plugin->exportStructure(
  633. $db, $table, $crlf, $err_url, 'create_table',
  634. $export_type, $do_relation, $do_comments,
  635. $do_mime, $do_dates, $aliases
  636. )) {
  637. break;
  638. }
  639. }
  640. }
  641. // if this is a view or a merge table, don't export data
  642. if (($whatStrucOrData == 'data' || $whatStrucOrData == 'structure_and_data')
  643. && in_array($table, $table_data)
  644. && ! ($is_view)
  645. ) {
  646. $tableObj = new Table($table, $db);
  647. $nonGeneratedCols = $tableObj->getNonGeneratedColumns(true);
  648. $local_query = 'SELECT ' . implode(', ', $nonGeneratedCols)
  649. . ' FROM ' . Util::backquote($db)
  650. . '.' . Util::backquote($table);
  651. if (! $export_plugin->exportData(
  652. $db, $table, $crlf, $err_url, $local_query, $aliases
  653. )) {
  654. break;
  655. }
  656. }
  657. // this buffer was filled, we save it and go to the next one
  658. if ($separate_files == 'database') {
  659. self::saveObjectInBuffer('table_' . $table);
  660. }
  661. // now export the triggers (needs to be done after the data because
  662. // triggers can modify already imported tables)
  663. if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
  664. || $whatStrucOrData == 'structure_and_data')
  665. && in_array($table, $table_structure)
  666. ) {
  667. if (! $export_plugin->exportStructure(
  668. $db, $table, $crlf, $err_url, 'triggers',
  669. $export_type, $do_relation, $do_comments,
  670. $do_mime, $do_dates, $aliases
  671. )) {
  672. break;
  673. }
  674. if ($separate_files == 'database') {
  675. self::saveObjectInBuffer('table_' . $table, true);
  676. }
  677. }
  678. }
  679. if (isset($GLOBALS['sql_create_view'])) {
  680. foreach ($views as $view) {
  681. // no data export for a view
  682. if ($whatStrucOrData == 'structure'
  683. || $whatStrucOrData == 'structure_and_data'
  684. ) {
  685. if (! $export_plugin->exportStructure(
  686. $db, $view, $crlf, $err_url, 'create_view',
  687. $export_type, $do_relation, $do_comments,
  688. $do_mime, $do_dates, $aliases
  689. )) {
  690. break;
  691. }
  692. if ($separate_files == 'database') {
  693. self::saveObjectInBuffer('view_' . $view);
  694. }
  695. }
  696. }
  697. }
  698. if (! $export_plugin->exportDBFooter($db)) {
  699. return;
  700. }
  701. // export metadata related to this db
  702. if (isset($GLOBALS['sql_metadata'])) {
  703. // Types of metadata to export.
  704. // In the future these can be allowed to be selected by the user
  705. $metadataTypes = self::getMetadataTypes();
  706. $export_plugin->exportMetadata($db, $tables, $metadataTypes);
  707. if ($separate_files == 'database') {
  708. self::saveObjectInBuffer('metadata');
  709. }
  710. }
  711. if ($separate_files == 'database') {
  712. self::saveObjectInBuffer('extra');
  713. }
  714. if (($GLOBALS['sql_structure_or_data'] == 'structure'
  715. || $GLOBALS['sql_structure_or_data'] == 'structure_and_data')
  716. && isset($GLOBALS['sql_procedure_function'])
  717. ) {
  718. $export_plugin->exportEvents($db);
  719. if ($separate_files == 'database') {
  720. self::saveObjectInBuffer('events');
  721. }
  722. }
  723. }
  724. /**
  725. * Export at the table level
  726. *
  727. * @param string $db the database to export
  728. * @param string $table the table to export
  729. * @param string $whatStrucOrData structure or data or both
  730. * @param ExportPlugin $export_plugin the selected export plugin
  731. * @param string $crlf end of line character(s)
  732. * @param string $err_url the URL in case of error
  733. * @param string $export_type the export type
  734. * @param bool $do_relation whether to export relation info
  735. * @param bool $do_comments whether to add comments
  736. * @param bool $do_mime whether to add MIME info
  737. * @param bool $do_dates whether to add dates
  738. * @param string $allrows whether "dump all rows" was ticked
  739. * @param string $limit_to upper limit
  740. * @param string $limit_from starting limit
  741. * @param string $sql_query query for which exporting is requested
  742. * @param array $aliases Alias information for db/table/column
  743. *
  744. * @return void
  745. */
  746. public static function exportTable(
  747. $db, $table, $whatStrucOrData, $export_plugin, $crlf, $err_url,
  748. $export_type, $do_relation, $do_comments, $do_mime, $do_dates,
  749. $allrows, $limit_to, $limit_from, $sql_query, array $aliases
  750. ) {
  751. $db_alias = !empty($aliases[$db]['alias'])
  752. ? $aliases[$db]['alias'] : '';
  753. if (! $export_plugin->exportDBHeader($db, $db_alias)) {
  754. return;
  755. }
  756. if (isset($allrows)
  757. && $allrows == '0'
  758. && $limit_to > 0
  759. && $limit_from >= 0
  760. ) {
  761. $add_query = ' LIMIT '
  762. . (($limit_from > 0) ? $limit_from . ', ' : '')
  763. . $limit_to;
  764. } else {
  765. $add_query = '';
  766. }
  767. $_table = new Table($table, $db);
  768. $is_view = $_table->isView();
  769. if ($whatStrucOrData == 'structure'
  770. || $whatStrucOrData == 'structure_and_data'
  771. ) {
  772. if ($is_view) {
  773. if (isset($GLOBALS['sql_create_view'])) {
  774. if (! $export_plugin->exportStructure(
  775. $db, $table, $crlf, $err_url, 'create_view',
  776. $export_type, $do_relation, $do_comments,
  777. $do_mime, $do_dates, $aliases
  778. )) {
  779. return;
  780. }
  781. }
  782. } elseif (isset($GLOBALS['sql_create_table'])) {
  783. if (! $export_plugin->exportStructure(
  784. $db, $table, $crlf, $err_url, 'create_table',
  785. $export_type, $do_relation, $do_comments,
  786. $do_mime, $do_dates, $aliases
  787. )) {
  788. return;
  789. }
  790. }
  791. }
  792. // If this is an export of a single view, we have to export data;
  793. // for example, a PDF report
  794. // if it is a merge table, no data is exported
  795. if ($whatStrucOrData == 'data'
  796. || $whatStrucOrData == 'structure_and_data'
  797. ) {
  798. if (! empty($sql_query)) {
  799. // only preg_replace if needed
  800. if (! empty($add_query)) {
  801. // remove trailing semicolon before adding a LIMIT
  802. $sql_query = preg_replace('%;\s*$%', '', $sql_query);
  803. }
  804. $local_query = $sql_query . $add_query;
  805. $GLOBALS['dbi']->selectDb($db);
  806. } else {
  807. // Data is exported only for Non-generated columns
  808. $tableObj = new Table($table, $db);
  809. $nonGeneratedCols = $tableObj->getNonGeneratedColumns(true);
  810. $local_query = 'SELECT ' . implode(', ', $nonGeneratedCols)
  811. . ' FROM ' . Util::backquote($db)
  812. . '.' . Util::backquote($table) . $add_query;
  813. }
  814. if (! $export_plugin->exportData(
  815. $db, $table, $crlf, $err_url, $local_query, $aliases
  816. )) {
  817. return;
  818. }
  819. }
  820. // now export the triggers (needs to be done after the data because
  821. // triggers can modify already imported tables)
  822. if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure'
  823. || $whatStrucOrData == 'structure_and_data')
  824. ) {
  825. if (! $export_plugin->exportStructure(
  826. $db, $table, $crlf, $err_url, 'triggers',
  827. $export_type, $do_relation, $do_comments,
  828. $do_mime, $do_dates, $aliases
  829. )) {
  830. return;
  831. }
  832. }
  833. if (! $export_plugin->exportDBFooter($db)) {
  834. return;
  835. }
  836. if (isset($GLOBALS['sql_metadata'])) {
  837. // Types of metadata to export.
  838. // In the future these can be allowed to be selected by the user
  839. $metadataTypes = self::getMetadataTypes();
  840. $export_plugin->exportMetadata($db, $table, $metadataTypes);
  841. }
  842. }
  843. /**
  844. * Loads correct page after doing export
  845. *
  846. * @param string $db the database name
  847. * @param string $table the table name
  848. * @param string $export_type Export type
  849. *
  850. * @return void
  851. */
  852. public static function showPage($db, $table, $export_type)
  853. {
  854. global $cfg;
  855. if ($export_type == 'server') {
  856. $active_page = 'server_export.php';
  857. include_once 'server_export.php';
  858. } elseif ($export_type == 'database') {
  859. $active_page = 'db_export.php';
  860. include_once 'db_export.php';
  861. } else {
  862. $active_page = 'tbl_export.php';
  863. include_once 'tbl_export.php';
  864. }
  865. exit();
  866. }
  867. /**
  868. * Merge two alias arrays, if array1 and array2 have
  869. * conflicting alias then array2 value is used if it
  870. * is non empty otherwise array1 value.
  871. *
  872. * @param array $aliases1 first array of aliases
  873. * @param array $aliases2 second array of aliases
  874. *
  875. * @return array resultant merged aliases info
  876. */
  877. public static function mergeAliases(array $aliases1, array $aliases2)
  878. {
  879. // First do a recursive array merge
  880. // on aliases arrays.
  881. $aliases = array_merge_recursive($aliases1, $aliases2);
  882. // Now, resolve conflicts in aliases, if any
  883. foreach ($aliases as $db_name => $db) {
  884. // If alias key is an array then
  885. // it is a merge conflict.
  886. if (isset($db['alias']) && is_array($db['alias'])) {
  887. $val1 = $db['alias'][0];
  888. $val2 = $db['alias'][1];
  889. // Use aliases2 alias if non empty
  890. $aliases[$db_name]['alias']
  891. = empty($val2) ? $val1 : $val2;
  892. }
  893. if (!isset($db['tables'])) {
  894. continue;
  895. }
  896. foreach ($db['tables'] as $tbl_name => $tbl) {
  897. if (isset($tbl['alias']) && is_array($tbl['alias'])) {
  898. $val1 = $tbl['alias'][0];
  899. $val2 = $tbl['alias'][1];
  900. // Use aliases2 alias if non empty
  901. $aliases[$db_name]['tables'][$tbl_name]['alias']
  902. = empty($val2) ? $val1 : $val2;
  903. }
  904. if (!isset($tbl['columns'])) {
  905. continue;
  906. }
  907. foreach ($tbl['columns'] as $col => $col_as) {
  908. if (isset($col_as) && is_array($col_as)) {
  909. $val1 = $col_as[0];
  910. $val2 = $col_as[1];
  911. // Use aliases2 alias if non empty
  912. $aliases[$db_name]['tables'][$tbl_name]['columns'][$col]
  913. = empty($val2) ? $val1 : $val2;
  914. }
  915. };
  916. };
  917. }
  918. return $aliases;
  919. }
  920. /**
  921. * Locks tables
  922. *
  923. * @param string $db database name
  924. * @param array $tables list of table names
  925. * @param string $lockType lock type; "[LOW_PRIORITY] WRITE" or "READ [LOCAL]"
  926. *
  927. * @return mixed result of the query
  928. */
  929. public static function lockTables($db, array $tables, $lockType = "WRITE")
  930. {
  931. $locks = array();
  932. foreach ($tables as $table) {
  933. $locks[] = Util::backquote($db) . "."
  934. . Util::backquote($table) . " " . $lockType;
  935. }
  936. $sql = "LOCK TABLES " . implode(", ", $locks);
  937. return $GLOBALS['dbi']->tryQuery($sql);
  938. }
  939. /**
  940. * Releases table locks
  941. *
  942. * @return mixed result of the query
  943. */
  944. public static function unlockTables()
  945. {
  946. return $GLOBALS['dbi']->tryQuery("UNLOCK TABLES");
  947. }
  948. /**
  949. * Returns all the metadata types that can be exported with a database or a table
  950. *
  951. * @return string[] metadata types.
  952. */
  953. public static function getMetadataTypes()
  954. {
  955. return array(
  956. 'column_info',
  957. 'table_uiprefs',
  958. 'tracking',
  959. 'bookmark',
  960. 'relation',
  961. 'table_coords',
  962. 'pdf_pages',
  963. 'savedsearches',
  964. 'central_columns',
  965. 'export_templates',
  966. );
  967. }
  968. /**
  969. * Returns the checked clause, depending on the presence of key in array
  970. *
  971. * @param string $key the key to look for
  972. * @param array $array array to verify
  973. *
  974. * @return string the checked clause
  975. */
  976. public static function getCheckedClause($key, array $array)
  977. {
  978. if (in_array($key, $array)) {
  979. return ' checked="checked"';
  980. }
  981. return '';
  982. }
  983. /**
  984. * get all the export options and verify
  985. * call and include the appropriate Schema Class depending on $export_type
  986. *
  987. * @param string $export_type format of the export
  988. *
  989. * @return void
  990. */
  991. public static function processExportSchema($export_type)
  992. {
  993. /**
  994. * default is PDF, otherwise validate it's only letters a-z
  995. */
  996. if (! isset($export_type) || ! preg_match('/^[a-zA-Z]+$/', $export_type)) {
  997. $export_type = 'pdf';
  998. }
  999. // sanitize this parameter which will be used below in a file inclusion
  1000. $export_type = Core::securePath($export_type);
  1001. // get the specific plugin
  1002. /* @var $export_plugin SchemaPlugin */
  1003. $export_plugin = Plugins::getPlugin(
  1004. "schema",
  1005. $export_type,
  1006. 'libraries/classes/Plugins/Schema/'
  1007. );
  1008. // Check schema export type
  1009. if (! isset($export_plugin)) {
  1010. Core::fatalError(__('Bad type!'));
  1011. }
  1012. $GLOBALS['dbi']->selectDb($_POST['db']);
  1013. $export_plugin->exportSchema($_POST['db']);
  1014. }
  1015. }