<?php
/*
  $Id: database.php,v 1.1.1.1 2004/03/04 23:40:48 ccwjr Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

  function tep_db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link') {
    global $$link;

      $$link = mysqli_connect($server, $username, $password, $database);
	  // Check connection
	  if (mysqli_connect_errno())	{
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
		exit();
	  }

	  //Set all client/server communication in UTF8
	  mysqli_query($$link, "SET CHARACTER SET utf8");
	  mysqli_query($$link, "SET NAMES 'utf8'");
	  mysqli_query($$link, "SET SESSION sql_mode=''");

	return $$link;
  }

  function tep_db_close($link = 'db_link') {
    global $$link;
    return mysqli_close($$link);
  }

  function tep_db_error($query, $errno, $error) {
    global $PHP_SELF;
    if(trim($errno) != '')
    {
		ob_start();
		debug_print_backtrace();
		$traceback = ob_get_clean();
		$isSecure = false;
		if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
			$isSecure = true;
		}
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
			$isSecure = true;
		}
		$request_protocol = $isSecure ? 'On' : 'Off';
		$msg = '<b>Date/Time:</b> '.date('m/d/Y H:i:s'). "\n";
		$msg .= '<b>Domain:</b> '.$_SERVER['HTTP_HOST']. "\n";
		$msg .= '<b>IP Address:</b> '.$_SERVER['REMOTE_ADDR']. "\n";
		$msg .= '<b>URL:</b> '.$_SERVER['REQUEST_URI']. "\n\n";
		$msg .= 'Query Error reported on page ' . $PHP_SELF . "\n" . 'MySQL error: ' . $errno . ' - ' . $error . "\n\n" . $query . "\n\n";
		$msg .= 'URI for the page: ' . $_SERVER['REQUEST_URI'] . "\n\n";
		$msg .= 'Backtrace ' . $traceback . "\n\n";

		$msg .= '<b>General Data</b>'."\n\n";
		$msg .= '<b>PATH_INFO:</b> '.$_SERVER['SCRIPT_FILENAME']. "\n";
		$msg .= '<b>SCRIPT_NAME: :</b> '.$_SERVER['SCRIPT_FILENAME']. "\n";
		$msg .= '<b>LOCAL_ADDR:</b> '.$_SERVER['SERVER_ADDR']. "\n";
		$msg .= '<b>REMOTE_ADDR:</b> '.$_SERVER['REMOTE_ADDR']. "\n";
		$msg .= '<b>REQUEST_METHOD:</b> '.$_SERVER['REQUEST_URI']. "\n";
		$msg .= '<b>SERVER_PROTOCOL:</b> '.$_SERVER['SERVER_PROTOCOL']. "\n";
		$msg .= '<b>HTTPS:</b> '.$request_protocol. "\n";
		$msg .= '<b>HTTP_USER_AGENT:</b> '.$_SERVER['HTTP_USER_AGENT']. "\n";
		$msg .= '<b>HTTP_COOKIE:</b> '.$_SERVER['HTTP_COOKIE']. "\n";
		$msg .= '<b>HTTP_REFERER:</b> '.$_SERVER['HTTP_REFERER']. "\n";

		$email_address = 'devi@egcms.com';
		if ($email_address != '')
		{
			// Always set content-type when sending HTML email
			$headers = "MIME-Version: 1.0" . "\n";
			$headers .= "Content-type:text/html;charset=UTF-8" . "\n";

			// More headers
			$headers .= 'From: '. STORE_OWNER .'<'. STORE_OWNER_EMAIL_ADDRESS .'>' . "\n";
			//mail($email_address, STORE_NAME.': Critical Store Error!', nl2br($msg), $headers);
		}
		// log the error message
		_error_handler($msg);
		die(INTERNAL_ERROR);
	}
  }

  function tep_db_query($query, $debug=0, $link = 'db_link') {
    global $$link;

    if($debug)
    	echo $query;

    if (defined('STORE_DB_TRANSACTIONS') && (STORE_DB_TRANSACTIONS == 'true')) {
      $page_name = $_SERVER['SCRIPT_FILENAME'];
      $page_name = str_replace('\\', '/', $page_name);
      $page_name = str_replace('//', '/', $page_name);
      $i = strrpos($page_name, '/');
      $page_name = substr($page_name, $i+1);
      error_log('QUERY - ' . $page_name . ':'. "\n" . $query . "\n", 3, DIR_FS_CATALOG . STORE_PAGE_PARSE_TIME_LOG);
      $sql_start = microtime(true);
    }

    $result = mysqli_query($$link, $query) or tep_db_error($query, mysqli_errno($$link), mysqli_error($$link));

    if (defined('STORE_DB_TRANSACTIONS') && (STORE_DB_TRANSACTIONS == 'true')) {
      $sql_end = microtime(true);
      $sql_exec_time = $sql_end - $sql_start;
      $row_count = mysqli_num_rows($result);
      error_log('RESULT - time: ' . $sql_exec_time . ' rows: ' . $row_count . "\n\n", 3, DIR_FS_CATALOG . STORE_PAGE_PARSE_TIME_LOG);
    }

    return $result;
  }

  function tep_db_perform($table, $data, $action = 'insert', $parameters = '', $link = 'db_link') {
    reset($data);
    if ($action == 'insert') {
      $query = 'insert into ' . $table . ' (';
	  foreach($data as $columns=>$tmpvalue) {
        $query .= $columns . ', ';
      }
      $query = substr($query, 0, -2) . ') values (';
      reset($data);
	  foreach($data as $tmpcols=>$value) {
        switch ((string)$value) {
          case 'now()':
            $query .= 'now(), ';
            break;
          case 'null':
            $query .= 'null, ';
            break;
          default:
            $query .= '\'' . tep_db_input($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ')';
    } elseif ($action == 'update') {
      $query = 'update ' . $table . ' set ';
	  foreach($data as $columns=>$value) {
        switch ((string)$value) {
          case 'now()':
            $query .= $columns . ' = now(), ';
            break;
          case 'null':
            $query .= $columns .= ' = null, ';
            break;
          default:
            $query .= $columns . ' = \'' . tep_db_input($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ' where ' . $parameters;
    }

    return tep_db_query($query, 0, $link);
  }

  function tep_db_insert_delayed($table, $data, $parameters = '', $link = 'db_link') {
    reset($data);
    $query = 'INSERT DELAYED INTO ' . $table . ' (';
	foreach($data as $columns=>$tmpvalue) {
      $query .= $columns . ', ';
    }
    $query = substr($query, 0, -2) . ') values (';
    reset($data);
	foreach($data as $tmpcol=>$value) {
      switch ((string)$value) {
        case 'now()':
          $query .= 'now(), ';
          break;
        case 'null':
          $query .= 'null, ';
          break;
        default:
          $query .= '\'' . tep_db_input($value) . '\', ';
          break;
      }
    }
    $query = substr($query, 0, -2) . ')';

    return tep_db_query($query, $link);
  }

  function tep_db_fetch_array($db_query) {
	if ($db_query instanceof mysqli_result) {
    	return mysqli_fetch_array($db_query, MYSQLI_ASSOC);
    }
  }

  function tep_db_fetch_row($db_query) {
    return mysqli_fetch_row($db_query);
  }

  function tep_db_num_rows($db_query) {
	if ($db_query instanceof mysqli_result) {
    	return mysqli_num_rows($db_query);
    }
  }

  function tep_db_data_seek($db_query, $row_number) {
    return mysqli_data_seek($db_query, $row_number);
  }

  function tep_db_insert_id($link = 'db_link') {
    global $$link;
    return mysqli_insert_id($$link);
  }

  function tep_db_free_result($db_query) {
    return mysqli_free_result($db_query);
  }

  function tep_db_fetch_fields($db_query) {
    return mysqli_fetch_field($db_query);
  }

  function tep_db_output($string) {
    return html_entity_decode(htmlspecialchars($string));
  }

  function tep_db_input($string) {
    return addslashes($string);
  }

  function tep_db_real_escape_string($string, $link = 'db_link') {
    global $$link;
    return mysqli_real_escape_string($$link, $string);
  }

  function tep_db_escape_string($string) {
    return tep_db_real_escape_string($string);
  }

  function tep_db_get_result($query, $debug=0, $link = 'db_link') {
    global $$link;

    if($debug)
    	echo $query;

    $result = tep_db_query($query);	
	$arrData = array();
	while($row = tep_db_fetch_array($result)) {
		$arrData[] = $row;
	}

    return $arrData;
  }

  function tep_db_prepare_input($string) {
    if (is_string($string)) {
      return trim(tep_sanitize_string(stripslashes($string)));
    } elseif (is_array($string)) {
      reset($string);
	  foreach($string as $key=>$value) {
        $string[$key] = tep_db_prepare_input($value);
      }
      return $string;
    } else {
      return $string;
    }
  }

  //Eversun mod for sppc and qty price breaks
 function tep_db_table_exists($table, $link = 'db_link') {
    $result = tep_db_query("show table status from `" . DB_DATABASE . "`");
    while ($list_tables = tep_db_fetch_array($result)) {
    	if ($list_tables['Name'] == $table) {
    	  return true;
    	}
    }
    return false;
  }

  function tep_db_list_fields($table_name) {
	$arr_fields = array();
	if($table_name != '') {
		$result = tep_db_query("SHOW COLUMNS FROM ".$table_name);
		if (tep_db_num_rows($result) > 0) {
			while ($row = tep_db_fetch_array($result)) {
				$arr_fields[] = $row;
			}
		}
	}
    return $arr_fields;
  }

  function tep_db_decoder($string) {
	$string = str_replace('&#39;', "'", $string);
	$string = str_replace('&#39', "'", $string); //backword compatabiliy
	return $string;
  }
?>
