<?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  12/02/11, 15:02
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
 *\file application_top.php
 *
*/

/**
 compatibilité mode diminue le nbr d'appel de constante, et ammeliore les performance.
 NOTE: Ce mode peut provoquer des erreurs php si vous utiliser des modules et element non finaliser pour cette version d'oscss-Rv
*/
define('OSCSS_RV_COMPATIBILITY', true);
/// start the timer for the page parse time log
define('PAGE_PARSE_START_TIME', microtime());

//!This displays executed queries in error message NOT recommanded in a production environment!

  /**
   * \brief as active / inactive cache and error return
   * @var boolean
   */
  define('OSCSS_DEBUG', true);
  /**
   * \brief as active view query in error requet sql
   * @var boolean
   */
  define('OSCSS_SHOW_QUERIES', true);
  /**
   * \brief as active / incative garbage collector error
   * @var boolean
   */
  define('OSCSS_GARBAGE_ERROR', false);

// define('MODULE_ORDER_TOTAL_DISCOUNT_COUPON_DEBUG', true);

/// Set the local configuration parameters - mainly for developers
  if (file_exists('includes/local/configure.php'))  include('includes/local/configure.php');
  elseif (!file_exists('includes/configure.php')) {
    if (is_dir('install'))  header('Location: install/index.php');
    else die(_('file configure.php is not found ! '));
  }else require('includes/configure.php');


if (OSCSS_DEBUG == true) {
  $oscss_debug_infos = array();
  error_reporting(-1);
} else {
/// set the level of error reporting
  ini_set("error_reporting",E_ALL & ~E_NOTICE);
  ini_set("display_errors","1");
  ini_set("log_errors", "0" );
  error_reporting(0);
}
error_reporting(E_ALL);
/// attribut produits ameliorer
  define('UPLOAD_PREFIX', 'upload_');
  define('TEXT_PREFIX', 'txt_');
  define('PRODUCTS_OPTIONS_VALUE_TEXT_ID', '0');

/** Alert register_globals if enabled */
  if ((int)ini_get('register_globals') > 0)  die('GLOBALS overwrite attempt detected');

/// set the type of request (secure or not)
  $request_type = (getenv('HTTPS') == 'on') ? 'SSL' : 'NONSSL';

/// set php_self in the local scope
  $PHP_SELF = $_SERVER['PHP_SELF'];

  define('DIR_WS_CATALOG', (($request_type == 'NONSSL') ? DIR_WS_HTTP_CATALOG : DIR_WS_HTTPS_CATALOG ));

/// include the list of project database tables
  include(DIR_WS_INCLUDES . 'inc_base_conf.php');
/// include  list of project class and lib permanente
  include(DIR_WS_INCLUDES . 'inc_base_lib_min.php');

  require_once(DIR_WS_CLASSES . 'page.php');

  //! gestionnaire d'erreur
  if(OSCSS_GARBAGE_ERROR == true){
	  require_once(DIR_WS_CLASSES . 'osC_ErrorHandler.php');
	  $errorHandler = osC_ErrorHandler::start();
	  if(OSCSS_DEBUG==true) $errorHandler->attach($mock=new MockWriter());
  }

/// make a connection to the database... now
  $DB=Database::getInstance();

//! element optionnel
//   if (file_exists(DIR_WS_INCLUDES . 'tables_files_modules.php')) require(DIR_WS_INCLUDES . 'tables_files_modules.php');

/// set the application parameters
  $res=$DB->query("SELECT configuration_key AS cfgKey, configuration_value AS cfgValue FROM " . TABLE_CONFIGURATION ." where configuration_type IN (2,3) ");

  while($configuration = $res->fetchAssoc()){
    if ((OSCSS_RV_COMPATIBILITY ==true) && strtoupper($configuration['cfgValue']) !='FALSE') define(strtoupper($configuration['cfgKey']), $configuration['cfgValue']);
    elseif (OSCSS_RV_COMPATIBILITY ==false) define(strtoupper($configuration['cfgKey']), $configuration['cfgValue']);
  }

/// include  list of project class and lib permanente
  include(DIR_WS_INCLUDES . 'inc_base_lib.php');

   if(OSCSS_GARBAGE_ERROR == true){
    if (_cst_bool('STORE_PAGE_PARSE_STOCK_ERROR')) $errorHandler->attachFileWriter('sessions/err-php.log');
    if (_cst_bool('STORE_PAGE_PARSE_EMAIL_OWNER')) $errorHandler->attachMailWriter(STORE_OWNER_EMAIL_ADDRESS);
   }

/// define the project version
  define('PROJECT_VERSION', get_info_core(DIR_WS_COMMON.'oscss.version.xml','version').' - svn '.get_info_core(DIR_WS_COMMON.'oscss.version.xml','svn'));


/// if gzip_compression is enabled, start to buffer the output
  if ( (defined('GZIP_COMPRESSION') && GZIP_COMPRESSION == 'true') && ($ext_zlib_loaded = extension_loaded('zlib'))  ) {
    if (($ini_zlib_output_compression = (int)ini_get('zlib.output_compression')) > 1) {
      ini_set('zlib.output_compression_level', GZIP_LEVEL);
    }
  }

//! control get
  if(isset($_GET))
    foreach($_GET as $k=>$v) $_GET[$k]=tep_sanitize_string($v);

/// Constructeur de page
  require_once(DIR_WS_CLASSES . 'page.php');
  $page= page::getInstance();
  $page->add_var_page('request_type',$request_type);

/// include osc Price
  $osC_Tax=$price=$currencies = new price();
  $page->add_object('price', $price);
  /// reto-compatibilité
  $page->add_object('currencies', $currencies);
  $page->add_object('osC_Tax', $osC_Tax);

/// 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
  $osCSS_Cache = new osCSS_Cache;
  $page->add_object('osCSS_Cache',$osCSS_Cache);

/// include navigation history class
  $navigation=navigation_history::getInstance();
  $page->add_object('navigation_history',$navigation);

/// récupére la MASTER VALUE de 'session.save_path'
  define('PHP_SESSION_SAVE_PATH_MASTER', ini_get('session.save_path'));

/// set the session name and save path
  tep_session_name('osCsid');
  tep_session_save_path();

/// active le garbage collector de PHP si nécessaire
  if (tep_session_save_path() != PHP_SESSION_SAVE_PATH_MASTER){
    ini_set('session.gc_maxlifetime', SESSION_LIFE_PUBLIC*60);
    ini_set('session.gc_probability', '1');
    ini_set('session.gc_divisor', '100');
  }

/// 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($_POST[tep_session_name()])) {
     tep_session_id($_POST[tep_session_name()]);
   } elseif ( ($request_type == 'SSL') && isset($_GET[tep_session_name()]) ) {
     tep_session_id($_GET[tep_session_name()]);
   }

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

    if (isset($_COOKIE['cookie_test'])) {
      tep_session_start();
      $session_started = true;
    }
  } elseif (_cst_bool('SESSION_BLOCK_SPIDERS')) {
    $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;
  }

//! Mise en offligne
  if (_cst_bool('STORE_OFFLINE')) {
//     if (!$session_started) {
	if (!isset($_GET['admin'])) {
	  echo TXT_OFFLINE_MESSAGE;
	  exit;
	}
	else {
	  tep_session_register('aauth');
	  $aauth = 'yes';
	}
//     }
  }

/// set SID once, even if empty
  $SID = (defined('SID') ? SID : '');

/// verify the ssl_session_id if the feature is enabled
  if ( ($request_type == 'SSL') && (_cst_bool('SESSION_CHECK_SSL_SESSION_ID ')) && (_cst_bool('ENABLE_SSL')) && ($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 (_cst_bool('SESSION_CHECK_USER_AGENT')) {
    $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 (_cst_bool('SESSION_CHECK_IP_ADDRESS')) {
    $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));
    }
  }

/// create the shopping cart & fix the cart if necesary
  if (!tep_session_is_registered('cart') ||  !isset($cart) || !is_object($cart) ) {
    $cart = new shoppingCart;
    tep_session_register('cart');
  }
  $page->add_object('cart', $cart);


/// set the language
  if (!tep_session_is_registered('language') || isset($_GET['language'])) {
    if (!tep_session_is_registered('language')) {
      tep_session_register('language');
      tep_session_register('languages_id');
    }

    $lng = new language();

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

    $language = $lng->language['directory'];
    $languages_id = $lng->language['id'];
  }
  $page->add_var_page('language',$language);
  $page->add_var_page('languages_id',$languages_id);

/// include the language translations
  if(($path=$page->fix_file(DIR_WS_LANGUAGES . $language.'.php' ,true, true)) !=false) include($path);
  elseif(($path=$page->fix_file(DIR_WS_LANGUAGES . 'fr_FR.php' ,true, true)) !=false) include($path);

//! init cache lang (.txt)
  $page->cache_lang();

/// Ultimate SEO URLs v2.1
  if (_cst_bool('SEO_ENABLED'))  $seo_urls = seo_url::getInstance($languages_id);

/// currency
  if (!tep_session_is_registered('currency') || isset($_GET['currency']) ||  (_cst_bool('USE_DEFAULT_LANGUAGE_CURRENCY')) && (LANGUAGE_CURRENCY != $currency) ) {
    if (!tep_session_is_registered('currency')) tep_session_register('currency');

    if (isset($_GET['currency'])) {
      if (!$currency = tep_currency_exists($_GET['currency'])) $currency = (_cst_bool('USE_DEFAULT_LANGUAGE_CURRENCY')) ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;
    } else {
      $currency = (_cst_bool('USE_DEFAULT_LANGUAGE_CURRENCY')) ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;
    }
  }
  $page->add_var_page('currency',$currency);

/// navigation history
  if (!tep_session_is_registered('navigation')) {
     tep_session_register('navigation');
     $navigation = $page->return_object('navigation_history');
  }
  $page->navigation_history->add_current_page();

/// Shopping cart actions
  if (isset($_GET['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));
    $shop_action=new shopping_cart_action();
    $shop_action->init($_GET['action']);
  }

//! Recup element user et groups
  if (tep_session_is_registered('customer_id')) {
    $page->add_var_page('customer_id',$customer_id);
    $account=$page->new_class('customer',$customer_id);
  }
  else $account=$page->new_class('customer','');
// $account=$page->_call('customer','the_customer');


/// include the who's online functions
if (_cst_bool('WHOS_ONLINE_ACTIVE') || (  (tep_cst_define('WHOS_ONLINE_ACTIVE') =='auto') && _cst_bool('WHOS_ONLINE_FLAG')) ){
  require(DIR_WS_FUNCTIONS . 'whos_online.php');
  tep_update_whos_online();
}

/* MARK FOR CIP -- DOES NOT TOUCH */


/// calculate category path
  if (isset($_GET['cPath'])) $cPath = $_GET['cPath'];
  elseif (isset($_GET['products_id']) && !isset($_GET['manufacturers_id'])) $cPath = product::get_product_path($_GET['products_id']);
  elseif (isset($_GET['content']) && is_numeric($_GET['content'])) $cPath = content::get_content_path($_GET['content']);
  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;
  }

  $page->add_var_page('current_category_id',$current_category_id);
  $page->add_var_page('cPath',$cPath);
  $page->add_var_page('cPath_array',@$cPath_array);
  /// include start the breadcrumb trail
  $breadcrumb=$page->new_class('breadcrumb');

  $page->pre_init();

  /// initialize the message stack for output messages
  $messageStack = $page->new_class('messageStack');
  /// set the template
  $template = $page->ret_template();


/// add category names to the breadcrumb trail
  if (isset($cPath_array)) {
    for ($i=0, $n=sizeof($cPath_array); $i<$n; $i++) {
      if( ($categories=categorie::get_item((int)$cPath_array[$i])) !=false)  $page->breadcrumb->add($categories->categories_name, tep_href_link(FILENAME_DEFAULT, 'cPath=' . implode('_', array_slice($cPath_array, 0, ($i+1)))));
      else break;
    }
  }

?>