<?php
/*
      
osCommerce, Open Source E-Commerce Solutions 
http://www.oscommerce.com 

Copyright (c) 2003 osCommerce 

osCommRes, Services Online 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare 

Released under the GNU General Public License 
*/
//catchFatalErrors();
//set_error_handler("myErrorHandler");

// set the level of error reporting

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
   
 if(!isset($joomla_include)){ 
	error_reporting(E_ALL & ~E_NOTICE);
    ini_set('session.bug_compat_42',0);
    ini_set('session.bug_compat_warn',0);
    $NOGLOBALS_SESSION_DATA=array();
   if (version_compare(phpversion(), "4.5.0", "<")===true || ( strtolower(ini_get("register_long_arrays"))=="on" || strtolower(ini_get("register_long_arrays"))=="1")) {
	   $REGISTER_LONG_ARRAYS=true;
   } else {
		$REGISTER_LONG_ARRAYS=false;
   }
	$_SERVER['SCRIPT_FILENAME']=$_SERVER['DOCUMENT_ROOT'].((strpos($_SERVER['DOCUMENT_ROOT'],"\\")>0)?str_replace("/","\\",$_SERVER['PHP_SELF']):$_SERVER['PHP_SELF']);
	if (version_compare(phpversion(), "4.5.0", "<") === true) {
	    $_GET =& $HTTP_GET_VARS;
	    $_POST =& $HTTP_POST_VARS;
	    $_SERVER =& $HTTP_SERVER_VARS;
	    $_FILES =& $HTTP_POST_FILES;
	    $_ENV =& $HTTP_ENV_VARS;
	    if (isset($HTTP_COOKIE_VARS)) $_COOKIE =& $HTTP_COOKIE_VARS;
 	} else if (!$REGISTER_LONG_ARRAYS){
	    $HTTP_GET_VARS=&$_GET;
	    $HTTP_POST_VARS=&$_POST;
	    $HTTP_SERVER_VARS=&$_SERVER;
	    $HTTP_POST_FILES=&$_FILES;
	    $HTTP_ENV_VARS=&$_ENV;
	    if (isset($_COOKIE)) $HTTP_COOKIE_VARS=&$_COOKIE;
 	}
	define('CHECK_CON','');
 if (strtolower(ini_get("register_globals"))=="on" || strtolower(ini_get("register_globals"))=="1" ) {
	 $REGISTER_GLOBALS=true;
 } else {
	 $REGISTER_GLOBALS=false;
 }
  if (!$REGISTER_GLOBALS) { 
    extract($_GET, EXTR_SKIP); 
    extract($_POST, EXTR_SKIP); 
    extract($_COOKIE, EXTR_SKIP);
	extract($_SERVER,EXTR_SKIP);
  }
  ini_set('default_charset','iso-8859-1'); //set charset

// start the timer for the page pars	e time log
  define('PAGE_PARSE_START_TIME', microtime());

// check if register_globals is enabled.
// since this is a temporary measure this message is hardcoded. The requirement will be removed before 2.2 is finalized.
  // init the global variables if needed
   if (function_exists('ini_get')) {
    //ini_get('register_globals') or exit('FATAL ERROR: register_globals is disabled in php.ini, please enable it!');
  }

// Set the local configuration parameters - mainly for developers
  if (file_exists('includes/local/configure.php')) include('includes/local/configure.php');

// include server parameters
  require('includes/configure.php');

  require(DIR_WS_CLASSES . 'filter_input.php');

  if( (isset($HTTP_POST_VARS)) || (isset($HTTP_GET_VARS)) ){
		$INPUT_FILTER = new filter_input();
		if(count($HTTP_POST_VARS)>0){
			reset($HTTP_POST_VARS);
			while(list($key,) = each($HTTP_POST_VARS)){ 
					 if( !is_array($HTTP_POST_VARS[$key]) ){
					 $HTTP_POST_VARS[$key]=$INPUT_FILTER->_cleanTags($HTTP_POST_VARS[$key]);
					 }
				}
		}		
		if (count($HTTP_GET_VARS)>0){
			reset($HTTP_GET_VARS);	
			while(list($key,) = each($HTTP_GET_VARS)){
					if(!is_array($HTTP_GET_VARS[$key])){
					$HTTP_GET_VARS[$key]=$INPUT_FILTER->_cleanTags($HTTP_GET_VARS[$key]);
					}
				}	
		}	
    }
 
  include(DIR_WS_CLASSES . 'request.php');

  $REQUEST= new phprequest();
  

  if (strlen(DB_SERVER) < 1) {
    if (is_dir('install')) {
      header('Location: install/index.php');
    }
  }
   
// define the project version
  define('PROJECT_VERSION', 'Freeway');
// set the type of request (secure or not)
  $request_type = (getenv('HTTPS') == 'on') ? 'SSL' : 'NONSSL';

// set php_self in the local scope
  if (!isset($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];

  if ($request_type == 'NONSSL') {
    define('DIR_WS_CATALOG', DIR_WS_HTTP_CATALOG);
  } else {
    define('DIR_WS_CATALOG', DIR_WS_HTTPS_CATALOG);
  }
	$TEMPLATE_MAIN_PAGE='';
// include the list of project filenames
  require(DIR_WS_INCLUDES . 'filenames.php');

// include the list of project database tables
  require(DIR_WS_INCLUDES . 'database_tables.php');

// customization for the design layout
//define('BOX_WIDTH', 125); // how wide the boxes should be in pixels (default: 125)

// include the database functions
  require(DIR_WS_FUNCTIONS . 'database.php');

// make a connection to the database... now
  tep_db_connect() or die('Unable to connect to database server!');

// set the application parameters
  $configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);
  while ($configuration = tep_db_fetch_array($configuration_query)) {
    define($configuration['cfgKey'], $configuration['cfgValue']);
  }

// if gzip_compression is enabled, start to buffer the output
  if ( (GZIP_COMPRESSION == 'true') && ($ext_zlib_loaded = extension_loaded('zlib')) && (PHP_VERSION >= '4') ) {
    if (($ini_zlib_output_compression = (int)ini_get('zlib.output_compression')) < 1) {
      if (PHP_VERSION >= '4.0.4') {
        ob_start('ob_gzhandler');
      } else {
        include(DIR_WS_FUNCTIONS . 'gzip_compression.php');
        ob_start();
        ob_implicit_flush();
      }
    } else {
      ini_set('zlib.output_compression_level', GZIP_LEVEL);
    }
  }


// set the HTTP GET parameters manually if search_engine_friendly_urls is enabled
  if (SEARCH_ENGINE_FRIENDLY_URLS == 'true' && strpos($_SERVER['REQUEST_URI'], '.php')!==false) {
		$path_info=$_SERVER["REQUEST_URI"];
    if (strlen($path_info) > 1) {
      $GET_array = array();
	  $temp_pos=strpos($path_info,".php");

	  if ($temp_pos!==false){
		  $PHP_SELF=substr($path_info,0,$temp_pos+4);
		  $_SERVER['PHP_SELF']=$PHP_SELF;
	      $path_info = substr($path_info,$temp_pos+4);
	  }
      $vars = explode('/', substr($path_info, 1));
      for ($i=0, $n=count($vars); $i<$n; $i++) {
        if (strpos($vars[$i], '[]')) {
          $GET_array[substr($vars[$i], 0, -2)][] = $vars[$i+1];
        } else {
          $HTTP_GET_VARS[$vars[$i]] = $vars[$i+1];
        }
        $i++;
      }

      if (sizeof($GET_array) > 0) {
        while (list($key, $value) = each($GET_array)) {
          $HTTP_GET_VARS[$key] = $value;
        }
      }
    }
  }

// define general functions used application-wide
  require(DIR_WS_FUNCTIONS . 'general.php');
  require(DIR_WS_FUNCTIONS . 'html_output.php');

// set the cookie domain
  $cookie_domain = (($request_type == 'NONSSL') ? HTTP_COOKIE_DOMAIN : HTTPS_COOKIE_DOMAIN);
  $cookie_path = (($request_type == 'NONSSL') ? HTTP_COOKIE_PATH : HTTPS_COOKIE_PATH);

// include cache functions if enabled
if (USE_CACHE == 'true') include(DIR_WS_FUNCTIONS . 'cache.php');
// SEF BEGIN

  require(DIR_WS_CLASSES . 'seo_url.php');
  $SEO_URL = new seo_url;
  if ($GLOBALS["SEO_URL"]->enabled){
	  $SEO_URL->restore_seo_url();
}
// include shopping cart class

  require(DIR_WS_CLASSES . 'shopping_cart.php');
  require(DIR_WS_CLASSES . "services.php");


// include navigation history class
  require(DIR_WS_CLASSES . 'navigation_history.php');


// some code to solve compatibility issues
  require(DIR_WS_FUNCTIONS . 'compatibility.php');
  

// check if sessions are supported, otherwise use the php3 compatible session class
  if (!function_exists('session_start')) {
    define('PHP_SESSION_NAME', 'osCsid');
    define('PHP_SESSION_PATH', $cookie_path);
    define('PHP_SESSION_DOMAIN', $cookie_domain);
    define('PHP_SESSION_SAVE_PATH', SESSION_WRITE_DIRECTORY);

    include(DIR_WS_CLASSES . 'sessions.php');
  }

// define how the session functions will be used
//require(DIR_WS_FUNCTIONS . 'sessions.php');
	if ($REGISTER_GLOBALS){
		require(DIR_WS_FUNCTIONS . 'sessions.php');
	}else{
		require(DIR_WS_FUNCTIONS . 'sessions_no_globals.php');
    } 
// set the session name and save path
  tep_session_name('osCsid');
  tep_session_save_path(SESSION_WRITE_DIRECTORY);
  
  // set the session cookie parameters
   if (function_exists('session_set_cookie_params')) {
    session_set_cookie_params(0, $cookie_path,$cookie_domain);
  } elseif (function_exists('ini_set')) {
    ini_set('session.cookie_lifetime', '0');
    ini_set('session.cookie_path', $cookie_path);
    ini_set('session.cookie_domain', $cookie_domain);
  }
  
// set the session ID if it exists
   if (isset($HTTP_POST_VARS[tep_session_name()])) {
     tep_session_id($HTTP_POST_VARS[tep_session_name()]);
   } elseif ( ($request_type=="SSL") && isset($HTTP_GET_VARS[tep_session_name()]) ) {
     tep_session_id($HTTP_GET_VARS[tep_session_name()]);
   } elseif ($LINK_OSC_ID!=''){
	   tep_session_id($LINK_OSC_ID);
   }

// start the session
  $session_started = false;
  if (SESSION_FORCE_COOKIE_USE == 'True') {
    tep_setcookie('cookie_test', 'please_accept_for_session', time()+60*60*24*30, $cookie_path, $cookie_domain);

    if (isset($HTTP_COOKIE_VARS['cookie_test'])) {
      tep_session_start();
      $session_started = true;
    }
  } elseif (SESSION_BLOCK_SPIDERS == 'True') {
    $user_agent = strtolower(getenv('HTTP_USER_AGENT'));
    $spider_flag = false;

    if (tep_not_null($user_agent)) {
      $spiders = file(DIR_WS_INCLUDES . 'spiders.txt');

      for ($i=0, $n=sizeof($spiders); $i<$n; $i++) {
        if (tep_not_null($spiders[$i])) {
          if (is_integer(strpos($user_agent, trim($spiders[$i])))) {
            $spider_flag = true;
            break;
          }
        }
      }
    }
    if ($spider_flag == false) {
      tep_session_start();
      $session_started = true;
    }
  } else {
    tep_session_start();
    $session_started = true;
  }

// set SID once, even if empty
  // Register Globals MOD - http://oscommerce.magic-seo-url.com
  if (!$REGISTER_GLOBALS) {
  	if ($REGISTER_LONG_ARRAYS){
		$NOGLOBALS_SESSION_DATA=&$HTTP_SESSION_VARS;
	} else {
		$NOGLOBALS_SESSION_DATA=&$_SESSION;
	}
    if ($REGISTER_LONG_ARRAYS) {
       $_SESSION =&$HTTP_SESSION_VARS;
    } else {
		$HTTP_SESSION_VARS=$_SESSION;
	}
	if (count($NOGLOBALS_SESSION_DATA)>0){
		reset($NOGLOBALS_SESSION_DATA);
		while(list($key,$value)=each($NOGLOBALS_SESSION_DATA)){
			$$key=$value;
		}
	}
  }
  
  $SID = (defined('SID') ? SID : '');

// verify the ssl_session_id if the feature is enabled
  if ( ($request_type == 'SSL') && (SESSION_CHECK_SSL_SESSION_ID == 'True') && (ENABLE_SSL == true) && ($session_started == true) ) {
    $ssl_session_id = getenv('SSL_SESSION_ID');
    if (!tep_session_is_registered('SSL_SESSION_ID')) {
      $SESSION_SSL_ID = $ssl_session_id;
      tep_session_register('SESSION_SSL_ID');
    }

    if ($SESSION_SSL_ID != $ssl_session_id) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_SSL_CHECK));
    }
  }

// verify the browser user agent if the feature is enabled
  if (SESSION_CHECK_USER_AGENT == 'True') {
    $http_user_agent = getenv('HTTP_USER_AGENT');
    if (!tep_session_is_registered('SESSION_USER_AGENT')) {
      $SESSION_USER_AGENT = $http_user_agent;
      tep_session_register('SESSION_USER_AGENT');
    }

    if ($SESSION_USER_AGENT != $http_user_agent) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_LOGIN));
    }
  }

// verify the IP address if the feature is enabled
  if (SESSION_CHECK_IP_ADDRESS == 'True') {
    $ip_address = tep_get_ip_address();
    if (!tep_session_is_registered('SESSION_IP_ADDRESS')) {
      $SESSION_IP_ADDRESS = $ip_address;
      tep_session_register('SESSION_IP_ADDRESS');
    }

    if ($SESSION_IP_ADDRESS != $ip_address) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_LOGIN));
    }
  }

 /*if (!function_exists('ini_get') || ini_get('register_globals')==0){
	if (count($HTTP_GET_VARS)>0){
		reset($HTTP_GET_VARS);
		while(list($key,$value)=each($HTTP_GET_VARS)){
			$$key=$value;
		}
	}
	if (count($HTTP_POST_VARS)>0){
		reset($HTTP_POST_VARS);
		while(list($key,$value)=each($HTTP_POST_VARS)){
			$$key=$value;
		}
	}
	if (count($HTTP_SESSION_VARS)>0){
		reset($HTTP_SESSION_VARS);
		while(list($key,$value)=each($HTTP_SESSION_VARS)){
			$$key=$value;
		}
	}
  }*/
  if (!tep_session_is_registered('GLOBAL_LIST')){
  	$NOGLOBALS_SESSION_DATA["GLOBAL_LIST"]=array();
  }
// create the shopping cart & fix the cart if necesary
  if (tep_session_is_registered('cart') && is_object($cart)) {
    if (version_compare(phpversion(), "4.0.0", "<")) {
      $broken_cart = $cart;
      $cart = new shoppingCart;
      $cart->unserialize($broken_cart);
    }
  } else {
    tep_session_register('cart');
    $cart = new shoppingCart;
  }

   // check the cookie for the user values
  $osCuser=isset($HTTP_COOKIE_VARS["osCuser"])?$HTTP_COOKIE_VARS["osCuser"]:'';
  $oscPass=isset($HTTP_COOKIE_VARS["osCpass"])?$HTTP_COOKIE_VARS["osCpass"]:'';
  $current_file=basename($PHP_SELF);

  if (!tep_session_is_registered('customer_id') && !tep_session_is_registered('customer_auto_name') && $osCuser!="" && $oscPass!="" && $current_file!=FILENAME_LOGIN && $current_file!=FILENAME_LOGOFF){
	$add_option="";
	if (ACCOUNT_USERNAME=="true") $add_option=" or customers_username='" . tep_db_input($osCuser) . "'";
    $check_customer_query = tep_db_query("select customers_id, customers_firstname, customers_password, customers_email_address, customers_default_address_id,encryption_style from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($osCuser) . "' " . $add_option);
	
	if (tep_db_num_rows($check_customer_query)>0){
      $check_customer = tep_db_fetch_array($check_customer_query);
	  $hash_value=defined('ENCRYPTION_HASH_VALUE')?ENCRYPTION_HASH_VALUE:'@sC@mmRes';
	  if ($oscPass==md5($check_customer["customers_password"] . $hash_value)){
        if (SESSION_RECREATE == 'True') {
          tep_session_recreate();
        }
        $customer_auto_name = $check_customer['customers_firstname'];
        tep_session_register('customer_auto_name');

		// update survey flag if customer exist
		tep_set_session_value('error_count',0); 
		$sName=tep_session_name();
		$sKey=isset($HTTP_GET_VARS[$sName])?tep_db_prepare_input($HTTP_GET_VARS[$sName]):'';
		
		tep_db_query("update " . TABLE_EVENTS_SURVEYS_FLAG . " set survey_flag_email='" . $customer_id . "' where survey_flag_email='" .$sKey . "'");
		// restore cart contents
		$SID = (defined('SID') ? SID : '');
		tep_redirect(tep_href_link($current_file,tep_get_all_get_params(),'SSL'));
	  }// $oscPass
  }// $check_customers_query
 }// session_registered
  
  if (tep_session_is_registered('customer_id') && $HTTP_COOKIE_VARS['survey_login_id']!=$customer_id){
     tep_setcookie('survey_login_id',$customer_id,time()+(30*24*60*60),$cookie_path,$cookie_domain);
  }



// include currencies class and create an instance
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new currencies();

// include the mail classes
  require(DIR_WS_CLASSES . 'mime.php');
  require(DIR_WS_CLASSES . 'email.php');
  
	if (defined('USE_SMTP') && USE_SMTP && file_exists(DIR_WS_CLASSES . 'class.phpgmailer.php')) {
	  require(DIR_WS_CLASSES . 'class.phpgmailer.php');
    }
  
// set the language
  if (!tep_session_is_registered('language') || isset($HTTP_GET_VARS['language'])) {
    if (!tep_session_is_registered('language')) {
      tep_session_register('language');
      tep_session_register('languages_id');
    }

    include(DIR_WS_CLASSES . 'language.php');
    $lng = new language();

    if (isset($HTTP_GET_VARS['language']) && tep_not_null($HTTP_GET_VARS['language'])) {
      $lng->set_language($HTTP_GET_VARS['language']);
    } else {
      $lng->get_browser_language();
    }

    $language = $lng->language['directory'];

    $languages_id = $lng->language['id'];
  }

// include the language translations
  require(DIR_WS_LANGUAGES . $language . '.php');
  
// currency
  if (!tep_session_is_registered('currency') || isset($HTTP_GET_VARS['currency'])) {
    if (!tep_session_is_registered('currency')) tep_session_register('currency');

    if (isset($HTTP_GET_VARS['currency'])) {
      if (!$currency = tep_currency_exists($HTTP_GET_VARS['currency'])) $currency = DEFAULT_CURRENCY;
    } else {
      $currency = DEFAULT_CURRENCY;
    }
  }
  /*$currency_count = 1;
  if(USE_DEFAULT_LANGUAGE_CURRENCY && strtolower(USE_DEFAULT_LANGUAGE_CURRENCY) == 'true'){
	  $sql = "select count(*) as count from " . TABLE_CURRENCIES . " where code='" . LANGUAGE_CURRENCY . "'";
	  $query = tep_db_query($sql);
	  $result = tep_db_fetch_array($query);
	  $currency_count = $result['count'];
  }*/


// navigation history
  if (tep_session_is_registered('navigation')) {
    if (PHP_VERSION < 4) {
      $broken_navigation = $navigation;
      $navigation = new navigationHistory;
      $navigation->unserialize($broken_navigation);
    }
  } else {
    tep_session_register('navigation');
    $navigation = new navigationHistory;
  }
  $navigation->add_current_page();

// BOF: Down for Maintenance except for admin ip
if (EXCLUDE_ADMIN_IP_FOR_MAINTENANCE != getenv('REMOTE_ADDR')){
	if (DOWN_FOR_MAINTENANCE=='true' and !strstr($PHP_SELF,DOWN_FOR_MAINTENANCE_FILENAME)) { tep_redirect(tep_href_link(DOWN_FOR_MAINTENANCE_FILENAME)); }
	}
// do not let people get to down for maintenance page if not turned on
if (DOWN_FOR_MAINTENANCE=='false' and strstr($PHP_SELF,DOWN_FOR_MAINTENANCE_FILENAME)) {
    tep_redirect(tep_href_link(FILENAME_DEFAULT));
}
// EOF: WebMakers.com Added: Down for Maintenance


// BOF: WebMakers.com Added: Functions Library
    include(DIR_WS_FUNCTIONS . 'webmakers_added_functions.php');
// EOF: WebMakers.com Added: Functions Library
  if (isset($HTTP_GET_VARS['action'])) {

// redirect the customer to a friendly cookie-must-be-enabled page if cookies are disabled
    if ($session_started == false) {
      tep_redirect(tep_href_link(FILENAME_COOKIE_USAGE));
    }
    if (DISPLAY_CART == 'true') {
      $goto =  FILENAME_SHOPPING_CART;
	  $parameters = array('action', 'cPath', 'products_id', 'pid');
    } else {
      $goto = basename($PHP_SELF);
      if ($HTTP_GET_VARS['action'] == 'buy_now') {
        $parameters = array('action', 'pid', 'products_id');
      } else {
        $parameters = array('action', 'pid');
      }
    }
    switch ($HTTP_GET_VARS['action']) {
      // customer wants to update the product quantity in their shopping cart
      case 'update_product' : for ($i=0, $n=sizeof($HTTP_POST_VARS['products_id']); $i<$n; $i++) {
                                if (in_array($HTTP_POST_VARS['products_id'][$i], (is_array($HTTP_POST_VARS['cart_delete']) ? tep_db_prepare_input($HTTP_POST_VARS['cart_delete']) : array()))) {
                                  $cart->remove($HTTP_POST_VARS['products_id'][$i]);
                                } else {
                                  if (PHP_VERSION < 4) {
                                    // if PHP3, make correction for lack of multidimensional array.
                                    reset($HTTP_POST_VARS);
                                    while (list($key, $value) = each($HTTP_POST_VARS)) {
                                      if (is_array($value)) {
                                        while (list($key2, $value2) = each($value)) {
                                          if (ereg ("(.*)\]\[(.*)", $key2, $var)) {
                                            $id2[$var[1]][$var[2]] = $value2;
                                          }
                                        }
                                      }
                                    }
                                    $attributes = ($id2[$HTTP_POST_VARS['products_id'][$i]]) ? $id2[tep_db_prepare_input($HTTP_POST_VARS['products_id'][$i])] : '';
                                  } else {
                                    $attributes = ($HTTP_POST_VARS['id'][$HTTP_POST_VARS['products_id'][$i]]) ? tep_db_prepare_input($HTTP_POST_VARS['id'][$HTTP_POST_VARS['products_id'][$i]]) : '';
                                  }
                                  $cart->add_cart($HTTP_POST_VARS['products_id'][$i], $HTTP_POST_VARS['cart_quantity'][$i], $attributes, false);
                                }
                              }
                              tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                              break;
      // customer adds a product from the products page
      case 'add_product' :   
				if (isset($HTTP_POST_VARS['products_id']) && is_numeric($HTTP_POST_VARS['products_id'])) {
					$products_id=(int)$HTTP_POST_VARS['products_id'];
					$subscription_start_date = isset($HTTP_POST_VARS['your_start_date'])?tep_convert_date_raw($HTTP_POST_VARS['your_start_date']):'0000-00-00';
					$serverDate = date('Y-m-d',getServerDate(false));
					
					$qty=isset($HTTP_POST_VARS['qty'])?(int)$HTTP_POST_VARS['qty']:1;
					if ($qty<=0) $qty=1;

					
					$attributes="";
					if (isset($HTTP_POST_VARS['id'])){
						$attributes=tep_db_prepare_input($HTTP_POST_VARS['id']);
					} else if (isset($HTTP_POST_VARS['attrValues']) && isset($HTTP_POST_VARS['attrIds'])){
						for ($icnt=0,$n=count($HTTP_POST_VARS['attrValues']);$icnt<$n;$icnt++){
							$attributes[$HTTP_POST_VARS['attrIds'][$icnt]]=tep_db_prepare_input($HTTP_POST_VARS['attrValues'][$icnt]);
						}
					}
					$salemaker_id=isset($HTTP_POST_VARS['salemaker_id'])?(int)$HTTP_POST_VARS['salemaker_id']:0;
					//if (!$cart->is_price_break((int)$HTTP_POST_VARS['products_id'])) $qty+=$cart->get_quantity(tep_get_uprid($products_id, $HTTP_POST_VARS['id']));
					$cart->add_cart($products_id, $qty, $attributes,true,array(),0,$salemaker_id);
					// check for forced products;
					$xsell_ids=(isset($HTTP_POST_VARS["xsell_forced_id"])?tep_db_prepare_input($HTTP_POST_VARS["xsell_forced_id"]):array());
					if (count($xsell_ids)>0){
						for ($lcnt=0;$lcnt<count($xsell_ids);$lcnt++){
							$attr=(isset($xsell_forced_attributes[$xsell_ids[$lcnt]])?$xsell_forced_attributes[$xsell_ids[$lcnt]]:array());
							
						$sale_query=tep_db_query("select apply_to_cross_sale from " . TABLE_SALEMAKER_SALES . " where sale_id='" . $salemaker_id . "'")	;
						$sale_result=tep_db_fetch_array($sale_query);
						$sale_id=0;
						if($sale_result['apply_to_cross_sale']=='Y')
							$sale_id=$salemaker_id;
						
						 $cart->add_cart($xsell_ids[$lcnt], 1, $attr,true,array(),0,$sale_id);
						}
					}
				}
				tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                break;
				
				
		// Modificacion Wishlist Checkboxes
case 'add_products_wishlist' : if (isset($HTTP_POST_VARS['add_wishprod'])) {
			if ($HTTP_POST_VARS['borrar'] == 0) {
  				  foreach ($HTTP_POST_VARS['add_wishprod'] as $value) {
   					 if (ereg('^[0-9]+$', $value)) {					tep_db_query("delete from " . TABLE_WISHLIST . " where products_id = $value and customers_id = '" . tep_db_input($customer_id) . "'");
    			$cart->add_cart($value, $cart->get_quantity(tep_get_uprid($value, tep_db_prepare_input($HTTP_POST_VARS['id'])))+1, tep_db_prepare_input($HTTP_POST_VARS['id']));
   				 }
  			}
			tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
		}
	if ($HTTP_POST_VARS['borrar'] == 1) {
  		foreach ($HTTP_POST_VARS['add_wishprod'] as $value) {
   			 if (ereg('^[0-9]+$', $value)) {
 				tep_db_query("delete from " . TABLE_WISHLIST . " where products_id = $value and customers_id = '" . tep_db_input($customer_id) . "'");
  			 }
 		 }
		tep_redirect(tep_href_link(FILENAME_WISHLIST));
	   }
	}
  break;
		// Fin Wishlist Checkboxes

// Add product to the wishlist
      case 'add_wishlist' :   if (ereg('^[0-9]+$', $HTTP_GET_VARS['products_id'])) {
                                if ($HTTP_GET_VARS['products_id']) {
                                  tep_db_query("delete from " . TABLE_WISHLIST . " where products_id = '" . tep_db_input(tep_db_prepare_input($HTTP_GET_VARS['products_id'])) . "' and customers_id = '" . tep_db_input($customer_id) . "'");
                                  tep_db_query("insert into " . TABLE_WISHLIST . " (customers_id, products_id, products_model, products_name, products_price) values ('" . tep_db_input($customer_id) . "', '" . tep_db_input($products_id) . "', '" . $products_model . "', '" . $products_name . "', '" . $products_price . "' )");
                                }
                              }
                              tep_redirect(tep_href_link(FILENAME_WISHLIST));
                              break;


      case 'wishlist_add_cart': reset ($lvnr);
                                reset ($lvanz);
                                  while (list($key,$elem) =each ($lvnr))
                                        {
                                        (list($key1,$elem1) =each ($lvanz));
                                        tep_db_query("update " . TABLE_WISHLIST . " set products_quantity = '" . $elem1 . "' where customers_id = '" . $customer_id . "' and products_id = '" . $elem . "'");
                                        tep_db_query("delete from " . TABLE_WISHLIST . " where customers_id= '" . $customer_id . "' and products_quantity = '999'");
                                        $produkte_mit_anzahl=tep_db_query("select * from " . TABLE_WISHLIST . " where customers_id = '" . $customer_id . "' and products_id = '" . $elem . "' and products_quantity<>'0'");

                                  while ($HTTP_GET_VARS=mysql_fetch_array($produkte_mit_anzahl))
                                  {
                                  $cart->add_cart(tep_db_prepare_input($HTTP_POST_VARS['products_id']), tep_db_prepare_input($HTTP_POST_VARS['products_quantity']));
                                  }
                                          }
                                reset ($lvanz);
                              tep_redirect(tep_href_link(FILENAME_WISHLIST));
                              break;


// remove item from the wishlist
      case 'remove_wishlist':
                              tep_db_query("delete from " . TABLE_WISHLIST . " where products_id = '" . tep_db_input(tep_db_prepare_input($HTTP_GET_VARS['pid'])) . "' and customers_id = '" . tep_db_input($customer_id) . "'");
                              tep_redirect(tep_href_link(FILENAME_WISHLIST));
                              break;
				
				
				
      // performed by the 'buy now' button in product listings and review page
      case 'buy_now' :        
	  				if (isset($HTTP_GET_VARS['products_id']) && is_numeric($HTTP_GET_VARS['products_id'])) {
                        if (tep_has_product_attributes($HTTP_GET_VARS['products_id'])) {
                           tep_redirect(tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . tep_db_prepare_input($HTTP_GET_VARS['products_id'])));
                        } else {
                            $cart->add_cart(tep_db_prepare_input($HTTP_GET_VARS['products_id']), $cart->get_quantity(tep_db_prepare_input($HTTP_GET_VARS['products_id']))+1);
                        }
					}
                    tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                    break;
      case 'notify' :         if (tep_session_is_registered('customer_id')) {
                                if (isset($HTTP_GET_VARS['products_id'])) {
                                  $notify = tep_db_prepare_input($HTTP_GET_VARS['products_id']);
                                } elseif (isset($HTTP_GET_VARS['notify'])) {
                                  $notify = tep_db_prepare_input($HTTP_GET_VARS['notify']);
                                } elseif (isset($HTTP_POST_VARS['notify'])) {
                                  $notify = tep_db_prepare_input($HTTP_POST_VARS['notify']);
                                } else {
                                  tep_redirect(tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action', 'notify'))));
                                }
                                if (!is_array($notify)) $notify = array($notify);
                                for ($i=0, $n=sizeof($notify); $i<$n; $i++) {
                                  $check_query = tep_db_query("select count(*) as count from " . TABLE_PRODUCTS_NOTIFICATIONS . " where products_id = '" . tep_db_input($notify[$i]) . "' and customers_id = '" . tep_db_input($customer_id) . "'");
                                  $check = tep_db_fetch_array($check_query);
                                  if ($check['count'] < 1 && isset($HTTP_GET_VARS['products_id'])) {
                                    tep_db_query("insert into " . TABLE_PRODUCTS_NOTIFICATIONS . " (products_id, customers_id, date_added) values ('" . tep_db_input($notify[$i]) . "', '" . tep_db_input($customer_id) . "', now())");
                                  }
                                }
                                tep_redirect(tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action', 'notify'))));
                              } else {
                                $navigation->set_snapshot();
                                tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
                              }
                              break;
      case 'notify_remove' :  if (tep_session_is_registered('customer_id') && isset($HTTP_GET_VARS['products_id'])) {
                                $check_query = tep_db_query("select count(*) as count from " . TABLE_PRODUCTS_NOTIFICATIONS . " where products_id = '" . tep_db_input(tep_db_prepare_input($HTTP_GET_VARS['products_id'])) . "' and customers_id = '" . tep_db_input($customer_id) . "'");
                                $check = tep_db_fetch_array($check_query);
                                if ($check['count'] > 0) {
                                  tep_db_query("delete from " . TABLE_PRODUCTS_NOTIFICATIONS . " where products_id = '" . tep_db_input(tep_db_prepare_input($HTTP_GET_VARS['products_id'])) . "' and customers_id = '" . tep_db_input($customer_id) . "'");
                                }
                                tep_redirect(tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action'))));
                              } else {
                                $navigation->set_snapshot();
                                tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
                              }
                              break;
      case 'cust_order' :     if (tep_session_is_registered('customer_id') && isset($HTTP_GET_VARS['pid'])) {
                                if (tep_has_product_attributes($HTTP_GET_VARS['pid'])) {
                                  tep_redirect(tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $HTTP_GET_VARS['pid']));
                                } else {
                                  $cart->add_cart($HTTP_GET_VARS['pid'], $cart->get_quantity($HTTP_GET_VARS['pid'])+1);
                                }
                              }
                              tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                              break;
    }
  }

// include the who's online functions
  require(DIR_WS_FUNCTIONS . 'whos_online.php');
  tep_update_whos_online();

// include the password crypto functions
  require(DIR_WS_FUNCTIONS . 'password_funcs.php');
// include validation functions (right now only email address)
  require(DIR_WS_FUNCTIONS . 'validations.php');

// split-page-results
  require(DIR_WS_CLASSES . 'split_page_results.php');

// Lango added for template BOF:
  require(DIR_WS_INCLUDES . 'template_application_top.php');
// Lango added for template EOF:
  if (!defined('TEMPLATENAME_MAIN_PAGE')) define('TEMPLATENAME_MAIN_PAGE',TEMPLATENAME_MAIN_PAGE_DEFAULT);

// auto activate and expire banners
  require(DIR_WS_FUNCTIONS . 'banner.php');
  tep_activate_banners();
  tep_expire_banners();

// auto expire special products
  require(DIR_WS_FUNCTIONS . 'specials.php');
  tep_expire_specials();

// auto expire featured products
  require(DIR_WS_FUNCTIONS . 'featured.php');
  tep_expire_featured();

// calculate category path
  if (isset($HTTP_GET_VARS['cPath'])) { 
    $cPath = tep_db_prepare_input($HTTP_GET_VARS['cPath']);
  } elseif ((int)isset($HTTP_GET_VARS['products_id']) && !isset($HTTP_GET_VARS['manufacturers_id'])) {
    $cPath = (int)tep_get_product_path($HTTP_GET_VARS['products_id']);
  } else {
    $cPath = '';
  }

  if (tep_not_null($cPath)) {
    $cPath_array = tep_parse_category_path($cPath);
    $cPath = implode('_', $cPath_array);
    $current_category_id = $cPath_array[(sizeof($cPath_array)-1)];
  } else {
    $current_category_id = 0;
  }
   if (tep_not_null($cPath)){
     tep_set_session_value('prev_category_viewed','cPath='.$cPath);
  }

  

// include the breadcrumb class and start the breadcrumb trail
  require(DIR_WS_CLASSES . 'breadcrumb.php');
  $breadcrumb = new breadcrumb;

  if (tep_session_is_registered('customer_id') && defined("HTTP_HOME_URL") && ENABLE_WEB_SERVICE){
	$breadcrumb->add(HEADER_TITLE_TOP, (defined("HTTP_HOME_URL")?HTTP_HOME_URL:HTTP_SERVER) . "?user_id=" . $customer_id . "&session_key=" . tep_session_id() . "&type=1981");
} else {
	$breadcrumb->add(HEADER_TITLE_TOP, (defined("HTTP_HOME_URL")?HTTP_HOME_URL:HTTP_SERVER));
}

  $breadcrumb->add(HEADER_TITLE_CATALOG, tep_href_link(FILENAME_DEFAULT));

// add category names or the manufacturer name to the breadcrumb trail
  if (isset($cPath_array)) {
    for ($i=0, $n=sizeof($cPath_array); $i<$n; $i++) {
      $categories_query = tep_db_query("select categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_id = '" . (int)$cPath_array[$i] . "' and language_id = '" . (int)$languages_id . "'");
      if (tep_db_num_rows($categories_query) > 0) {
        $categories = tep_db_fetch_array($categories_query);
        $breadcrumb->add($categories['categories_name'], tep_href_link(FILENAME_DEFAULT, 'cPath=' . implode('_', array_slice($cPath_array, 0, ($i+1)))));
      } else {
        break;
      }
    }
  } elseif (isset($HTTP_GET_VARS['manufacturers_id'])) {
    $manufacturers_query = tep_db_query("select manufacturers_name from " . TABLE_MANUFACTURERS . " where manufacturers_id = '" . (int)$HTTP_GET_VARS['manufacturers_id'] . "'");
    if (tep_db_num_rows($manufacturers_query)) {
      $manufacturers = tep_db_fetch_array($manufacturers_query);
      $breadcrumb->add($manufacturers['manufacturers_name'], tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . tep_db_prepare_input($HTTP_GET_VARS['manufacturers_id'])));
    }
  }
// add the products model to the breadcrumb trail
  if (isset($HTTP_GET_VARS['products_id'])) {
    $model_query = tep_db_query("select p.products_model, pd.products_name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "' and p.products_id=pd.products_id and pd.language_id='" . (int)$languages_id . "' ");
    if (tep_db_num_rows($model_query)) {
      $model = tep_db_fetch_array($model_query);
		if($model['products_model']!="")
			$product_name=$model['products_model'];
		else
			$product_name=$model['products_name'];	
      $breadcrumb->add($product_name, tep_href_link(FILENAME_PRODUCT_INFO, 'cPath=' . $cPath . '&products_id=' . (int)$HTTP_GET_VARS['products_id']));
    }
  }

// initialize the message stack for output messages
  require(DIR_WS_CLASSES . 'message_stack.php');
  $messageStack = new messageStack;
//  if($currency_count<=0)
//	  $messageStack->add('header', sprintf(WARNING_CURRENCY,$currency), 'warning');

  if ($GLOBALS["SEO_URL"]->lastError!='')
	  $messageStack->add('header', $GLOBALS["SEO_URL"]->lastError, 'error');


// error handler function
 //joomla1.0
   if(isset($HTTP_GET_VARS['user_hash_id']) && $HTTP_GET_VARS['user_hash_id']!="" && isset($HTTP_GET_VARS['email']) && $HTTP_GET_VARS['email']!=""){
  		$user_hash_id=tep_db_prepare_input($HTTP_GET_VARS['user_hash_id']);
  		$mod_freeway_name_hash=md5('freeway_name'.$user_hash_id);
		$mod_freeway_username_hash=md5('freeway_username'.$user_hash_id);
		$mod_freeway_email_hash=md5('freeway_email'.$user_hash_id);
   	 	if(!strpos($HTTP_GET_VARS['name'],$mod_freeway_name_hash) || !strpos($HTTP_GET_VARS['username'],$mod_freeway_username_hash) || !strpos($HTTP_GET_VARS['email'],$mod_freeway_email_hash)) tep_redirect(tep_href_link('index.php'));
		else {
			$firsname=base64_decode(str_replace($mod_freeway_name_hash,"",$HTTP_GET_VARS['name']));
			$username=base64_decode(str_replace($mod_freeway_username_hash,"",$HTTP_GET_VARS['username']));
			$emailaddress=base64_decode(str_replace($mod_freeway_email_hash,"",$emailaddress));
		}
  		$check_user=tep_db_query("select customers_username,customers_id,customers_default_address_id,customers_firstname from ".TABLE_CUSTOMERS." where customers_username='".tep_db_input($username)."'");
  		$customer_found=false;
  		if(tep_db_num_rows($check_user)>0)
  			$customer_found=true;
  		else {
  			$new_password = tep_create_random_value(ENTRY_PASSWORD_MIN_LENGTH);
      		//create new password
      		  	$password = '';
      		  	$type=ENCRYPTION_STYLE;
			    for ($i=0; $i<10; $i++)  $password .= tep_rand();
			    $salt = substr(md5($password), 0, 2);
				if ($type=="V")
				    $password = md5(md5($new_password) . $salt) . ':' . $salt;
				else
					$password = md5($salt . $new_password) . ':' . $salt;
				$crypted_password=tep_db_input($password);
      		//create new password
  			$insert_new_customer=array('customers_gender'=>'m','customers_firstname'=>$name,'customers_lastname'=>$name,'customers_username'=>$username,'customers_email_address'=>$email_address,'customers_password'=>$crypted_password);
  			tep_db_perform(TABLE_CUSTOMERS,$insert_new_customer);
  			$c_id=tep_db_insert_id();
  			if($c_id>0){
  				$insert_customer_address_book=array('customers_id'=>$c_id,'entry_gender'=>'m','entry_firstname'=>$name,'entry_lastname'=>$name,'entry_postcode'=>'4895','entry_city'=>DEFAULT_CITY,'entry_state'=>tep_get_zone_name(STORE_COUNTRY,STORE_ZONE,STORE_ZONE),'entry_country_id'=>STORE_COUNTRY);
  				tep_db_perform(TABLE_ADDRESS_BOOK,$insert_customer_address_book);
  				$a_id=tep_db_insert_id();
  				tep_db_query("update ".TABLE_CUSTOMERS." set customers_default_address_id='".$a_id."' where customers_id='".$c_id."'");	
  			}
  			$customer_found=true;
  		}
  		if($customer_found && $customer_id==0){
  			$check_customer=tep_db_fetch_array($check_user);
  			$check_country_query = tep_db_query("select entry_country_id, entry_zone_id from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$check_customer['customers_id'] . "' and address_book_id = '" . (int)$check_customer['customers_default_address_id'] . "'");
	        $check_country = tep_db_fetch_array($check_country_query);		    
	        $customer_id = $check_customer['customers_id'];
	        $customer_default_address_id = $check_customer['customers_default_address_id'];
	        $customer_first_name = $check_customer['customers_firstname'];
	        $customer_country_id = $check_country['entry_country_id'];
	        $customer_zone_id = $check_country['entry_zone_id'];	        
        	tep_session_register('customer_id');
        	tep_session_register('customer_default_address_id');
        	tep_session_register('customer_first_name');
        	tep_session_register('customer_country_id');
        	tep_session_register('customer_zone_id');
        	$merge_details[TEXT_SM]=STORE_NAME;
			$merge_details[TEXT_SN]=STORE_OWNER;
		    $merge_details[TEXT_SE]=STORE_OWNER_EMAIL_ADDRESS;
		    $merge_details[TEXT_LE]=$email_address;
		    $merge_details[TEXT_LP]=$new_password;		    
		    $send_details[0]['to_name'] = $name;
	        $send_details[0]['to_email'] = $email_address;
	        $send_details[0]['from_name']=STORE_OWNER;
	        $send_details[0]['from_email']=STORE_OWNER_EMAIL_ADDRESS;
            if($new_password) tep_send_default_email("CUS",$merge_details,$send_details);
            $cart->restore_contents();
  		}
   }
   if(isset($HTTP_GET_VARS['user_hash_id'])) tep_redirect(tep_href_link('index.php'));
 //joomla1.0
	  
// set which precautions should be checked
  define('WARN_INSTALL_EXISTENCE', 'true');
  define('WARN_CONFIG_WRITEABLE', 'true');
  define('WARN_SESSION_DIRECTORY_NOT_WRITEABLE', 'true');
  define('WARN_SESSION_AUTO_START', 'true');
  define('WARN_DOWNLOAD_DIRECTORY_NOT_READABLE', 'true');
  define('WARN_IMAGES_DIRECTORY_NOT_WRITEABLE','true');
  define('WARN_IMAGES_BIG_DIRECTORY_NOT_WRITEABLE','true');
  define('WARN_IMAGES_SMALL_DIRECTORY_NOT_WRITEABLE','true');
  define('WARN_LOG_DIRECTORY_NOT_WRITABLE','true');
// Include OSC-AFFILIATE
  require(DIR_WS_INCLUDES .'affiliate_application_top.php');
  require(DIR_WS_INCLUDES .'add_ccgvdc_application_top.php');
  include(DIR_WS_INCLUDES .'application_top_newsdesk.php');
  include(DIR_WS_INCLUDES .'application_top_faqdesk.php');
  include(DIR_WS_INCLUDES .'languages/add_ccgvdc_english.php');
  require(DIR_WS_INCLUDES . "events_application_top.php");
  require(DIR_WS_INCLUDES . "services_application_top.php");
  
  if (file_exists(DIR_WS_INCLUDES .'contractor_application_top.php')) require(DIR_WS_INCLUDES .'contractor_application_top.php');
 } //joomla
 
	function json_string(&$array){
		global $js_string;
		$js_string.="{";
		$first=true;
		while(list($key,)=each($array)){
			if (!$first) {
				$js_string.=",\n";
			}
			$js_string.="'" . $key . "':";
			$first=false;
			if (is_array($array[$key])){
				if (count($array[$key])>0)
					json_string($array[$key]);
				else
					$js_string.="{}";
			} else{
				$js_string.=dispvalue($array[$key]);
			}
		}
		$js_string.="}";
	}
 header('Content-Type: text/html; charset=utf-8');
 
 if(SINGLE_PAGE_CHECKOUT=='True'){
 	$base_file = basename($PHP_SELF);
 	if($base_file==FILENAME_CHECKOUT_SHIPPING || $base_file==FILENAME_CHECKOUT_PAYMENT || $base_file==FILENAME_CHECKOUT_CONFIRMATION)
		tep_redirect(tep_href_link(FILENAME_CHECKOUT_SINGLE,'','SSL'));
 	} elseif(SINGLE_PAGE_CHECKOUT=='False'){
 	$base_file = basename($PHP_SELF);
 	if($base_file==FILENAME_CHECKOUT_SINGLE)
		tep_redirect(tep_href_link(FILENAME_CHECKOUT_SHIPPING,'','SSL'));
 }
 
   function tep_strip_input($data){
		global $INPUT_FILTER;
		if (is_array($data) && count($data)>0) {
			reset($data);
			while(list($key,)=each($data)){
				$data[$key]=$INPUT_FILTER->_cleanTags($data[$key]);
			}
			return $data;
		} else {
			return $INPUT_FILTER->_cleanTags($data);
		}
	}	
   
?>