Fixed mysql command syntax for configuration import under windows
[openemr.git] / interface / main / backup.php
bloba8b95994d449db58b837e6db253bdc5648aadf15
1 <?php
2 /* $Id$ */
3 // Copyright (C) 2008-2010 Rod Roark <rod@sunsetsystems.com>
4 // Adapted for cross-platform operation by Bill Cernansky (www.mi-squared.com)
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This script creates a backup tarball and sends it to the users's
12 // browser for download. The tarball includes:
14 // * an OpenEMR database dump (gzipped)
15 // * a phpGACL database dump (gzipped), if phpGACL is used and has
16 // its own database
17 // * a SQL-Ledger database dump (gzipped), if SQL-Ledger is used
18 // (currently skipped on Windows servers)
19 // * the OpenEMR web directory (.tar.gz)
20 // * the phpGACL web directory (.tar.gz), if phpGACL is used
21 // * the SQL-Ledger web directory (.tar.gz), if SQL-Ledger is used
22 // and its web directory exists as a sister of the openemr directory
23 // and has the name "sql-ledger" (otherwise we do not have enough
24 // information to find it)
26 // The OpenEMR web directory is important because it includes config-
27 // uration files, patient documents, and possible customizations, and
28 // also because the database structure is dependent on the installed
29 // OpenEMR version.
31 // This script depends on execution of some external programs:
32 // mysqldump & pg_dump. It has been tested with Debian and Ubuntu
33 // Linux and with Windows XP.
34 // Do not assume that it works for you until you have successfully
35 // tested a restore!
37 require_once("../globals.php");
38 require_once("$srcdir/acl.inc");
39 require_once("$srcdir/log.inc");
41 if (!acl_check('admin', 'super')) die(xl('Not authorized','','','!'));
43 include_once("Archive/Tar.php");
45 // Set up method, which will depend on OS and if pear tar.php is installed
46 if (class_exists('Archive_Tar')) {
47 # pear tar.php is installed so can use os independent method
48 $newBackupMethod = true;
50 elseif (IS_WINDOWS) {
51 # without the tar.php module, can't run backup in windows
52 die(xl("Error. You need to install the Archive/Tar.php php module."));
54 else {
55 # without the tar.php module, can run via system commands in non-windows
56 $newBackupMethod = false;
59 $BTN_TEXT_CREATE = xl('Create Backup');
60 $BTN_TEXT_EXPORT = xl('Export Configuration');
61 $BTN_TEXT_IMPORT = xl('Import Configuration');
62 // ViSolve: Create Log Backup button
63 $BTN_TEXT_CREATE_EVENTLOG = xl('Create Eventlog Backup');
65 $form_step = isset($_POST['form_step']) ? trim($_POST['form_step']) : '0';
66 $form_status = isset($_POST['form_status' ]) ? trim($_POST['form_status' ]) : '';
68 if (!empty($_POST['form_export'])) $form_step = 101;
69 if (!empty($_POST['form_import'])) $form_step = 201;
70 //ViSolve: Assign Unique Number for the Log Creation
71 if (!empty($_POST['form_backup'])) $form_step = 301;
72 // When true the current form will submit itself after a brief pause.
73 $auto_continue = false;
75 # set up main paths
76 $backup_file_prefix = "emr_backup";
77 $backup_file_suffix = ".tar";
78 $TMP_BASE = $GLOBALS['temporary_files_dir'] . "/openemr_web_backup";
79 $BACKUP_DIR = $TMP_BASE . "/emr_backup";
80 $TAR_FILE_PATH = $TMP_BASE . DIRECTORY_SEPARATOR . $backup_file_prefix . $backup_file_suffix;
81 $EXPORT_FILE = $GLOBALS['temporary_files_dir'] . "/openemr_config.sql";
82 $MYSQL_PATH = $GLOBALS['mysql_bin_dir'];
83 $PERL_PATH = $GLOBALS['perl_bin_dir'];
85 if ($form_step == 8) {
86 header("Pragma: public");
87 header("Expires: 0");
88 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
89 header("Content-Type: application/force-download");
90 header("Content-Length: " . filesize($TAR_FILE_PATH));
91 header("Content-Disposition: attachment; filename=" . basename($TAR_FILE_PATH));
92 header("Content-Description: File Transfer");
93 readfile($TAR_FILE_PATH);
94 unlink($TAR_FILE_PATH);
95 obliterate_dir($BACKUP_DIR);
96 exit(0);
99 if ($form_step == 104) {
100 header("Pragma: public");
101 header("Expires: 0");
102 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
103 header("Content-Type: application/force-download");
104 header("Content-Length: " . filesize($EXPORT_FILE));
105 header("Content-Disposition: attachment; filename=" . basename($EXPORT_FILE));
106 header("Content-Description: File Transfer");
107 readfile($EXPORT_FILE);
108 unlink($EXPORT_FILE);
109 exit(0);
112 <html>
114 <head>
115 <link rel="stylesheet" href='<?php echo $css_header ?>' type='text/css'>
116 <title><?php xl('Backup','e'); ?></title>
117 </head>
119 <body class="body_top">
120 <center>
121 &nbsp;<br />
122 <form method='post' action='backup.php' enctype='multipart/form-data'>
124 <table style='width:50em'>
125 <tr>
126 <td>
128 <?php
129 $cmd = '';
130 $mysql_cmd = $MYSQL_PATH . DIRECTORY_SEPARATOR . 'mysql';
131 $mysql_dump_cmd = $mysql_cmd . 'dump';
132 $file_to_compress = ''; // if named, this iteration's file will be gzipped after it is created
133 $eventlog=0; // Eventlog Flag
135 if ($form_step == 0) {
136 echo "<table>\n";
137 echo " <tr>\n";
138 echo " <td><input type='submit' name='form_create' value='$BTN_TEXT_CREATE' /></td>\n";
139 echo " <td>" . xl('Create and download a full backup') . "</td>\n";
140 echo " </tr>\n";
141 // The config import/export feature is optional.
142 if (!empty($GLOBALS['configuration_import_export'])) {
143 echo " <tr>\n";
144 echo " <td><input type='submit' name='form_export' value='$BTN_TEXT_EXPORT' /></td>\n";
145 echo " <td>" . xl('Download configuration data') . "</td>\n";
146 echo " </tr>\n";
147 echo " <tr>\n";
148 echo " <td><input type='submit' name='form_import' value='$BTN_TEXT_IMPORT' /></td>\n";
149 echo " <td>" . xl('Upload configuration data') . "</td>\n";
150 echo " </tr>\n";
152 // ViSolve : Add ' Create Log table backup Button'
153 echo " <tr>\n";
154 echo " <td><input type='submit' name='form_backup' value='$BTN_TEXT_CREATE_EVENTLOG' /></td>\n";
155 echo " <td>" . xl('Create Eventlog Backup') . "</td>\n";
156 echo " </tr>\n";
157 echo " <tr>\n";
158 echo " <td></td><td class='text'><b>" . xl('Note')."</b>&nbsp;" . xl('Please refer to').'&nbsp;README-Log-Backup.txt&nbsp;'.xl('file in the Documentation directory to learn how to automate the process of creating log backups') . "</td>\n";
159 echo " </tr>\n";
160 echo "</table>\n";
163 if ($form_step == 1) {
164 $form_status .= xl('Dumping OpenEMR database') . "...<br />";
165 echo nl2br($form_status);
166 if (file_exists($TAR_FILE_PATH))
167 if (! unlink($TAR_FILE_PATH)) die(xl("Couldn't remove old backup file:") . " " . $TAR_FILE_PATH);
168 if (! obliterate_dir($TMP_BASE)) die(xl("Couldn't remove dir:"). " " . $TMP_BASE);
169 if (! mkdir($BACKUP_DIR, 0777, true)) die(xl("Couldn't create backup dir:") . " " . $BACKUP_DIR);
170 $file_to_compress = "$BACKUP_DIR/openemr.sql"; // gzip this file after creation
172 if($GLOBALS['include_de_identification']==1)
174 //include routines during backup when de-identification is enabled
175 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
176 " -p" . escapeshellarg($sqlconf["pass"]) .
177 " --routines".
178 " --opt --quote-names -r $file_to_compress " .
179 escapeshellarg($sqlconf["dbase"]);
181 else
183 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
184 " -p" . escapeshellarg($sqlconf["pass"]) .
185 " --opt --quote-names -r $file_to_compress " .
186 escapeshellarg($sqlconf["dbase"]);
188 $auto_continue = true;
191 if ($form_step == 2) {
192 if (!empty($phpgacl_location) && $gacl_object->_db_name != $sqlconf["dbase"]) {
193 $form_status .= xl('Dumping phpGACL database') . "...<br />";
194 echo nl2br($form_status);
195 $file_to_compress = "$BACKUP_DIR/phpgacl.sql"; // gzip this file after creation
196 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($gacl_object->_db_user) .
197 " -p" . escapeshellarg($gacl_object->_db_password) .
198 " --opt --quote-names -r $file_to_compress " .
199 escapeshellarg($gacl_object->_db_name);
200 $auto_continue = true;
202 else {
203 ++$form_step;
207 if ($form_step == 3) {
208 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] &&
209 $GLOBALS['oer_config']['ws_accounting']['enabled'] !== 2) {
210 if (IS_WINDOWS) {
211 // Somebody may want to make this work in Windows, if they have SQL-Ledger set up.
212 $form_status .= xl('Skipping SQL-Ledger dump - not implemented for Windows server') . "...<br />";
213 echo nl2br($form_status);
214 ++$form_step;
216 else {
217 $form_status .= xl('Dumping SQL-Ledger database') . "...<br />";
218 echo nl2br($form_status);
219 $file_to_compress = "$BACKUP_DIR/sql-ledger.sql"; // gzip this file after creation
220 $cmd = "PGPASSWORD=" . escapeshellarg($sl_dbpass) . " pg_dump -U " .
221 escapeshellarg($sl_dbuser) . " -h localhost --format=c -f " .
222 "$file_to_compress " . escapeshellarg($sl_dbname);
223 $auto_continue = true;
226 else {
227 ++$form_step;
231 if ($form_step == 4) {
232 $form_status .= xl('Dumping OpenEMR web directory tree') . "...<br />";
233 echo nl2br($form_status);
234 $cur_dir = getcwd();
235 chdir($webserver_root);
237 // Select the files and directories to archive. Basically everything
238 // except site-specific data for other sites.
239 $file_list = array();
240 $dh = opendir($webserver_root);
241 if (!$dh) die("Cannot read directory '$webserver_root'.");
242 while (false !== ($filename = readdir($dh))) {
243 if ($filename == '.' || $filename == '..') continue;
244 if ($filename == 'sites') {
245 // Omit other sites.
246 $file_list[] = "$filename/" . $_SESSION['site_id'];
248 else {
249 $file_list[] = $filename;
252 closedir($dh);
254 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "openemr.tar.gz";
255 if (!create_tar_archive($arch_file, "gz", $file_list))
256 die(xl("An error occurred while dumping OpenEMR web directory tree"));
257 chdir($cur_dir);
258 $auto_continue = true;
261 if ($form_step == 5) {
262 if ((!empty($phpgacl_location)) && ($phpgacl_location != $srcdir."/../gacl") ) {
263 $form_status .= xl('Dumping phpGACL web directory tree') . "...<br />";
264 echo nl2br($form_status);
265 $cur_dir = getcwd();
266 chdir($phpgacl_location);
267 $file_list = array('.'); // archive entire directory
268 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "phpgacl.tar.gz";
269 if (!create_tar_archive($arch_file, "gz", $file_list))
270 die (xl("An error occurred while dumping phpGACL web directory tree"));
271 chdir($cur_dir);
272 $auto_continue = true;
274 else {
275 ++$form_step;
279 if ($form_step == 6) {
280 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] &&
281 $GLOBALS['oer_config']['ws_accounting']['enabled'] !== 2 &&
282 is_dir("$webserver_root/../sql-ledger"))
284 $form_status .= xl('Dumping SQL-Ledger web directory tree') . "...<br />";
285 echo nl2br($form_status);
286 $cur_dir = getcwd();
287 $arch_dir = $webserver_root . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "sql-ledger";
288 chdir($arch_dir);
289 $file_list = array('.'); // archive entire directory
290 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "sql-ledger.tar.gz";
291 if (!create_tar_archive($arch_file, "gz", $file_list))
292 die(xl("An error occurred while dumping SQL-Ledger web directory tree"));
293 chdir($cur_dir);
294 $auto_continue = true;
296 else {
297 ++$form_step;
300 if ($form_step == 7) { // create the final compressed tar containing all files
301 $form_status .= xl('Backup file has been created. Will now send download.') . "<br />";
302 echo nl2br($form_status);
303 $cur_dir = getcwd();
304 chdir($BACKUP_DIR);
305 $file_list = array('.');
306 if (!create_tar_archive($TAR_FILE_PATH, '', $file_list))
307 die(xl("Error: Unable to create downloadable archive"));
308 chdir($cur_dir);
309 /* To log the backup event */
310 if ($GLOBALS['audit_events_backup']){
311 newEvent("backup", $_SESSION['authUser'], $_SESSION['authProvider'], 0,"Backup is completed");
313 $auto_continue = true;
317 if ($form_step == 101) {
318 echo xl('Select the configuration items to export') . ":";
319 echo "<br />&nbsp;<br />\n";
320 echo "<input type='checkbox' name='form_cb_services' value='1' />\n";
321 echo " " . xl('Services') . "<br />\n";
322 echo "<input type='checkbox' name='form_cb_products' value='1' />\n";
323 echo " " . xl('Products') . "<br />\n";
324 echo "<input type='checkbox' name='form_cb_lists' value='1' />\n";
325 echo " " . xl('Lists') . "<br />\n";
326 echo "<input type='checkbox' name='form_cb_layouts' value='1' />\n";
327 echo " " . xl('Layouts') . "<br />\n";
328 echo "<input type='checkbox' name='form_cb_prices' value='1' />\n";
329 echo " " . xl('Prices') . "<br />\n";
330 echo "<input type='checkbox' name='form_cb_categories' value='1' />\n";
331 echo " " . xl('Document Categories') . "<br />\n";
332 echo "<input type='checkbox' name='form_cb_feesheet' value='1' />\n";
333 echo " " . xl('Fee Sheet Options') . "<br />\n";
334 echo "<input type='checkbox' name='form_cb_lang' value='1' />\n";
335 echo " " . xl('Translations') . "<br />\n";
337 echo "&nbsp;<br /><input type='submit' value='" . xl('Continue') . "' />\n";
340 if ($form_step == 102) {
341 $tables = '';
342 if ($_POST['form_cb_services' ]) $tables .= ' codes';
343 if ($_POST['form_cb_products' ]) $tables .= ' drugs drug_templates';
344 if ($_POST['form_cb_lists' ]) $tables .= ' list_options';
345 if ($_POST['form_cb_layouts' ]) $tables .= ' layout_options';
346 if ($_POST['form_cb_prices' ]) $tables .= ' prices';
347 if ($_POST['form_cb_categories']) $tables .= ' categories categories_seq';
348 if ($_POST['form_cb_feesheet' ]) $tables .= ' fee_sheet_options';
349 if ($_POST['form_cb_lang' ]) $tables .= ' lang_languages lang_constants lang_definitions';
350 if ($tables) {
351 $form_status .= xl('Creating export file') . "...<br />";
352 echo nl2br($form_status);
353 if (file_exists($EXPORT_FILE))
354 if (! unlink($EXPORT_FILE)) die(xl("Couldn't remove old export file: ") . $EXPORT_FILE);
356 // The substitutions below use perl because sed's not usually on windows systems.
357 $perl = $PERL_PATH . DIRECTORY_SEPARATOR . 'perl';
358 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
359 " -p" . escapeshellarg($sqlconf["pass"]) .
360 " --opt --quote-names " .
361 escapeshellarg($sqlconf["dbase"]) . " $tables" .
362 " | $perl -pe 's/ DEFAULT CHARSET=utf8//i; s/ collate[ =][^ ;,]*//i;'" .
363 " > $EXPORT_FILE;";
365 else {
366 echo xl('No items were selected!');
367 $form_step = -1;
369 $auto_continue = true;
372 if ($form_step == 103) {
373 $form_status .= xl('Done. Will now send download.') . "<br />";
374 echo nl2br($form_status);
375 $auto_continue = true;
378 if ($form_step == 201) {
379 echo xl('WARNING: This will overwrite configuration information with data from the uploaded file!') . " \n";
380 echo xl('Use this feature only with newly installed sites, ');
381 echo xl('otherwise you will destroy references to/from existing data.') . "\n";
382 echo "<br />&nbsp;<br />\n";
383 echo xl('File to upload') . ":\n";
384 echo "<input type='hidden' name='MAX_FILE_SIZE' value='4000000' />\n";
385 echo "<input type='file' name='userfile' /><br />&nbsp;<br />\n";
386 echo "<input type='submit' value='" . xl('Continue') . "' />\n";
389 if ($form_step == 202) {
390 // Process uploaded config file.
391 if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
392 if (move_uploaded_file($_FILES['userfile']['tmp_name'], $EXPORT_FILE)) {
393 $form_status .= xl('Applying') . "...<br />";
394 echo nl2br($form_status);
395 $cmd = "$mysql_cmd -u" . escapeshellarg($sqlconf["login"]) .
396 " -p" . escapeshellarg($sqlconf["pass"]) . " " .
397 escapeshellarg($sqlconf["dbase"]) .
398 " < $EXPORT_FILE";
400 else {
401 echo xl('Internal error accessing uploaded file!');
402 $form_step = -1;
405 else {
406 echo xl('Upload failed!');
407 $form_step = -1;
409 $auto_continue = true;
412 if ($form_step == 203) {
413 $form_status .= xl('Done') . ".";
414 echo nl2br($form_status);
417 /// ViSolve : EventLog Backup
418 if ($form_step == 301) {
419 # Get the Current Timestamp, to attach with the log backup file
420 $backuptime=date("Ymd_His");
421 # Eventlog backup directory
422 $BACKUP_EVENTLOG_DIR = $GLOBALS['backup_log_dir'] . "/emr_eventlog_backup";
424 # Check if Eventlog Backup directory exists, if not create it with Write permission
425 if (!file_exists($BACKUP_EVENTLOG_DIR))
427 mkdir($BACKUP_EVENTLOG_DIR);
428 chmod($BACKUP_EVENTLOG_DIR,0777);
430 # Frame the Eventlog Backup File Name
431 $BACKUP_EVENTLOG_FILE=$BACKUP_EVENTLOG_DIR.'/eventlog_'.$backuptime.'.sql';
432 # Create a new table similar to event table, rename the existing table as backup table, and rename the new table to event log table. Then export the contents of the table into a text file and drop the table.
433 $res=sqlStatement("create table if not exists log_new like log");
434 $res=sqlStatement("rename table log to log_backup,log_new to log");
435 echo "<br>";
436 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
437 " -p" . escapeshellarg($sqlconf["pass"]) .
438 " --opt --quote-names -r $BACKUP_EVENTLOG_FILE " .
439 escapeshellarg($sqlconf["dbase"]) ." --tables log_backup";
440 # Set Eventlog Flag when it is done
441 $eventlog=1;
442 // 301 If ends here.
445 ++$form_step;
448 </td>
449 </tr>
450 </table>
452 <input type='hidden' name='form_step' value='<?php echo $form_step; ?>' />
453 <input type='hidden' name='form_status' value='<?php echo $form_status; ?>' />
455 </form>
457 <?php
458 ob_flush();
459 flush();
460 if ($cmd) {
461 $tmp0 = exec($cmd, $tmp1, $tmp2);
463 if ($tmp2)
465 if ($eventlog==1)
467 // ViSolve : Restore previous state, if backup fails.
468 $res=sqlStatement("drop table if exists log");
469 $res=sqlStatement("rename table log_backup to log");
471 die("\"$cmd\" returned $tmp2: $tmp0");
473 // ViSolve: If the Eventlog is set, then clear the temporary table -- Start here
474 if ($eventlog==1) {
475 $res=sqlStatement("drop table if exists log_backup");
476 echo "<br><b>";
477 echo xl('Backup Successfully taken in')." ";
478 echo $BACKUP_EVENTLOG_DIR;
479 echo "</b>";
481 // ViSolve: If the Eventlog is set, then clear the temporary table -- Ends here
483 // If a file was flagged to be gzip-compressed after this cmd, do it.
484 if ($file_to_compress) {
485 if (!gz_compress_file($file_to_compress))
486 die (xl("Error in gzip compression of file: ") . $file_to_compress);
490 </center>
492 <?php if ($auto_continue) { ?>
493 <script language="JavaScript">
494 setTimeout("document.forms[0].submit();", 500);
495 </script>
496 <?php }
498 // Recursive directory remove (like an O/S insensitive "rm -rf dirname")
499 function obliterate_dir($dir) {
500 if (!file_exists($dir)) return true;
501 if (!is_dir($dir) || is_link($dir)) return unlink($dir);
502 foreach (scandir($dir) as $item) {
503 if ($item == '.' || $item == '..') continue;
504 if (!obliterate_dir($dir . DIRECTORY_SEPARATOR . $item)) {
505 chmod($dir . DIRECTORY_SEPARATOR . $item, 0777);
506 if (!obliterate_dir($dir . DIRECTORY_SEPARATOR . $item)) return false;
509 return rmdir($dir);
512 // Create a tar archive given the archive file name, compression method if any, and the
513 // array of file/directory names to archive
514 function create_tar_archive($archiveName, $compressMethod, $itemArray) {
515 global $newBackupMethod;
517 if ($newBackupMethod) {
518 // Create a tar object using the pear library
519 // (this is the preferred method)
520 $tar = new Archive_Tar($archiveName, $compressMethod);
521 if ($tar->create($itemArray)) return true;
523 else {
524 // Create the tar files via command line tools
525 // (this method used when the tar pear library is not available)
526 $files = '"' . implode('" "', $itemArray) . '"';
527 if ($compressMethod == "gz") {
528 $command = "tar --same-owner --ignore-failed-read -zcphf $archiveName $files";
530 else {
531 $command = "tar -cpf $archiveName $files";
533 $temp0 = exec($command, $temp1, $temp2);
534 if ($temp2) die("\"$command\" returned $temp2: $temp0");
535 return true;
537 return false;
540 // Compress a file using gzip. Source file removed, leaving only the compressed
541 // *.gz file, just like gzip command line would behave.
542 function gz_compress_file($source) {
543 $dest=$source.'.gz';
544 $error=false;
545 if ($fp_in=fopen($source,'rb')) {
546 if ($fp_out=gzopen($dest,'wb')) {
547 while(!feof($fp_in))
548 gzwrite($fp_out,fread($fp_in,1024*512));
549 gzclose($fp_out);
550 fclose($fp_in);
551 unlink($source);
553 else $error=true;
555 else $error=true;
556 if($error)
557 return false;
558 else
559 return $dest;
563 </body>
564 </html>