<?php
/*
  $Id: backup.php,v 6.5.4 2017/12/17 01:41:11 datazen Exp $

  CRE Loaded, Open Source E-Commerce Solutions
  http://www.loadedcommerce.com

  Copyright (c) 2017 Loaded Commerce
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

require('includes/application_top.php');

$debug=MYSQL_BACKUP_DEBUG;

//*******************
//set variables to 0
 $d_serv_gzip_avail = '0' ;
 $d_serv_gunzip_avail = '0' ;
 $d_serv_zip_avail = '0' ;
 $d_serv_unzip_avail = '0' ;
 $d_php_gzip_on = '0';

 $server_os_id = 0;
//*******************
//os detect we need to know if this is a Win32 or Unix compat
//if WINNT then we must use php built in gzip $server_os_id 0 = non found,  1= poxis compatible, 2 = windows

//if (function_exists(PHP_OS) ){
  $server_os = PHP_OS ;

  if ($server_os == 'WINNT'){
    $server_os_id = '2' ;
  } else if ($server_os == 'LINUX'){
    $server_os_id = '1' ;
  }else if ($server_os == 'FreeBSD'){
    $server_os_id = '1' ;
  }
//}
//*******************
//gzip detect
  if (function_exists('exec')) {
    $gzip_path_1 = exec('which gzip');

  if($gzip_path_1 > ' '){
    $d_serv_gzip_avail = '1' ;
   }
  }
//*******************
 //gunzip detect
   if (function_exists('exec')) {
     $gunzip_path_1 = exec('which gunzip');

   if($gunzip_path_1 > ' '){
     $d_serv_gunzip_avail = '1' ;
    }
  }
//*******************
//zip detect
  if (function_exists('exec')) {
    $zip_path_1 = exec('which zip');

  if($zip_path_1 > ' '){
    $d_serv_zip_avail = '1' ;
   }
  }

//*******************
//unzip detect
  if (function_exists('exec')) {
    $unzip_path_1 = exec('which unzip');

  if($unzip_path_1 > ' '){
    $d_serv_unzip_avail = '1' ;
   }
  }

//*******************

//zip detect settings

// note ADMIN_GZIP_LEVEL is set in lcadmin/includes/application_top_admin_cre_setting.php the admin only
//when backup mysql has it's own configuration settings change below to new define
//$gzip_level_set = ADMIN_GZIP_LEVEL ;
  $gzip_level_set = 9 ;


// if avaible on server don't use php gzip
  if ($d_serv_gzip_avail == '0'){
    if (extension_loaded('zlib') == 1) {
      $d_php_gzip_on = '1' ;
      $gzip_file_ext = '.gz';
    }
  }

// we cannot have zlib.output_handler set to on if we use regualar gzip compression
//gzopen

  if (isset($_GET['debug']) && $_GET['debug']=='ON'){
    $debug='ON';
  }
// Note that LOCAL_EXE_MYSQL and LOCAL_EXE_MYSQL_DUMP are defined in the /lcadmin/includes/application_top_admin_cre_setting.php file
// These can occasionally be overridden in the URL by specifying &tool=/path/to/foo/bar/plus/utilname, depending on server support
// if windows application_top_admin_cre_setting.php must be edited since I have not fond an elegent was to search for these two apps

if ($server_os_id == '2'){
  $mysql_exe = LOCAL_EXE_MYSQL ;
  $mysqldump_exe = LOCAL_EXE_MYSQLDUMP ;
}

//if posix then issues a which command

if ($server_os_id != '2'){
  //mysql and mysql dump detect
  if (function_exists('exec')) {
    $mysql_path_1 = exec('which mysql');

    if(!($mysql_path_1 == ' ')){
      $d_serv_mysql_avail = '1' ;
    }
  }
  $mysql_exe = $mysql_path_1 ;

  if (function_exists('exec')) {
    $mysql_dump_path_1 = exec('which mysqldump');

    if(!($mysql_dump_path_1 == ' ')){
      $d_serv_mysqldump_avail = '1' ;
    }
  }
  $mysqldump_exe = $mysql_dump_path_1;

}
// debug on
if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_ERROR_MSG_9,'warning');

//server OS detect
if (($debug=='ON') && ($server_os_id == '0')) {
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_12,'warning');
} else if (($debug=='ON') && ($server_os_id == '1')) {
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_7,'warning');
} else if (($debug=='ON') && ($server_os_id == '2')) {
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_8,'warning');
}

//zip and or zlib detect
if (($debug=='ON') && ($d_serv_gzip_avail == '1') ){
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_1,'warning');
} else if (($debug=='ON') && ($d_serv_gzip_avail == '0') ) {
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_5,'warning');
}

if (($debug=='ON') && ($d_serv_gunzip_avail == '1')){
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_2,'warning');
}
if (($debug=='ON') && ($d_serv_zip_avail == '1')){
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_3,'warning');
} else if (($debug=='ON') && ($d_serv_zip_avail == '0') ) {
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_6,'warning');
}
if (($debug=='ON') && ($d_serv_unzip_avail == '1')){
  $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_4,'warning');
}

//mysql detect
if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_ERROR_MSG_2,'warning');
if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_ERROR_MSG_7 .$mysql_exe .'<br>','warning');
if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_ERROR_MSG_8. $mysqldump_exe .'<br><br>','warning');

$action = (isset($_GET['action']) ? $_GET['action'] : '');

if (tep_not_null($action)) {
  switch ($action) {
    case 'forget':
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key = 'DB_LAST_RESTORE'");

      $messageStack->add_session('search', SUCCESS_LAST_RESTORE_CLEARED, 'success');

      tep_redirect(tep_href_link(FILENAME_BACKUP));
      break;
    case 'backupnow':
      tep_set_time_limit(250);  // not sure if this is needed anymore?
      $backup_file = 'db_' . DB_DATABASE . '-' . date('YmdHis') . '.sql';
      $fp = fopen(DIR_FS_BACKUP . $backup_file, 'w');

      $schema = '# osCommerce, Open Source E-Commerce Solutions' . "\n" .
                '# http://www.oscommerce.com' . "\n" .
                '#' . "\n" .
                '# Database Backup For ' . STORE_NAME . "\n" .
                '# Copyright (c) ' . date('Y') . ' ' . STORE_OWNER . "\n" .
                '#' . "\n" .
                '# Database: ' . DB_DATABASE . "\n" .
                '# Database Server: ' . DB_SERVER . "\n" .
                '#' . "\n" .
                '# Backup Date: ' . date(PHP_DATE_TIME_FORMAT) . "\n\n";
      fputs($fp, $schema);

      $tables_query = tep_db_query('show tables');
      while ($tables = tep_db_fetch_array($tables_query)) {
        $table = current($tables);

        $schema = 'drop table if exists ' . $table . ';' . "\n" .
                  'create table ' . $table . ' (' . "\n";

        $table_list = array();
        $fields_query = tep_db_query("show fields from " . $table);
        while ($fields = tep_db_fetch_array($fields_query)) {
          $table_list[] = $fields['Field'];

          $schema .= '  ' . $fields['Field'] . ' ' . $fields['Type'];

          if (strlen($fields['Default']) > 0) {
           if ($fields['Default'] == 'CURRENT_TIMESTAMP'){
              $schema .= ' default ' . $fields['Default'] . '';
             }else{
              $schema .= ' default \'' . $fields['Default'] . '\'';
             }
           }
          if ($fields['Null'] != 'YES') $schema .= ' not null';

          if (isset($fields['Extra'])) $schema .= ' ' . $fields['Extra'];

          $schema .= ',' . "\n";
        }

        $schema = preg_replace("/,\n$/", '', $schema);

        // add the keys
        $index = array();
        $keys_query = tep_db_query("show keys from " . $table);
        while ($keys = tep_db_fetch_array($keys_query)) {
          $kname = $keys['Key_name'];

          if (!isset($index[$kname])) {
            $index[$kname] = array('unique' => !$keys['Non_unique'],
                                   'columns' => array());
          }

          $index[$kname]['columns'][] = $keys['Column_name'];
        }

		foreach($index as $kname=>$info) {
          $schema .= ',' . "\n";

          $columns = implode($info['columns'], ', ');

          if ($kname == 'PRIMARY') {
            $schema .= '  PRIMARY KEY (' . $columns . ')';
          } elseif ($info['unique']) {
            $schema .= '  UNIQUE ' . $kname . ' (' . $columns . ')';
          } else {
            $schema .= '  KEY ' . $kname . ' (' . $columns . ')';
          }
        }

        $schema .= "\n" . ');' . "\n\n";
        fputs($fp, $schema);

        // dump the data
        $rows_query = tep_db_query("select " . implode(',', $table_list) . " from " . $table);
        while ($rows = tep_db_fetch_array($rows_query)) {
          $schema = 'insert into ' . $table . ' (' . implode(', ', $table_list) . ') values (';

          reset($table_list);
		  foreach($table_list as $i) {
            if (!isset($rows[$i])) {
              $schema .= 'NULL, ';
            } elseif (tep_not_null($rows[$i])) {
              $row = addslashes($rows[$i]);
              $row = preg_replace("/\n#/", "\n".'\#', $row);

              $schema .= '\'' . $row . '\', ';
            } else {
              $schema .= '\'\', ';
            }
          }

          $schema = preg_replace('/, $/', '', $schema) . ');' . "\n";
          fputs($fp, $schema);

        }
      }

      fclose($fp);
      
      if (isset($_POST['download']) && ($_POST['download'] == 'yes')) {
        switch ($_POST['compress']) {
          case 'gzip':
            //$backup_file .= '.gz';
            //build the files path and names
            $backup_file_2 = DIR_FS_BACKUP . $backup_file ;
            
            // if gzip library is on the server use it, if not fall back to php gzip
            if ($d_serv_gzip_avail == '1'){
              exec($gzip_path_1 . ' ' . $backup_file_2);
              // unlink(DIR_FS_BACKUP . $backup_file);
              if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_9,'warning');
              // reset the $backup_file variable with the new name for use below
              $backup_file = $backup_file . '.gz';

            } else {
              $backup_file_1 = DIR_FS_BACKUP . $backup_file . $gzip_file_ext;
              if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_10,'warning');

              //open the uncompressed file and read it
              $fp_1 = fopen($backup_file_2, "r");
              $fp_1_data = fread($fp_1, filesize($backup_file_2));
              //compress data
              $gzdata = gzencode($fp_1_data, $gzip_level_set);
              // write compressed data to a gz file
              $gz = gzopen($backup_file_1,'w');
              gzwrite($gz, $gzdata);
              gzclose($gz);
              //close orginal file and remove it
              fclose($fp_1);
              //delete the orginal file
              unlink($backup_file_2);
              // reset the $backup_file variable with the new name for use below
              $backup_file = $backup_file . $gzip_file_ext;
            }
            break;
          case 'zip':
            exec($zip_path_1 . ' -j ' . DIR_FS_BACKUP . $backup_file . '.zip ' . DIR_FS_BACKUP . $backup_file);
            if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_11,'warning');
            unlink(DIR_FS_BACKUP . $backup_file);
            // reset the $backup_file variable with the new name for use below
              $backup_file = $backup_file . '.zip';
        }

        //add mine header for download
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
          header('Content-Type: application/octetstream');
          header('Cache-Control: no-store, no-cache, must-revalidate' );
          header('Cache-Control: post-check=0, pre-check=0', false );
          header("Pragma: public");
          header("Cache-control: private");
          header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
          header('Content-Transfer-Encoding: Binary');
          header("Content-length: " . filesize(DIR_FS_BACKUP . $backup_file));
          header('Content-Disposition: attachment; filename=' . $backup_file);
        } else {
          header('Content-Type: application/octet-stream');
          header('Cache-Control: no-store, no-cache, must-revalidate' );
          header('Cache-Control: post-check=0, pre-check=0', false );
          header("Pragma: no-cache");
          header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
          header('Content-Transfer-Encoding: Binary');
          header("Content-length: " . filesize(DIR_FS_BACKUP . $backup_file));
          header('Content-Disposition: attachment; filename=' . $backup_file);
        }
        
        readfile(DIR_FS_BACKUP . $backup_file);
        unlink(DIR_FS_BACKUP . $backup_file);

        exit;
      } else {
        switch ($_POST['compress']) {
          case 'gzip':
            //$backup_file .= '.gz';
            //build the files path and names
            $backup_file_2 = DIR_FS_BACKUP . $backup_file ;
            
            // if gzip library is on the server use it, if not fall back to php gzip
            if ($d_serv_gzip_avail == '1'){ 
              exec($gzip_path_1 . ' ' . $backup_file_2);
              // unlink(DIR_FS_BACKUP . $backup_file);
              if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_9,'warning');
            } else {
              $backup_file_1 = DIR_FS_BACKUP . $backup_file . $gzip_file_ext;
              if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_10,'warning');
              //open the uncompressed file and read it
              $fp_1 = fopen($backup_file_2, "r");
              $fp_1_data = fread($fp_1, filesize($backup_file_2));
              //compress data
              //$gzdata = gzencode($fp_1_data, $gzip_level_set);
              // write compressed data to a gz file
              $gz = gzopen($backup_file_1,"w");
              gzwrite($gz, $fp_1_data);
              gzclose($gz);
              //close orginal file and remove it
              fclose($fp_1);
             //delete the orginal file
              unlink($backup_file_2);
            }
            break;
          case 'zip':
            exec($zip_path_1 . ' -j ' . DIR_FS_BACKUP . $backup_file . '.zip ' . DIR_FS_BACKUP . $backup_file);
            unlink(DIR_FS_BACKUP . $backup_file);
            if ($debug=='ON') $messageStack->add_session('search', BACKUP_MYSQl_DEBUG_MSG_11,'warning');
        }

        $messageStack->add_session('search', SUCCESS_DATABASE_SAVED, 'success');
      }

      tep_redirect(tep_href_link(FILENAME_BACKUP));
      break;
    case 'restorenow':
    case 'restorelocalnow':
      tep_set_time_limit(0);

      $specified_restore_file = isset($_GET['file']) ? $_GET['file'] : '';
      if ($specified_restore_file !='' && file_exists(DIR_FS_BACKUP . $specified_restore_file)) {
        $restore_file = DIR_FS_BACKUP . $specified_restore_file;
        $extension = substr($specified_restore_file, -3);

        //determine file format and unzip if needed
        if ( ($extension == 'sql') || ($extension == '.gz') || ($extension == 'zip') ) {
          switch ($extension) {
            case 'sql':
              $restore_from = $restore_file;
              $remove_raw = false;
              break;
            case '.gz':
              if ($d_serv_gunzip_avail == 1){
                $restore_from = substr($restore_file, 0, -3);
                exec($gunzip_path_1 . ' ' . $restore_file . ' -c > ' . $restore_from);
                $remove_raw = true;
              } else {
                //use php gzip to uncompress
                //get file size

                $restore_from = substr($restore_file, 0, -3);
                //get file size of final file
                $file_open = fopen($restore_file, "rb");
                fseek($file_open, -4, SEEK_END);
                $buf = fread($file_open, 4);
                $gz_file_size = end(unpack("V", $buf));
                fclose($file_open);

                // getting content of the compressed file
                $zp = gzopen($restore_file, "r");
                $data = gzread ($zp, $gz_file_size );
                gzclose($zp);

                // write data to temp file for restore
                $fp = fopen($restore_from, "w");
                fwrite($fp, $data);
                fclose($fp);
                $remove_raw = true;
              }
              break;
            case 'zip':
              $restore_from = substr($restore_file, 0, -4);
              if ($d_serv_unzip_avail == '1') {
                exec($unzip_path_1 . ' ' . $restore_file . ' -d ' . DIR_FS_BACKUP);
              } else {
                $backup_file_2 = DIR_FS_BACKUP . $restore_file ;
                $backup_file_1 = DIR_FS_BACKUP . $restore_file . $bzip_file_ext;

                $in_file = bzopen ($backup_file_1, "rb");
                $out_file = fopen ($backup_file_2, "wb");

                while ($buffer = bzread (filesize($backup_file_1) )) {
                  fwrite ($out_file, $buffer, filesize($backup_file_2));
                }

                bzclose ($in_file);
                fclose ($out_file);
                $remove_raw = true;
              }
          }
        }
      } elseif ($action == 'restorelocalnow') {
        $sql_file = new upload('sql_file', DIR_FS_BACKUP);
        $specified_restore_file = $sql_file->filename;
        $restore_from = DIR_FS_BACKUP . $specified_restore_file;
      }

      if (isset($restore_query)) {
        $sql_array = array();
        $sql_length = strlen($restore_query);
        $pos = strpos($restore_query, ';');
        for ($i=$pos; $i<$sql_length; $i++) {
          if ($restore_query[0] == '#') {
            $restore_query = ltrim(substr($restore_query, strpos($restore_query, "\n")));
            $sql_length = strlen($restore_query);
            $i = strpos($restore_query, ';')-1;
            continue;
          }
          if ($restore_query[($i+1)] == "\n") {
            for ($j=($i+2); $j<$sql_length; $j++) {
              if (trim($restore_query[$j]) != '') {
                $next = substr($restore_query, $j, 6);
                if ($next[0] == '#') {
                  // find out where the break position is so we can remove this line (#comment line)
                  for ($k=$j; $k<$sql_length; $k++) {
                    if ($restore_query[$k] == "\n") break;
                  }
                  $query = substr($restore_query, 0, $i+1);
                  $restore_query = substr($restore_query, $k);
                  // join the query before the comment appeared, with the rest of the dump
                  $restore_query = $query . $restore_query;
                  $sql_length = strlen($restore_query);
                  $i = strpos($restore_query, ';')-1;
                  continue 2;
                }
                break;
              }
            }
            if ($next == '') { // get the last insert query
              $next = 'insert';
            }
            if ( (preg_match('/create/i', $next)) || (preg_match('/insert/i', $next)) || (preg_match('/drop t/i', $next)) ) {
              $next = '';
              $sql_array[] = substr($restore_query, 0, $i);
              $restore_query = ltrim(substr($restore_query, $i+1));
              $sql_length = strlen($restore_query);
              $i = strpos($restore_query, ';')-1;
            }
          }
        }

        tep_db_query("drop table if exists address_book, address_format, banners, banners_history, categories, categories_description, configuration, configuration_group, counter, counter_history, countries, currencies, customers, customers_basket, customers_basket_attributes, customers_info, languages, manufacturers, manufacturers_info, orders, orders_products, orders_status, orders_status_history, orders_products_attributes, orders_products_download, products, products_attributes, products_attributes_download, prodcts_description, products_options, products_options_values, products_options_values_to_products_options, products_to_categories, reviews, reviews_description, sessions, specials, tax_class, tax_rates, geo_zones, whos_online, zones, zones_to_geo_zones");

        for ($i=0, $n=sizeof($sql_array); $i<$n; $i++) {
          tep_db_query($sql_array[$i]);
        }

        tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key = 'DB_LAST_RESTORE'");
        tep_db_query("insert into " . TABLE_CONFIGURATION . " values ('', 'Last Database Restore', 'DB_LAST_RESTORE', '" . $read_from . "', 'Last database restore file', '6', '', '', now(), '', '')");

        if (isset($remove_raw) && ($remove_raw == true)) {
          unlink($restore_from);
        }

        $messageStack->add_session('search', SUCCESS_DATABASE_RESTORED, 'success');
      }

      tep_redirect(tep_href_link(FILENAME_BACKUP));
      break;
    case 'download':
      $extension = substr($_GET['file'], -3);

      if ( ($extension == 'zip') || ($extension == '.gz') || ($extension == 'sql') ) {
        if ($fp = fopen(DIR_FS_BACKUP . $_GET['file'], 'rb')) {
          $buffer = fread($fp, filesize(DIR_FS_BACKUP . $_GET['file']));
          fclose($fp);

          header('Content-type: application/x-octet-stream');
          header('Content-disposition: attachment; filename=' . $_GET['file']);

          echo $buffer;

          exit;
        }
      } else {
        $messageStack->add('search', ERROR_DOWNLOAD_LINK_NOT_ACCEPTABLE, 'error');
      }
      break;
    case 'deleteconfirm':
      if (strstr($_GET['file'], '..')) tep_redirect(tep_href_link(FILENAME_BACKUP, '', 'SSL'));

      tep_remove(DIR_FS_BACKUP . '/' . $_GET['file']);

      if (!$tep_remove_error) {
        $messageStack->add_session('search', SUCCESS_BACKUP_DELETED, 'success');

        tep_redirect(tep_href_link(FILENAME_BACKUP));
      }
      break;
  }
}

// check if the backup directory exists
$dir_ok = false;
if (is_dir(DIR_FS_BACKUP)) {
  if (is_writeable(DIR_FS_BACKUP)) {
    $dir_ok = true;
  } else {
    $messageStack->add('search', ERROR_BACKUP_DIRECTORY_NOT_WRITEABLE, 'error');
  }
} else {
  $messageStack->add('search', ERROR_BACKUP_DIRECTORY_DOES_NOT_EXIST, 'error');
}

include(DIR_WS_INCLUDES . 'html_top.php');
include(DIR_WS_INCLUDES . 'header.php');
include(DIR_WS_INCLUDES . 'column_left.php');
?>
<div id="content" class="content p-relative">         
  <h1 class="page-header"><i class="fa fa-laptop"></i> <?php echo HEADING_TITLE; ?></h1>

  <?php if (file_exists(DIR_WS_INCLUDES . 'toolbar.php')) include(DIR_WS_INCLUDES . 'toolbar.php'); ?>
  
  <div class="col">     
    <!-- begin panel -->
    <div class="dark">
      <!-- body_text //-->     
      <div id="table-languages" class="table-languages">
        <div class="row">
          <div class="col-md-9 col-xl-10 dark panel-left rounded-left">
            <table class="table table-hover w-100 mt-2">
              <thead>
                <tr class="th-row">
                  <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_TITLE; ?></th>
                  <th scope="col" class="th-col dark text-center d-none d-lg-table-cell col-blank"><?php echo TABLE_HEADING_FILE_DATE; ?></th>
                  <th scope="col" class="th-col dark text-right d-none d-lg-table-cell col-blank"><?php echo TABLE_HEADING_FILE_SIZE; ?></th>
                  <th scope="col" class="th-col dark text-right"><?php echo TABLE_HEADING_ACTION; ?></th>
                </tr>
              </thead>
              <tbody>
                <?php 
                if ($dir_ok == true) {
                  $dir = dir(DIR_FS_BACKUP);
                  $contents = array();
                  while ($file = $dir->read()) {
                    if (!is_dir(DIR_FS_BACKUP . $file)) {
                      $contents[] = $file;
                    }
                  }
                  sort($contents);

                  for ($i=0, $n=sizeof($contents); $i<$n; $i++) {
                    $entry = $contents[$i];

                    $check = 0;

                    if ((!isset($_GET['file']) || (isset($_GET['file']) && ($_GET['file'] == $entry))) && !isset($buInfo) && ($action != 'backup') && ($action != 'restorelocal')) {
                      $file_array['file'] = $entry;
                      $file_array['date'] = date(PHP_DATE_TIME_FORMAT, filemtime(DIR_FS_BACKUP . $entry));
                      //$file_array['size'] = number_format(filesize(DIR_FS_BACKUP . $entry)) . ' bytes';

                      $file_array['size'] = number_format(filesize(DIR_FS_BACKUP . $entry)) . BYTES;

                      switch (substr($entry, -3)) {
                        case 'zip': $file_array['compression'] = 'ZIP'; break;
                        case '.gz': $file_array['compression'] = 'GZIP'; break;
                        default: $file_array['compression'] = TEXT_NO_EXTENSION; break;
                      }

                      $buInfo = new objectInfo($file_array);
                    }

                    $selected = (isset($buInfo) && is_object($buInfo) && ($entry == $buInfo->file)) ? true : false;
                    if ($selected) {
                      echo '<tr class="table-row dark selected">' . "\n";
                      $onclick_link = 'file=' . $buInfo->file . '&action=restore';
                    } else {
                      echo '<tr class="table-row dark">' . "\n";
                      $onclick_link = 'file=' . $entry;
                    }
                    $col_selected = ($selected) ? ' selected' : '';
                    ?>
                    <td class="table-col dark text-left<?php echo $col_selected; ?>" onclick="document.location.href='<?php echo tep_href_link(FILENAME_BACKUP, $onclick_link); ?>'"><?php echo '<a href="' . tep_href_link(FILENAME_BACKUP, 'action=download&file=' . $entry) . '"><i class="fa fa-download fa-lg text-warning mr-2"></i></a>' . $entry; ?></td>
                    <td class="table-col dark text-center<?php echo $col_selected; ?>" onclick="document.location.href='<?php echo tep_href_link(FILENAME_BACKUP, $onclick_link); ?>'"><?php echo date(PHP_DATE_TIME_FORMAT, filemtime(DIR_FS_BACKUP . $entry)); ?></td>
                    <td class="table-col dark text-right<?php echo $col_selected; ?>" onclick="document.location.href='<?php echo tep_href_link(FILENAME_BACKUP, $onclick_link); ?>'"><?php echo number_format(filesize(DIR_FS_BACKUP . $entry)); ?> <!-- bytes --><?php echo BYTES;?></td>
                    <td class="table-col dark text-right<?php echo $col_selected; ?> d-none d-lg-table-cell col-blank"><?php echo ($selected) ? '<i class="fa fa-long-arrow-right fa-lg text-success"></i>' : '<a href="' . tep_href_link(FILENAME_CURRENCIES, 'page=' . $_GET['page'] . '&cID=' . $currency['currencies_id']) . '"><i class="fa fa-info-circle fa-lg text-muted"></i></a>'; ?>
                    </tr>
                    <?php
                  }
                  $dir->close();
                }
                ?>
              </tbody>
            </table>

            <div><?php echo '<div class="sidebar-text">' . TEXT_BACKUP_DIRECTORY . '<span class="sidebar-title ml-2">' . DIR_FS_BACKUP; ?></span></div></div>

            <div class="float-right mr-2 mt-3 mb-3" role="group">
              <?php 
              if ( ($action != 'backup') && (isset($dir)) && !get_cfg_var('safe_mode') && $dir_ok == true ) {
                echo '<a class="btn btn-success btn-sm mr-1" href="' . tep_href_link(FILENAME_BACKUP, 'action=backup'.(($debug=='ON')?'&debug=ON':''), 'SSL') . '">' . IMAGE_BACKUP . '</a>';
              }
              if ( ($action != 'restorelocal') && isset($dir) ) {
                echo '<a class="btn btn-success btn-sm mr-1" href="' . tep_href_link(FILENAME_BACKUP, 'action=restorelocal'.(($debug=='ON')?'&debug=ON':''), 'SSL') . '">' . TEXT_RESTORE_LOCAL . '</a>';
              }              
              ?>
            </div>  

            <?php
            if (defined('DB_LAST_RESTORE') && tep_not_null(DB_LAST_RESTORE)) {
              ?>
              <div class="sidebar-text mt-2"><?php echo TEXT_LAST_RESTORATION . ' ' . DB_LAST_RESTORE . ' <a href="' . tep_href_link(FILENAME_BACKUP, 'action=forget') . '">' . TEXT_FORGET . '</a>'; ?></div>
              <?php
            }
            ?>
          </div>
          <div class="col-md-3 col-xl-2 dark panel-right rounded-right">
            <?php
              $heading = array();
              $contents = array();

              switch ($action) {
                case 'backup':
                  $heading[] = array('text' => TEXT_INFO_HEADING_NEW_BACKUP);
                  $contents[] = array('form' => tep_draw_form('backup', FILENAME_BACKUP, 'action=backupnow'));
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-danger m-0"><p class="mb-0 mt-0 f-w-400">' . TEXT_INFO_NEW_BACKUP . '</p></div></div></div>');                                           
                  $contents[] = array('text' => '<div class="form-check mt-2">' . tep_draw_radio_field('compress', 'no', true, 'class="form-check-input"') . '<label class="form-check-label sidebar-text" for="compress">' . TEXT_INFO_USE_NO_COMPRESSION . '</label></div>');
                  if ($d_php_gzip_on == '1' || $d_serv_gzip_avail == '1') $contents[] = array('text' => '<div class="form-check">' . tep_draw_radio_field('compress', 'gzip', null, 'class="form-check-input"') . '<label class="form-check-label sidebar-text" for="compress">' . TEXT_INFO_USE_GZIP . '</label></div>');
                  if ($d_serv_zip_avail == '1') $contents[] = array('text' => '<div class="form-check">' . tep_draw_radio_field('compress', 'zip', null, 'class="form-check-input"') . '<label class="form-check-label sidebar-text" for="compress">' . TEXT_INFO_USE_ZIP . '</label></div>');
                  // Download to file --- Should only be done if SSL is active, otherwise database is exposed as clear text
                  if ($dir_ok == true) {
                    $contents[] = array('text' => '<div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 mt-3 main-text">' . TEXT_INFO_DOWNLOAD_ONLY . '</label><input type="checkbox" name="download" class="js-switch"></div>');
                  } else {
                    $contents[] = array('text' => '<div class="form-check">' . tep_draw_radio_field('compress', 'yes', false, 'class="form-check-input"') . '<label class="form-check-label sidebar-text" for="compress">' . TEXT_INFO_DOWNLOAD_ONLY . '</label></div>');
                    $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-danger m-0"><p class="mb-0 mt-0 f-w-400">' . TEXT_INFO_BEST_THROUGH_HTTPS . '</p></div></div></div>');                                           
                  }
                  $contents[] = array('align' => 'center', 'text' => '<button type="submit" class="btn btn-success btn-sm mt-2 mb-2 btn-backup">' . IMAGE_BACKUP . '</button><button type="button" class="btn btn-grey btn-sm mt-2 mb-2 btn-cancel" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP) . '\'">' . IMAGE_CANCEL . '</button>');
                  break;
                case 'restore':
                  $heading[] = array('text' => $buInfo->date);
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-info m-0 fw-400">' . tep_break_string(sprintf(TEXT_INFO_RESTORE, DIR_FS_BACKUP . (($buInfo->compression != TEXT_NO_EXTENSION) ? substr($buInfo->file, 0, strrpos($buInfo->file, '.')) : $buInfo->file), ($buInfo->compression != TEXT_NO_EXTENSION) ? TEXT_INFO_UNPACK : ''), 35, ' ') . '</div></div></div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2"><button type="button" class="btn btn-success btn-sm mt-2 mb-2 btn-restore" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP, 'file=' . $buInfo->file . '&action=restorenow') . '\'">' . IMAGE_RESTORE . '</button><button type="button" class="btn btn-grey btn-sm mt-2 mb-2 btn-cancel" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP, 'file=' . $buInfo->file) . '\'">' . IMAGE_CANCEL . '</button></div>');
                  break;
                case 'restorelocal':
                  $heading[] = array('text' => TEXT_INFO_HEADING_RESTORE_LOCAL);
                  $contents[] = array('form' => tep_draw_form('restore', FILENAME_BACKUP, 'action=restorelocalnow', 'post', 'enctype="multipart/form-data"'));
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-info m-0 fw-400">' . TEXT_INFO_RESTORE_LOCAL . '</div></div></div>');
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-danger m-0 fw-400">' . TEXT_INFO_BEST_THROUGH_HTTPS . '</div></div></div>');
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2 mb-4"><div class="note note-info m-0 fw-400">' . TEXT_INFO_RESTORE_LOCAL_RAW_FILE . '</div></div></div>');
                  $contents[] = array('text' => '<input type="file" class="filestyle" id="sql_file" name="sql_file" placeholder="' . TEXT_CHOOSE_FILE . '" />');
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2"><button type="submit" class="btn btn-success btn-sm mt-2 mb-2 btn-restore">' . IMAGE_RESTORE . '</button><button type="button" class="btn btn-grey btn-sm mt-2 mb-2 btn-cancel" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP)  . '\'">' . IMAGE_CANCEL . '</button></div>');
                  break;
                case 'delete':
                  $heading[] = array('text' => $buInfo->date);
                  $contents[] = array('form' => tep_draw_form('delete', FILENAME_BACKUP, 'file=' . $buInfo->file . '&action=deleteconfirm'));
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-danger m-0 fw-400">' . sprintf(TEXT_DELETE_INTRO, $buInfo->file) . '</div></div></div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2"><button type="submit" class="btn btn-danger btn-sm mt-2 mb-2 btn-deleteconfirm">' . IMAGE_CONFIRM_DELETE . '</button><button type="button" class="btn btn-grey btn-sm mt-2 mb-2 btn-cancel" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP, 'file=' . $buInfo->file)  . '\'">' . IMAGE_CANCEL . '</button></div>');
                  break;
                default:
                  if (isset($buInfo) && is_object($buInfo)) {
                    $heading[] = array('text' => $buInfo->date);
                    $contents[] = array('align' => 'center', 'text' => '<button type="button" class="btn btn-success btn-sm mt-2 mb-2 btn-restore" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP, 'file=' . $buInfo->file . '&action=restore') . '\'">' . IMAGE_RESTORE . '</button><button type="button" class="btn btn-danger btn-sm mt-2 mb-2 btn-delete" onclick="window.location=\'' . tep_href_link(FILENAME_BACKUP, 'file=' . $buInfo->file . '&action=delete') . '\'">' . IMAGE_DELETE . '</button>');
                    $contents[] = array('text' => '<div class="sidebar-text mt-3">' . TEXT_INFO_DATE . '<span class="sidebar-title ml-2">' . $buInfo->date . '</span</div>');
                    $contents[] = array('text' => '<div class="sidebar-text">' . TEXT_INFO_SIZE . '<span class="sidebar-title ml-2">' . $buInfo->size . '</span</div>');
                    $contents[] = array('text' => '<div class="sidebar-text mb-3">' . TEXT_INFO_COMPRESSION . '<span class="sidebar-title ml-2">' . $buInfo->compression . '</span</div>');
                  }
                  break;
              }

              // use $box->showSidebar()
              if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
                $box = new box;
                echo $box->showSidebar($heading, $contents);
              }
            ?>
          </div>
        </div>
      </div>   
      <!-- end body_text //-->
    </div>
    <!-- end panel -->
  </div>
</div>
<script>
$(document).ready(function(){

  //  instantiate checkbox switches
  var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  elems.forEach(function(html) {
    var switchery = new Switchery(html, { size: 'small', 
                                          color: '#ff4044',
                                          secondaryColor: '#a8acb1' });
  }); 
}); 
</script>
<!-- body_eof //-->
<?php 
include(DIR_WS_INCLUDES . 'html_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php'); 
?>