<?php
/**
  @licence GPL 2005-2011  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  24/03/11, 09:40
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
*/
  function osc_db_connect($server, $username, $password, $link = 'db_link') {
    global $link, $db_error;

    $db_error = false;

    if (!$server) {
      $db_error = 'No Server selected.';
      return false;
    }

    $link = @mysql_connect($server, $username, $password) or $db_error = mysql_error();
    @mysql_query("SET NAMES  'utf8' " , $link);
    return $link;
  }

  function osc_db_select_db($database) {
    return mysql_select_db($database);
  }

  function osc_db_close($link = 'db_link') {
    global $link;

    return mysql_close($link);
  }

  function osc_db_query($query, $link = 'db_link') {
    global $link;

    $res= mysql_query($query, $link) or oscss_db_error($query, mysql_errno(), mysql_error());
    return $res;
  }

  function osc_db_query_noblock($query, $link = 'db_link') {
    global $link;
// error_reporting()
    if( ($res=mysql_query($query, $link)) ==false)  echo '<br /><strong>Database reported:</strong> '.htmlspecialchars(mysql_error()).'<br /><strong>Failed query:</strong> '.htmlspecialchars($query)."<br />\n";
    else return $res;

  }

  /**
    Alias
  */
  function tep_db_query($query, $link = 'db_link') {
    global $link;

    return osc_db_query($query, $link);
  }

  function tep_db_fetch_array($db_query){
    return mysql_fetch_array($db_query, MYSQL_ASSOC);
  }

  function tep_db_num_rows($db_query) {
    return mysql_num_rows($db_query);
  }

function tep_db_prepare_input($string) {
  if (is_string($string)) {
    return trim(stripslashes($string));
  } elseif (is_array($string)) {
    reset($string);
    while (list($key, $value) = each($string)) {
      $string[$key] = tep_db_prepare_input($value);
    }
    return $string;
  } else {
    return $string;
  }
}

function tep_db_insert_id() {
  global $link;
  return mysql_insert_id($link);
}

function tep_db_input($string, $link = 'link') {
  global $link;
  return mysql_real_escape_string($string, $link);
}
  function oscss_db_error($query, $errno, $error) {

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html dir="ltr">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET ?>" />
    <title>Error</title>
    <style type="text/css">
    <!--
    BODY {margin: 10% 20% auto 20%; font: 10px verdana, arial, helvetica, sans-serif}
    #errorbox {border: 1px solid #b84623}
    H2 {margin: 0; color: #ffffff; background-color: #b84623; font-size: 1.1em; padding: 5px 4px}
    #errorbox DIV {padding: 6px 5px; background-color: #FFEFCE}
    -->
    </style>
    </head>
    <body>

    <div id="errorbox">
	    <h2>Error</h2>
	    <div>
	    <?php echo "\t\t".'<br /><br /><strong>Database reported:</strong> '.htmlspecialchars($error).(($errno) ? ' (Errno: '.$errno.')' : '')."\n";
		  echo "\t\t".'<br /><br /><strong>Failed query:</strong> '.htmlspecialchars($query)."\n";  ?>
	    </div>
    </div>

    </body>
    </html>
    <?php
	  die;
  }

  function osc_db_fetch_array($db_query) {
    return mysql_fetch_array($db_query);
  }

  function osc_db_num_rows($db_query) {
    return mysql_num_rows($db_query);
  }

  function osc_db_data_seek($db_query, $row_number) {
    return mysql_data_seek($db_query, $row_number);
  }

  function osc_db_insert_id() {
    return mysql_insert_id();
  }

  function osc_db_free_result($db_query) {
    return mysql_free_result($db_query);
  }

  function osc_db_test_create_db_permission($database) {
    global $db_error;

    $db_created = false;
    $db_error = false;

    if (!$database) {
      $db_error = 'No Database selected.';
      return false;
    }

    if (!$db_error) {
      if (!osc_db_select_db($database)) {
        $db_created = true;

        if (!osc_db_query('create database ' . $database)) {
          $db_error = mysql_error();
        }

      } else {
        $db_error = mysql_error();
      }

      if (!$db_error) {
        if (osc_db_select_db($database)) {
          if (osc_db_query('create table temp ( temp_id int(5) )')) {
            if (!osc_db_query('drop table temp')) {
	      $db_error = mysql_error();
            }
          } else {
            $db_error = mysql_error();
          }
        } else {
          $db_error = mysql_error();
        }
      }
    }

    if (!$db_error) {
      return false;
    } else {
      return true;
    }
  }

  /**
    Test la connexion
    @package oscss-2 <www http://www.oscss.org>
  */
  function osc_db_test_connection($database,$prefix) {
    global $db_error;

    $db_error = false;

    if (!$db_error) {
      if (!@osc_db_select_db($database)) {
        $db_error = mysql_error();
      } else {
        if (!@osc_db_query('select count(*) from '.$prefix.'configuration')) {
          $db_error = mysql_error();
        }
      }
    }

    if ($db_error) {
      return false;
    } else {
      return true;
    }
  }

  /**
    Insertion d'un fichier sql_file
    Converstion langue si fichier dispo
    @package oscss-2 <www http://www.oscss.org>
    @author modifié oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
  */
  function osc_db_install($database, $sql_file, $table_prefix = -1,$file_lg_sample='') {
    global $db_error,$language;

    $db_error = false;
    $lg=false;
    if (!@osc_db_select_db($database)) {
      if (@osc_db_query('create database ' . $database)) {
        osc_db_select_db($database);
      } else {
        $db_error = mysql_error();
      }
    }

    if (!$db_error) {
        if (file_exists($sql_file)) {
	  $file_lg= dirname($_SERVER['SCRIPT_FILENAME']).'/'.WS_LANGUAGE.DC_LOADER_LANG.'/'.str_replace('.sql','.txt',basename($sql_file));
	  if( $file_lg_sample !='')include($file_lg_sample);
	  elseif(file_exists($file_lg))include($file_lg);

          $fd = fopen($sql_file, 'rb');
          $import_queries = fread($fd, filesize($sql_file));
          fclose($fd);
      } else {
        $db_error = 'SQL file does not exist: ' . $sql_file;
        return false;
      }

        if (!get_cfg_var('safe_mode')) {
          @set_time_limit(0);
        }

        $sql_queries = array();
        $sql_length = strlen($import_queries);
        $pos = strpos($import_queries, ';');

        for ($i=$pos; $i<($sql_length+1); $i++) {
// remove comments
          if (isset($import_queries[0]) && $import_queries[0] == '#') {
            $import_queries = ltrim(substr($import_queries, strpos($import_queries, "\n")));
            $sql_length = strlen($import_queries);
            $i = strpos($import_queries, ';')-1;
            continue;
          }

          if (isset( $import_queries[($i+1)]) && $import_queries[($i+1)] == "\n") {
            for ($j=($i+2); $j<$sql_length; $j++) {
              if (!empty($import_queries[$j]) && $import_queries[$j]!= "\n") {
                $next = substr($import_queries, $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 ($import_queries[$k] == "\n") {
                      break;
                    }
                  }

                  $query = substr($import_queries, 0, $i+1);

                  $import_queries = substr($import_queries, $k);

// join the query before the comment appeared, with the rest of the dump
                  $import_queries = $query . $import_queries;
                  $sql_length = strlen($import_queries);
                  $i = strpos($import_queries, ';')-1;
                  continue 2;
                }

                break;
              }
            }

            if (empty($next)) { // get the last insert query
              $next = 'insert';
            }
	    if (in_array(strtoupper($next), array('TRUNCA','DROP V','DROP T','CREATE','INSERT','COMMIT','UPDATE') )) {
              $next = '';

              $sql_query = substr($import_queries, 0, $i);

              if ($table_prefix !== -1) {
                if (strtoupper(substr($sql_query, 0, 25)) == 'DROP TABLE IF EXISTS OSC_') {
                  $sql_query = 'DROP TABLE IF EXISTS ' . $table_prefix . substr($sql_query, 25);
                } elseif (strtoupper(substr($sql_query, 0, 17)) == 'CREATE TABLE OSC_') {
                  $sql_query = 'CREATE TABLE ' . $table_prefix . substr($sql_query, 17);
                } elseif (strtoupper(substr($sql_query, 0, 16)) == 'INSERT INTO OSC_') {
                  $sql_query = 'INSERT INTO ' . $table_prefix . substr($sql_query, 16);
                } elseif (strtoupper(substr($sql_query, 0, 18)) == 'TRUNCATE TABLE OSC_') {
                  $sql_query = 'TRUNCATE TABLE ' . $table_prefix . substr($sql_query, 18);
                }elseif (strtoupper(substr($sql_query, 0, 11)) == 'UPDATE OSC_') {
                  $sql_query = 'UPDATE ' . $table_prefix . substr($sql_query, 11);
                }
              }

              $sql_queries[] = $sql_query;

              $import_queries = ltrim(substr($import_queries, $i+1));
              $sql_length = strlen($import_queries);
              $i = strpos($import_queries, ';')-1;
            }
          }
        }

      for ($i=0; $i<=sizeof($sql_queries); $i++) {
	if(is_array($lg) && isset($sql_queries[$i])) osc_db_query(str_replace(array_keys($lg),array_map('addslashes',$lg),$sql_queries[$i]));
	elseif(isset($sql_queries[$i])) osc_db_query($sql_queries[$i]);
      }
    } else {
      return false;
    }
  }


  function osc_db_upgrade($database, $sql_file, $table_prefix = -1) {
    global $db_error,$language;

error_reporting(E_ALL);

    $db_error = false;
    $lg=false;
// osc_db_select_db($database);

    if (!$db_error) {

//         if (!get_cfg_var('safe_mode')) {
//           @set_time_limit(0);
//         }
          $fd = fopen($sql_file, 'rb');
          $import_queries = fread($fd, filesize($sql_file));
          fclose($fd);

        $sql_queries = array();
        $sql_length = strlen($import_queries);
        $pos = strpos($import_queries, ';');



        for ($i=$pos; $i<($sql_length+1); $i++) {
// remove comments
          if (isset($import_queries[0]) && $import_queries[0] == '#') {
            $import_queries = ltrim(substr($import_queries, strpos($import_queries, "\n")));
            $sql_length = strlen($import_queries);
            $i = strpos($import_queries, ';')-1;
            continue;
          }

          if (isset( $import_queries[($i+1)]) && $import_queries[($i+1)] == "\n") {
            for ($j=($i+2); $j<$sql_length; $j++) {
              if (!empty($import_queries[$j]) && $import_queries[$j]!= "\n") {
                $next = substr($import_queries, $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 ($import_queries[$k] == "\n") {
                      break;
                    }
                  }

                  $query = substr($import_queries, 0, $i+1);

                  $import_queries = substr($import_queries, $k);

// join the query before the comment appeared, with the rest of the dump
                  $import_queries = $query . $import_queries;
                  $sql_length = strlen($import_queries);
                  $i = strpos($import_queries, ';')-1;
                  continue 2;
                }

                break;
              }
            }

            if (empty($next)) { // get the last insert query
              $next = 'insert';
            }
            if (in_array(strtoupper($next), array('ALTER ','TRUNCA','DROP V','DROP T','CREATE','INSERT','COMMIT','RENAME','UPDATE', 'IF NOT', 'IF EXI') )) {
              $next = '';

              $sql_query = substr($import_queries, 0, $i);

              if ($table_prefix !== -1) {
                if (strtoupper(substr($sql_query, 0, 25)) == 'DROP TABLE IF EXISTS OSC_') {
                  $sql_query = 'DROP TABLE IF EXISTS ' . $table_prefix . substr($sql_query, 25);
                } elseif (strtoupper(substr($sql_query, 0, 17)) == 'CREATE TABLE OSC_') {
                  $sql_query = 'CREATE TABLE ' . $table_prefix . substr($sql_query, 17);
                } elseif (strtoupper(substr($sql_query, 0, 31)) == 'CREATE TABLE IF NOT EXISTS OSC_') {
                  $sql_query = 'CREATE TABLE IF NOT EXISTS ' . $table_prefix . substr($sql_query, 31);
                } elseif (strtoupper(substr($sql_query, 0, 16)) == 'INSERT INTO OSC_') {
                  $sql_query = 'INSERT INTO ' . $table_prefix . substr($sql_query, 16);
                }elseif (strtoupper(substr($sql_query, 0, 16)) == 'ALTER TABLE OSC_') {
                  $sql_query = 'ALTER TABLE ' . $table_prefix . substr($sql_query, 16);
                } elseif (strtoupper(substr($sql_query, 0, 11)) == 'UPDATE OSC_') {
                  $sql_query = 'UPDATE ' . $table_prefix . substr($sql_query, 11);
                }elseif (strtoupper(substr($sql_query, 0, 18)) == 'TRUNCATE TABLE OSC_') {
                  $sql_query = 'TRUNCATE TABLE ' . $table_prefix . substr($sql_query, 18);
                } elseif (strtoupper(substr($sql_query, 0, 12)) == 'RENAME TABLE') {
                  $sql_query = str_replace('  OSC_',' '.$table_prefix,$sql_query);
                }
		elseif (strtoupper(substr($sql_query, 0, 16)) == 'IF NOT EXISTS') {
                  $sql_query = str_replace('  OSC_',' '.$table_prefix,$sql_query);
                }
		elseif (strtoupper(substr($sql_query, 0, 12)) == 'IF EXISTS') {
                  $sql_query = str_replace('  OSC_',' '.$table_prefix,$sql_query);
                }
              }

              $sql_queries[] = $sql_query;

              $import_queries = ltrim(substr($import_queries, $i+1));
              $sql_length = strlen($import_queries);
              $i = strpos($import_queries, ';')-1;
            }
          }
        }

      for ($i=0; $i<=sizeof($sql_queries); $i++) {
	 if(isset($sql_queries[$i])){
	  echo $sql_queries[$i];
	  osc_db_query_noblock($sql_queries[$i]);
	  echo '<br />';
	}
      }
    } else {
      return false;
    }
  }
?>