The Third Reminders email bug fix - contributed by arnabnaha
[openemr.git] / interface / main / backup.php
blob55ed4a61d1a02c7f036458d46c8e930cfa29c19a
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!
36 set_time_limit(0);
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 " -h" . escapeshellarg($sqlconf["host"]) .
178 " --routines".
179 " --opt --quote-names -r $file_to_compress " .
180 escapeshellarg($sqlconf["dbase"]);
182 else
184 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
185 " -p" . escapeshellarg($sqlconf["pass"]) .
186 " -h" . escapeshellarg($sqlconf["host"]) .
187 " --opt --quote-names -r $file_to_compress " .
188 escapeshellarg($sqlconf["dbase"]);
190 $auto_continue = true;
193 if ($form_step == 2) {
194 if (!empty($phpgacl_location) && $gacl_object->_db_name != $sqlconf["dbase"]) {
195 $form_status .= xl('Dumping phpGACL database') . "...<br />";
196 echo nl2br($form_status);
197 $file_to_compress = "$BACKUP_DIR/phpgacl.sql"; // gzip this file after creation
198 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($gacl_object->_db_user) .
199 " -p" . escapeshellarg($gacl_object->_db_password) .
200 " --opt --quote-names -r $file_to_compress " .
201 escapeshellarg($gacl_object->_db_name);
202 $auto_continue = true;
204 else {
205 ++$form_step;
209 if ($form_step == 3) {
210 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] &&
211 $GLOBALS['oer_config']['ws_accounting']['enabled'] !== 2) {
212 if (IS_WINDOWS) {
213 // Somebody may want to make this work in Windows, if they have SQL-Ledger set up.
214 $form_status .= xl('Skipping SQL-Ledger dump - not implemented for Windows server') . "...<br />";
215 echo nl2br($form_status);
216 ++$form_step;
218 else {
219 $form_status .= xl('Dumping SQL-Ledger database') . "...<br />";
220 echo nl2br($form_status);
221 $file_to_compress = "$BACKUP_DIR/sql-ledger.sql"; // gzip this file after creation
222 $cmd = "PGPASSWORD=" . escapeshellarg($sl_dbpass) . " pg_dump -U " .
223 escapeshellarg($sl_dbuser) . " -h localhost --format=c -f " .
224 "$file_to_compress " . escapeshellarg($sl_dbname);
225 $auto_continue = true;
228 else {
229 ++$form_step;
233 if ($form_step == 4) {
234 $form_status .= xl('Dumping OpenEMR web directory tree') . "...<br />";
235 echo nl2br($form_status);
236 $cur_dir = getcwd();
237 chdir($webserver_root);
239 // Select the files and directories to archive. Basically everything
240 // except site-specific data for other sites.
241 $file_list = array();
242 $dh = opendir($webserver_root);
243 if (!$dh) die("Cannot read directory '$webserver_root'.");
244 while (false !== ($filename = readdir($dh))) {
245 if ($filename == '.' || $filename == '..') continue;
246 if ($filename == 'sites') {
247 // Omit other sites.
248 $file_list[] = "$filename/" . $_SESSION['site_id'];
250 else {
251 $file_list[] = $filename;
254 closedir($dh);
256 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "openemr.tar.gz";
257 if (!create_tar_archive($arch_file, "gz", $file_list))
258 die(xl("An error occurred while dumping OpenEMR web directory tree"));
259 chdir($cur_dir);
260 $auto_continue = true;
263 if ($form_step == 5) {
264 if ((!empty($phpgacl_location)) && ($phpgacl_location != $srcdir."/../gacl") ) {
265 $form_status .= xl('Dumping phpGACL web directory tree') . "...<br />";
266 echo nl2br($form_status);
267 $cur_dir = getcwd();
268 chdir($phpgacl_location);
269 $file_list = array('.'); // archive entire directory
270 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "phpgacl.tar.gz";
271 if (!create_tar_archive($arch_file, "gz", $file_list))
272 die (xl("An error occurred while dumping phpGACL web directory tree"));
273 chdir($cur_dir);
274 $auto_continue = true;
276 else {
277 ++$form_step;
281 if ($form_step == 6) {
282 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] &&
283 $GLOBALS['oer_config']['ws_accounting']['enabled'] !== 2 &&
284 is_dir("$webserver_root/../sql-ledger"))
286 $form_status .= xl('Dumping SQL-Ledger web directory tree') . "...<br />";
287 echo nl2br($form_status);
288 $cur_dir = getcwd();
289 $arch_dir = $webserver_root . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "sql-ledger";
290 chdir($arch_dir);
291 $file_list = array('.'); // archive entire directory
292 $arch_file = $BACKUP_DIR . DIRECTORY_SEPARATOR . "sql-ledger.tar.gz";
293 if (!create_tar_archive($arch_file, "gz", $file_list))
294 die(xl("An error occurred while dumping SQL-Ledger web directory tree"));
295 chdir($cur_dir);
296 $auto_continue = true;
298 else {
299 ++$form_step;
302 if ($form_step == 7) { // create the final compressed tar containing all files
303 $form_status .= xl('Backup file has been created. Will now send download.') . "<br />";
304 echo nl2br($form_status);
305 $cur_dir = getcwd();
306 chdir($BACKUP_DIR);
307 $file_list = array('.');
308 if (!create_tar_archive($TAR_FILE_PATH, '', $file_list))
309 die(xl("Error: Unable to create downloadable archive"));
310 chdir($cur_dir);
311 /* To log the backup event */
312 if ($GLOBALS['audit_events_backup']){
313 newEvent("backup", $_SESSION['authUser'], $_SESSION['authProvider'], 0,"Backup is completed");
315 $auto_continue = true;
319 if ($form_step == 101) {
320 echo xl('Select the configuration items to export') . ":";
321 echo "<br />&nbsp;<br />\n";
322 echo "<input type='checkbox' name='form_cb_services' value='1' />\n";
323 echo " " . xl('Services') . "<br />\n";
324 echo "<input type='checkbox' name='form_cb_products' value='1' />\n";
325 echo " " . xl('Products') . "<br />\n";
326 echo "<input type='checkbox' name='form_cb_lists' value='1' />\n";
327 echo " " . xl('Lists') . "<br />\n";
328 echo "<input type='checkbox' name='form_cb_layouts' value='1' />\n";
329 echo " " . xl('Layouts') . "<br />\n";
330 echo "<input type='checkbox' name='form_cb_prices' value='1' />\n";
331 echo " " . xl('Prices') . "<br />\n";
332 echo "<input type='checkbox' name='form_cb_categories' value='1' />\n";
333 echo " " . xl('Document Categories') . "<br />\n";
334 echo "<input type='checkbox' name='form_cb_feesheet' value='1' />\n";
335 echo " " . xl('Fee Sheet Options') . "<br />\n";
336 echo "<input type='checkbox' name='form_cb_lang' value='1' />\n";
337 echo " " . xl('Translations') . "<br />\n";
339 echo "&nbsp;<br /><input type='submit' value='" . xl('Continue') . "' />\n";
342 if ($form_step == 102) {
343 $tables = '';
344 if ($_POST['form_cb_services' ]) $tables .= ' codes';
345 if ($_POST['form_cb_products' ]) $tables .= ' drugs drug_templates';
346 if ($_POST['form_cb_lists' ]) $tables .= ' list_options';
347 if ($_POST['form_cb_layouts' ]) $tables .= ' layout_options';
348 if ($_POST['form_cb_prices' ]) $tables .= ' prices';
349 if ($_POST['form_cb_categories']) $tables .= ' categories categories_seq';
350 if ($_POST['form_cb_feesheet' ]) $tables .= ' fee_sheet_options';
351 if ($_POST['form_cb_lang' ]) $tables .= ' lang_languages lang_constants lang_definitions';
352 if ($tables) {
353 $form_status .= xl('Creating export file') . "...<br />";
354 echo nl2br($form_status);
355 if (file_exists($EXPORT_FILE))
356 if (! unlink($EXPORT_FILE)) die(xl("Couldn't remove old export file: ") . $EXPORT_FILE);
358 // The substitutions below use perl because sed's not usually on windows systems.
359 $perl = $PERL_PATH . DIRECTORY_SEPARATOR . 'perl';
360 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
361 " -p" . escapeshellarg($sqlconf["pass"]) .
362 " --opt --quote-names " .
363 escapeshellarg($sqlconf["dbase"]) . " $tables" .
364 " | $perl -pe 's/ DEFAULT CHARSET=utf8//i; s/ collate[ =][^ ;,]*//i;'" .
365 " > $EXPORT_FILE;";
367 else {
368 echo xl('No items were selected!');
369 $form_step = -1;
371 $auto_continue = true;
374 if ($form_step == 103) {
375 $form_status .= xl('Done. Will now send download.') . "<br />";
376 echo nl2br($form_status);
377 $auto_continue = true;
380 if ($form_step == 201) {
381 echo xl('WARNING: This will overwrite configuration information with data from the uploaded file!') . " \n";
382 echo xl('Use this feature only with newly installed sites, ');
383 echo xl('otherwise you will destroy references to/from existing data.') . "\n";
384 echo "<br />&nbsp;<br />\n";
385 echo xl('File to upload') . ":\n";
386 echo "<input type='hidden' name='MAX_FILE_SIZE' value='4000000' />\n";
387 echo "<input type='file' name='userfile' /><br />&nbsp;<br />\n";
388 echo "<input type='submit' value='" . xl('Continue') . "' />\n";
391 if ($form_step == 202) {
392 // Process uploaded config file.
393 if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
394 if (move_uploaded_file($_FILES['userfile']['tmp_name'], $EXPORT_FILE)) {
395 $form_status .= xl('Applying') . "...<br />";
396 echo nl2br($form_status);
397 $cmd = "$mysql_cmd -u" . escapeshellarg($sqlconf["login"]) .
398 " -p" . escapeshellarg($sqlconf["pass"]) . " " .
399 escapeshellarg($sqlconf["dbase"]) .
400 " < $EXPORT_FILE";
402 else {
403 echo xl('Internal error accessing uploaded file!');
404 $form_step = -1;
407 else {
408 echo xl('Upload failed!');
409 $form_step = -1;
411 $auto_continue = true;
414 if ($form_step == 203) {
415 $form_status .= xl('Done') . ".";
416 echo nl2br($form_status);
419 /// ViSolve : EventLog Backup
420 if ($form_step == 301) {
421 # Get the Current Timestamp, to attach with the log backup file
422 $backuptime=date("Ymd_His");
423 # Eventlog backup directory
424 $BACKUP_EVENTLOG_DIR = $GLOBALS['backup_log_dir'] . "/emr_eventlog_backup";
426 # Check if Eventlog Backup directory exists, if not create it with Write permission
427 if (!file_exists($BACKUP_EVENTLOG_DIR))
429 mkdir($BACKUP_EVENTLOG_DIR);
430 chmod($BACKUP_EVENTLOG_DIR,0777);
432 # Frame the Eventlog Backup File Name
433 $BACKUP_EVENTLOG_FILE=$BACKUP_EVENTLOG_DIR.'/eventlog_'.$backuptime.'.sql';
434 # 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.
435 $res=sqlStatement("create table if not exists log_new like log");
436 $res=sqlStatement("rename table log to log_backup,log_new to log");
437 echo "<br>";
438 $cmd = "$mysql_dump_cmd -u " . escapeshellarg($sqlconf["login"]) .
439 " -p" . escapeshellarg($sqlconf["pass"]) .
440 " --opt --quote-names -r $BACKUP_EVENTLOG_FILE " .
441 escapeshellarg($sqlconf["dbase"]) ." --tables log_backup";
442 # Set Eventlog Flag when it is done
443 $eventlog=1;
444 // 301 If ends here.
447 ++$form_step;
450 </td>
451 </tr>
452 </table>
454 <input type='hidden' name='form_step' value='<?php echo $form_step; ?>' />
455 <input type='hidden' name='form_status' value='<?php echo $form_status; ?>' />
457 </form>
459 <?php
460 ob_flush();
461 flush();
462 if ($cmd) {
463 $tmp0 = exec($cmd, $tmp1, $tmp2);
465 if ($tmp2)
467 if ($eventlog==1)
469 // ViSolve : Restore previous state, if backup fails.
470 $res=sqlStatement("drop table if exists log");
471 $res=sqlStatement("rename table log_backup to log");
473 die("\"$cmd\" returned $tmp2: $tmp0");
475 // ViSolve: If the Eventlog is set, then clear the temporary table -- Start here
476 if ($eventlog==1) {
477 $res=sqlStatement("drop table if exists log_backup");
478 echo "<br><b>";
479 echo xl('Backup Successfully taken in')." ";
480 echo $BACKUP_EVENTLOG_DIR;
481 echo "</b>";
483 // ViSolve: If the Eventlog is set, then clear the temporary table -- Ends here
485 // If a file was flagged to be gzip-compressed after this cmd, do it.
486 if ($file_to_compress) {
487 if (!gz_compress_file($file_to_compress))
488 die (xl("Error in gzip compression of file: ") . $file_to_compress);
492 </center>
494 <?php if ($auto_continue) { ?>
495 <script language="JavaScript">
496 setTimeout("document.forms[0].submit();", 500);
497 </script>
498 <?php }
500 // Recursive directory remove (like an O/S insensitive "rm -rf dirname")
501 function obliterate_dir($dir) {
502 if (!file_exists($dir)) return true;
503 if (!is_dir($dir) || is_link($dir)) return unlink($dir);
504 foreach (scandir($dir) as $item) {
505 if ($item == '.' || $item == '..') continue;
506 if (!obliterate_dir($dir . DIRECTORY_SEPARATOR . $item)) {
507 chmod($dir . DIRECTORY_SEPARATOR . $item, 0777);
508 if (!obliterate_dir($dir . DIRECTORY_SEPARATOR . $item)) return false;
511 return rmdir($dir);
514 // Create a tar archive given the archive file name, compression method if any, and the
515 // array of file/directory names to archive
516 function create_tar_archive($archiveName, $compressMethod, $itemArray) {
517 global $newBackupMethod;
519 if ($newBackupMethod) {
520 // Create a tar object using the pear library
521 // (this is the preferred method)
522 $tar = new Archive_Tar($archiveName, $compressMethod);
523 if ($tar->create($itemArray)) return true;
525 else {
526 // Create the tar files via command line tools
527 // (this method used when the tar pear library is not available)
528 $files = '"' . implode('" "', $itemArray) . '"';
529 if ($compressMethod == "gz") {
530 $command = "tar --same-owner --ignore-failed-read -zcphf $archiveName $files";
532 else {
533 $command = "tar -cpf $archiveName $files";
535 $temp0 = exec($command, $temp1, $temp2);
536 if ($temp2) die("\"$command\" returned $temp2: $temp0");
537 return true;
539 return false;
542 // Compress a file using gzip. Source file removed, leaving only the compressed
543 // *.gz file, just like gzip command line would behave.
544 function gz_compress_file($source) {
545 $dest=$source.'.gz';
546 $error=false;
547 if ($fp_in=fopen($source,'rb')) {
548 if ($fp_out=gzopen($dest,'wb')) {
549 while(!feof($fp_in))
550 gzwrite($fp_out,fread($fp_in,1024*512));
551 gzclose($fp_out);
552 fclose($fp_in);
553 unlink($source);
555 else $error=true;
557 else $error=true;
558 if($error)
559 return false;
560 else
561 return $dest;
565 </body>
566 </html>