<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  17/10/10, 13:36
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class backup
*/

class backup
  implements ExtModPage/*, InterfacedTJsonS */, InterfaceModule {

  const FILENAME = FILENAME_BACKUP;
  public static $code;

  public static $action;

  public static $list=array();
  /**
    @param bool $dir_ok
  */
  public static $dir_ok;


  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;

    //! active datatable in ajax, precise les GET necessaire
//     define('JSONSTATMENT', 'mod=page&type='.self::$code);


  }

  /**
    Recuperation des nom de cols
  */
  private static function showh_list_fields_from($table){
    $table_fields = array();
    $fields_query = tep_db_query("show fields from " . $table);
    while ($fields = tep_db_fetch_array($fields_query)) {
      $table_fields[] = $fields;
    }
    return $table_fields;
  }

  public function check_action($actions){
    global $messageStack;

    self::$action=$actions;

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

        $messageStack->add_session(__('success last restore cleared'), 'success');

        tep_redirect(tep_href_link(self::FILENAME));
        break;
      case 'backupnow':
        tep_set_time_limit(0);
        $backup_file = 'db_' . DB_DATABASE . '-' . date('YmdHis') . '.sql';
        $fp = fopen(DIR_FS_BACKUP . $backup_file, 'w');

        $schema = '# osCSS, Open Source E-Commerce Solutions' . "\n" .
                  '# http://www.oscss.org' . "\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, mb_convert_encoding($schema,mb_detect_encoding($schema),"UTF-8") );

        $tables_query = tep_db_query('show tables');
        while ($tables = tep_db_fetch_array($tables_query)) {
          list(,$table) = each($tables);

	  //! pas backup des vues
	  if(substr($table, 0,4) !='view') {

	    $schema=$schemacol='';
	    $table_fields=self:: showh_list_fields_from($table);
	    $table_list=array();



	    //! recup nom des colonnes
	    foreach($table_fields  as $k=>$fields) {
	      $table_list[]= $fields['Field'];
	      $schemacol .= '  ' . $fields['Field'] . ' ' . $fields['Type'];
	      if (strlen($fields['Default']) > 0) $schemacol .= ' default \'' . $fields['Default'] . '\'';
	      if ($fields['Null'] != 'YES') $schemacol .= ' not null';
	      if (isset($fields['Extra'])) $schemacol .= ' ' . $fields['Extra'];
	      $schemacol .= ',' . "\n";
	    }


	    //! structure
	    if (isset($_POST['backup_structure']) && ($_POST['backup_structure'] == 'yes')) {

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

	      $schema .= $schemacol;
	      $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'];
	      }
	      while (list($kname, $info) = each($index)) {
		$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, mb_convert_encoding($schema,mb_detect_encoding($schema),"UTF-8"));
	    }

	    if (isset($_POST['backup_truncate']) && ($_POST['backup_truncate'] == 'yes'))
	      fputs($fp, mb_convert_encoding('TRUNCATE TABLE '.$table.' ;'. "\n\n",mb_detect_encoding($schema),"UTF-8"));

	    //! 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);
	      while (list(,$i) = each($table_list)) {
		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, mb_convert_encoding($schema,mb_detect_encoding($schema),"UTF-8"));

	    }
	  }
        }

        fclose($fp);

        if (isset($_POST['download']) && ($_POST['download'] == 'yes')) {
          switch ($_POST['compress']) {
            case 'gzip':
              bu_gzip(DIR_FS_BACKUP, $backup_file, true);
                          $backup_file .= '.gz';
              break;

          }
          header('Content-type: application/x-octet-stream');
          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':
              bu_gzip(DIR_FS_BACKUP, $backup_file, true);
              break;
          }

          $messageStack->add_session(__('success database saved'), 'success');
        }

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

        if (self::$action == 'restorenow') {
          $read_from = $_GET['file'];

          if (file_exists(DIR_FS_BACKUP . $_GET['file'])) {
            $restore_file = DIR_FS_BACKUP . $_GET['file'];
            $extension = substr($_GET['file'], -3);

            if ( ($extension == 'sql') || ($extension == '.gz') || ($extension == 'zip') ) {
              switch ($extension) {
                case 'sql':
                  $restore_from = $restore_file;
                  $remove_raw = false;
                  break;
                case '.gz':
                    $restore_from = substr($restore_file, 0, -3);
                    bun_gzip($restore_file,$restore_from);
                    $remove_raw = true;
                  break;
              }

              if (isset($restore_from) && file_exists($restore_from)/* && (filesize($restore_from) > 15000)*/) {
                $fd = fopen($restore_from, 'rb');
                $restore_query = fread($fd, filesize($restore_from));
                fclose($fd);
              }
            }
          }
        } elseif (self::$action == 'restorelocalnow') {
          $sql_file = new upload('sql_file',DIR_FS_BACKUP);

          if ($sql_file->parse() == true) {
            $restore_query = fread(fopen($sql_file->tmp_filename, 'r'), filesize($sql_file->tmp_filename));
            $read_from = $sql_file->filename;
          }
        }

        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 (isset($restore_query[($i+1)]) && $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)) || (preg_match('/trunca/i', $next)) || (preg_match('/delete/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;
              }
            }
          }



          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(), '', '','1')");

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

          $messageStack->add_session(__('success database restored'), 'success');
        }

        tep_redirect(tep_href_link(self::FILENAME));
        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(__('error download link not acceptable'), 'error');
        }
        break;
      case 'deleteconfirm':
        if (strstr($_GET['file'], '..')) tep_redirect(tep_href_link(self::FILENAME));

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

        if (!$tep_remove_error) {
          $messageStack->add_session(__('success backup deleted'), 'success');

          tep_redirect(tep_href_link(self::FILENAME));
        }
        break;
    }

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

    return self::$action;
  }

  public function get_header(){
  }


  public static function load_db_values($ID){
      if(isset(self::$list[$ID])) return self::$list[$ID];
  }

  public function display_view(){
    self::$list=self::tep_get_list();
    return tep_get_include_contents(self::$code.'.listing');
  }


  public static function get_right_bar(){
    global $backup;
    $heading = array();
    $contents = array();

    if(isset($_GET['file']))  $buInfo=self::load_db_values((string)$_GET['file']);

    switch (self::$action) {

    case 'restore':
      $heading[] = array('text' => $buInfo->date );

      $contents[] = array('text' => 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, ' '));
      $contents[] = array('class' => 'button_nav', 'text' => '<a  class="button" href="' . tep_href_link(self::FILENAME, 'file=' . $buInfo->file . '&amp;action=restorenow') . '">' . __('image restore') . '</a> <a class="button" href="' . tep_href_link(self::FILENAME, 'file=' . $buInfo->file) . '">' .  IMAGE_CANCEL . '</a>');
      break;
    case 'restorelocal':
      $heading[] = array('text' => __('text info heading restore local') );

      $contents = array('form' => tep_draw_form('restore', self::FILENAME, 'action=restorelocalnow', 'post', 'enctype="multipart/form-data"'));
      $contents[] = array('text' => __('text info restore local'));
      $contents[] = array('text' => __('text info best through https'));
      $contents[] = array('class' => 'block_input','text' => tep_draw_file_field('sql_file'));
      $contents[] = array('text' => __('text info restore local raw file'));
      $contents[] = array('class' => 'button_nav', 'text' => tep_image_submit('button_restore.gif', __('image restore')) . ' <a  class="button" href="' . tep_href_link(self::FILENAME) . '">' .  IMAGE_CANCEL . '</a>');
      break;
    case 'delete':
      $heading[] = array('text' => $buInfo->date );

      $contents = array('form' => tep_draw_form('delete', self::FILENAME, 'file=' . $buInfo->file . '&amp;action=deleteconfirm'));
      $contents[] = array('text' => __('text delete intro'));
      $contents[] = array('text' => '<strong>' . $buInfo->file . '</strong>');
      $contents[] = array('class' => 'button_nav', 'text' => tep_image_submit('button_delete.gif', IMAGE_DELETE) . ' <a  class="button" href="' . tep_href_link(self::FILENAME, 'file=' . $buInfo->file) . '">' .  IMAGE_CANCEL . '</a>');
      break;
    case 'detail':
      if (isset($buInfo) && is_object($buInfo)) {
        $heading[] = array('text' => $buInfo->date );

        $contents[] = array('class' => 'button_nav', 'text' => '<a class="button" href="' . tep_href_link(self::FILENAME, 'file=' . $buInfo->file . '&amp;action=restore') . '">' .__('image restore') . '</a> <a  class="button" href="' . tep_href_link(self::FILENAME, 'file=' . $buInfo->file . '&amp;action=delete') . '">' . IMAGE_DELETE . '</a>');
        $contents[] = array('text' => __('text info date').' '. $buInfo->date);
        $contents[] = array('text' => __('text info size') .' '. $buInfo->size);
        $contents[] = array('text' => __('text info compression') .' '. $buInfo->compression);
      }
      break;
    case 'backup':
    default:
      $heading[] = array('text' => __('text info heading new backup') );

      $contents = array('form' => tep_draw_form('backup', self::FILENAME, 'action=backupnow'));
      $contents[] = array('text' => __('text info new backup'));

      $contents[] = array('class' => 'block_input','text' => tep_draw_radio_field('compress', 'no', 'no', true) . ' ' . __('text info use no compression') );

      if (@file_exists(LOCAL_EXE_ZIP)) $contents[] = array('class' => 'block_input','text' => tep_draw_radio_field('compress', 'zip', 'zip') . ' ' . __('text_info_use_zip'));
      if (function_exists('gzopen'))$contents[] = array('class' => 'block_input','text' => tep_draw_radio_field('compress', 'gzip', 'gzip') . ' ' . __('text info use gzip'));

      $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('backup_structure','', 'yes') . ' ' . __('faire un backup integrant la structure des tables'));
      $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('backup_truncate','', 'yes') . ' ' . __('ajouter commende pour vider les tables avant de restaurer'));

      if (self::$dir_ok == true)
        $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('download','', 'yes') . ' ' . __('text info download only'));
      else
        $contents[] = array('class' => 'block_input','text' => tep_draw_radio_field('download', '', 'yes', true) . ' ' . __('text info download only'));


      $contents[] = array('text' => __('text info best through https'));
      $contents[] = array('class' => 'button_nav', 'text' => tep_image_submit('button_backup.gif', __('image backup')) . ' <a  class="button" href="' . tep_href_link(self::FILENAME) . '">' .  IMAGE_CANCEL . '</a>');
      break;
    }

    if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
      $box = new box;
      echo $box->infoBox($heading, $contents);

    }
  }

  /** public static InterfacedTJsonS */

  private static function get_item_action($array){
  $s = '<span class="view fils fleft">'.
	'<a href="' . tep_href_link(self::FILENAME, 'action=download&amp;file=' . $array['file']) . '">' . tep_image(DIR_WS_ICONS . 'file_download.gif', ICON_FILE_DOWNLOAD) . '</a>'.
//             '<a  class="buttonimg" href="' . tep_href_link(self::FILENAME, 'cID=' . $array['file'] . '&amp;action=delete') . '">' .  tep_image(DIR_WS_ICONS . 'icon_delete.png',IMAGE_DELETE ). '</a>'.
	'</span>'.
	'<span class="fright">';
	  if (isset($_GET['file']) && ($array['file'] == (string)$_GET['file']))  $s .= tep_image(DIR_WS_ICONS . 'icon_arrow_right.gif', '');
	  else  $s .= '<a href="' . tep_href_link(self::FILENAME, 'file=' . $array['file'].'&amp;action=detail') . '">' . tep_image(DIR_WS_ICONS . 'icon_info.gif', IMAGE_ICON_INFO) . '</a>';
    $s .='</span>';
    return $s;
  }

  public static function tep_get_modele(){
    return array( 'title',
                  'date',
                  'poids'
                );
  }

  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows;

    $DB=Database::getInstance();

    $contents = array();
    foreach (scan(DIR_FS_BACKUP) as $file ) {
      $ext=substr($file,-3);
      if (in_array($ext, array('sql','.gz','zip')) )  $contents[] = array('file'=>$file,'extension'=>$ext) ;
    }
    sort($contents);

    foreach ($contents as $entry  ) {
      $file_array['ext'] = $entry['extension'];
      $file_array['file'] = $entry['file'];
      $file_array['date'] = tep_datetime_short(date(PHP_DATE_TIME_FORMAT, filemtime(DIR_FS_BACKUP . $entry['file']))); ;
      $file_array['size'] = number_format(filesize(DIR_FS_BACKUP . $entry['file'])) ;
      switch ($entry['extension']) {
	case 'zip': $file_array['compression'] = 'ZIP'; break;
	case '.gz': $file_array['compression'] = 'GZIP'; break;
	default: $file_array['compression'] = __('text no extension'); break;
      }
      self::$list[]=$file_array;
    }



    $li=$res=array();
    foreach(self::$list as $item){
//       foreach(self::tep_get_modele() as $k) $li[$k]=$item[$k];
      $li=$item;
      $li['title']=$item['file'];
      $li['date']=date(PHP_DATE_TIME_FORMAT, filemtime(DIR_FS_BACKUP . $item['file']));
      $li['size']=number_format(filesize(DIR_FS_BACKUP . $item['file']));
      $li['action']=self::get_item_action($item);
      $res[$item['file']]=new objectInfo($li);
    }

    return $res;
  }

/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }
}

?>