<?php
/**
  @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.0.9
  @date  25/07/10, 22:48
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
*/

Class CipUtility {

  protected static $_instance;

  protected function __construct() {

  }

  public static function getInstance() {
    if(self::$_instance == null)  self::$_instance = new self();
    return self::$_instance;
  }


/** XML explode and exploit */

  /**
    Debugg view node info
  */
  static function afficherInfos($noeud){
    $nom ='nodeName '. $noeud->nodeName;
    $valeur ='nodeValue '. $noeud->nodeValue;
    $type ='nodeType '. $noeud->nodeType;
    CIP::InProcess('<b>' . $nom . '</b> (' . $type . ') = ' . $valeur,__CLASS__.__FUNCTION__,'info');
  }







/** SQL backup / restore */


/**
  TODO: Revoir pour exploiter class backup_db
  @date  25/07/10, 19:57
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
*/
  public static function sql_restore() {
    tep_set_time_limit(0);
    $backup_file=CIP::PATH_BACKUP.CIP::$cip_name.'.sql';
    $zip_file=$backup_file.'.gz';
    $restore_query='';
    if (!file_exists($backup_file)) {
	if(file_exists($zip_file)) {
	  $zd = gzopen($zip_file, "r");
	  while(!feof($zd)){
	    $restore_query .= gzread($zd, 10000);
	  }
	  gzclose($zd);
	}
    }else{
      $restore_query=file_get_contents($backup_file);
    }
    if ($restore_query !='') {
      //Delete all tables from database:
      $tables_query=tep_db_query('show tables');
      while ($tables=tep_db_fetch_array($tables_query, MYSQL_ASSOC)) {
	list(,$table)=each($tables);
	if((substr($table,0,4) =='view')) break;
	tep_db_query('DROP TABLE IF EXISTS '.$table);
      }
      if ($restore_query) {
	$sql_array = parse_sql($restore_query);
	foreach ($sql_array as $query) tep_db_query($query);
      }
    }
    tep_remove($zip_file);
    tep_remove($backup_file);
    return true;
  }

/**
  TODO: Revoir pour exploiter class backup_db
  @date  25/07/10, 19:57
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
*/
  public static function sql_backup() {
    tep_set_time_limit(0);
    $backup_file=CIP::PATH_BACKUP.CIP::$cip_name.'.sql';
    // From original admin/backup.php:
    $fp=fopen($backup_file, 'w');
    $schema=
	      '# Contrib Installer.'."\n" .
	      '# Makes customizing osCommerce "simple".' . "\n" .
	      '# Copyright (c) '.date('Y').' Vlad Savitsky'."\n" .
	      '# http://www.cip.net.ua' . "\n" .
	      '#' . "\n" .
	      '# Database Backup For ' . STORE_NAME . "\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)) {
	list(,$table) = each($tables);
	if((substr($table,0,4) =='view')) break;
	$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)    $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'];
	    $index[$kname]['sub_part'][]=$keys['Sub_part'];
	}
	while (list($kname, $info)=each($index)) {
	    $schema.=','."\n";
	    $columns='';
	    foreach($info['columns'] as $id=>$col){
		    if($columns=='')
			    $columns.= "`".$col."`";
		    else
			    $columns.= ",`".$col."`";
		    if($info['sub_part'][$id] != NULL && $info['sub_part'][$id] != 'NULL')
			    $columns.= "(".$info['sub_part'][$id].")";
	    }
	    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);
	    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, $schema);
	}
    }
    fclose($fp);
    gzcompressfile($backup_file);

    if (is_file($backup_file)) {
	//chmod($backup_file, 0777);
	tep_remove($backup_file);
    }
    if (file_exists($backup_file.'.gz'))    chmod($backup_file.'.gz', 0777);

    return true;
  }


/*
  function backup_all() {
    $catalog_files=get_all_files_in_tree(DIR_FS_CATALOG, array(),
		array(basename(DIR_FS_CIP), basename(self::PATH_BACKUP)));
    foreach($catalog_files as $id=>$value) {
	$catalog_files[$id]=str_replace(DIR_FS_DOCUMENT_ROOT, '', $value);
    }
    $tag=$this->contrib_data[0];
    foreach($catalog_files as $file_path) {
	if (self::$error=$tag->backup_file($file_path))    break;
    }
  }

  function restore_all() {
    if (!$this->is_all_right()) self::InProcess(__("Erreur avant traitement de cette fonction "), __CLASS__.'->'.__FUNCTION__.'::'.__LINE__,'error');
//   {trigger_error(__CLASS__.sprintf(' error %s', __FUNCTION__), E_USER_ERROR);    return;}
    $catalog_files=get_all_files_in_tree(self::PATH_BACKUP.self::$cip_name.'/', array(), array());
    foreach($catalog_files as $id=>$value) {
	$catalog_files[$id]=str_replace(self::PATH_BACKUP.self::$cip_name.'/', '', $value);
    }
    $tag=$this->contrib_data[0];
    foreach($catalog_files as $file_path) {
	if (self::$error=$tag->restore_file($file_path))    break;
    }
    tep_remove(self::PATH_BACKUP.self::$cip_name);
  }*/







}


?>