<?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  29/01/11, 14:26
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
 *\file general.php
*/


/**
 *\fn tep_exit()
 *\brief  Stop from parsing any further PHP code
 *\return rien
*/
function tep_exit() {
  tep_session_close();
  exit();
}

/**
 *\fn tep_redirect($url)
 *\brief Redirect to another page or site
*/
function tep_redirect($url) {
  if ( (strstr($url, "\n") != false) || (strstr($url, "\r") != false) )  tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false));

  if ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) { // We are loading an SSL page
    if (substr($url, 0, strlen(HTTP_SERVER)) == HTTP_SERVER) { // NONSSL url
      $url = HTTPS_SERVER . substr($url, strlen(HTTP_SERVER)); // Change it to SSL
    }
  }

  header('Location: ' . str_replace('&amp;','&',$url));
  tep_exit();
}

/**
  @fn tep_get_http()
  @brief retrun url server
*/
function tep_get_http(){
  return  ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) ? HTTPS_SERVER : HTTP_SERVER;
}

/**
  @fn tep_get_httpdir()
  @brief return http and base dir server
*/
function tep_get_httpdir(){
  return  ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) ? HTTPS_SERVER.DIR_WS_HTTPS_CATALOG : HTTP_SERVER.DIR_WS_HTTP_CATALOG;
}


/**
 *\fn tep_parse_input_field_data($data, $parse)
 *\brief Parse the data used in the html tags to ensure the tags will not break
 * */
function tep_parse_input_field_data($data, $parse) { return strtr(trim($data), $parse); }

function tep_output_string($string, $translate = false, $protected = false) {
  if ($protected == true) return htmlspecialchars($string);
  else {
    if ($translate == false)  return tep_parse_input_field_data($string, array('"' => '&quot;'));
    else  return tep_parse_input_field_data($string, $translate);
  }
}

function tep_output_string_protected($string) { return tep_output_string($string, false, true); }

/**
 *\fn tep_sanitize_string($string)
 *\brief  nettoyage de chaîne de caratères (sécu)
  \param string la chaîne à nettoyer
*/
function tep_sanitize_string($string) {
  $string = preg_replace('/ +/', ' ', trim($string));
  return preg_replace("/[<>]/", '_', $string);
}

/**
 *\fn tep_random_select($query)
 *\brief Return a random row from a database query
  \return one result
*/
function tep_random_select($query) {
  $DB=Database::getInstance();
  $random_product = '';
  $random_query = $DB->query($query);
  $num_rows = $random_query->__get('numRows');
  if ($num_rows > 0) {
    $random_row = tep_rand(0, ($num_rows - 1));
    $random=$random_query->fetchAllAssoc();
    return $random[$random_row];
  }
  else return array();
}


/**
 *\fn  tep_browser_detect($component)
 *\brief Returns the clients browser
 */
function tep_browser_detect($component) { return stristr($_SERVER['HTTP_USER_AGENT'], $component); }

/**
 *\fn tep_break_string($string, $len, $break_char = '-')
 *\brief Break a word in a string if it is longer than a specified length ($len)
*/
function tep_break_string($string, $len, $break_char = '-') {
  $l = 0;
  $output = '';
  for ($i=0, $n=strlen($string); $i<$n; $i++) {
    $char = substr($string, $i, 1);
    if ($char != ' ')  $l++;
      else  $l = 0;

    if ($l > $len) {
      $l = 1;
      $output .= $break_char;
    }
    $output .= $char;
  }

  return $output;
}

/**
 *\fn tep_get_all_get_params($exclude_array = '')
 *\brief  Return all HTTP GET variables, except those passed as a parameter
*/
function tep_get_all_get_params($exclude_array = '') {
  global $_GET;

  if (!is_array($exclude_array)) $exclude_array = array();

  $get_url = '';
  if (is_array($_GET) && (sizeof($_GET) > 0)) {
    reset($_GET);
    while (list($key, $value) = each($_GET))
      if ( (strlen($value) > 0) && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') )
	$get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
  }
  return str_replace('&', '&amp;', $get_url);
}

/**
 *\fn tep_round($number, $precision)
 *\brief  Wrapper function for round()
 */
function tep_round($number, $precision) {
  if (strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision)) {
    $number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);

    if (substr($number, -1) >= 5) {
      if ($precision > 1)  $number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
      elseif ($precision == 1)  $number = substr($number, 0, -1) + 0.1;
      else  $number = substr($number, 0, -1) + 1;
    } else {
      $number = substr($number, 0, -1);
    }
  }

  return $number;
}

function tep_row_number_format($number) {
  if ( ($number < 10) && (substr($number, 0, 1) != '0') ) $number = '0' . $number;

  return $number;
}

/**
 *\fn tep_rand($min = null, $max = null)
 *\brief Return a random value
 */
  function tep_rand($min = null, $max = null) {
    static $seeded;

    if (!isset($seeded)) {
      mt_srand((double)microtime()*1000000);
      $seeded = true;
    }

    if (isset($min) && isset($max)) {
      if ($min >= $max) {
        return $min;
      } else {
        return mt_rand($min, $max);
      }
    } else {
      return mt_rand();
    }
  }

  function tep_array_to_string($array, $exclude = '', $equals = '=', $separator = '&amp;') {
    if (!is_array($exclude)) $exclude = array();

    $get_string = '';
    if (sizeof($array) > 0) {
      while (list($key, $value) = each($array)) {
        if ( (!in_array($key, $exclude)) && ($key != 'x') && ($key != 'y') ) {
          $get_string .= $key . $equals . $value . $separator;
        }
      }
      $remove_chars = strlen($separator);
      $get_string = substr($get_string, 0, -$remove_chars);
    }

    return $get_string;
  }

function tep_string_to_int($string) { return (int)$string; }

/**
 *\class arg()
 *\brief  Constructeur objet base array
*/
class objectInfo {
  function objectInfo($object_array) {
    reset($object_array);
    while (list($key, $value) = each($object_array)) {
      $this->$key = tep_db_prepare_input($value);
    }
  }
}

function arrayInfo($object) {
  $object_array=array();
  foreach($object as $key=>$value) {
    $object_array[$key] = $value;
  }
  return $object_array;
}


/**
 *\fn tep_word_count($string, $needle)
 *\brief  Get the number of times a word/character is present in a string
 */
function tep_word_count($string, $needle) { return sizeof(preg_split('/'.$needle.'/', $string)); }

  function tep_count_modules($modules = '') {
    $count = 0;

    if (empty($modules)) return $count;

    $modules_array = preg_split('/;/', $modules);

    for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
      $class = substr($modules_array[$i], 0, strrpos($modules_array[$i], '.'));

      if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
        if ($GLOBALS[$class]->enabled) {
          $count++;
        }
      }
    }

    return $count;
  }

  /**
   * \brief enresgitrement cookies
   * @param $name
   * @param $value
   * @param $expire
   * @param $path
   * @param $domain
   * @param $secure
   */
function tep_setcookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = 0) {
  setcookie($name, $value, $expire, $path, (tep_not_null($domain) ? $domain : ''), $secure);
}

  function tep_get_ip_address() {
    if (isset($_SERVER)) {
      if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
      } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
      } else {
        $ip = $_SERVER['REMOTE_ADDR'];
      }
    } else {
      if (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
      } elseif (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
      } else {
        $ip = getenv('REMOTE_ADDR');
      }
    }

    return $ip;
  }

/**  nl2br() prior PHP 4.2.0 did not convert linefeeds on all OSs (it only converted \n) */
function tep_convert_linefeeds($from, $to, $string) { return str_replace($from, $to, $string); }

/** Map global to GET variable */
function link_get_variable($var_name) { if (isset($_GET[$var_name])) { $GLOBALS[$var_name] =& $_GET[$var_name]; } }

/** Mapglobal to POST variable */
function link_post_variable($var_name) { if (isset($_POST[$var_name])) { $GLOBALS[$var_name] =& $_POST[$var_name]; } }


// Réécriture des dates dans des formats correctes pour la langue
function tep_strftime($format, $timestamp=false) {
  if (!$timestamp) $timestamp = time();
  $pattern = array(
		'%a'=>array('const'=>'NameOf_DAY_MINI','ftime'=>'%w'),
		'%A'=>array('const'=>'NameOf_DAY','ftime'=>'%w'),
		'%b'=>array('const'=>'NameOf_MONTH_MINI','ftime'=>'%m'),
		'%B'=>array('const'=>'NameOf_MONTH','ftime'=>'%m')
		);
  foreach ($pattern as $code=>$infos)
	if (preg_match('/'.$code.'/',$format) && defined($infos['const'].'_'.strftime($infos['ftime'], $timestamp)))
	$format = preg_replace('/'.$code.'/', constant($infos['const'].'_'.strftime($infos['ftime'], $timestamp)), $format);
  return strFtime($format, $timestamp);
}








/**
  Returns an array with countries
// TABLES: countries
*/
function tep_get_countries($countries_id = '', $with_iso_codes = false) {
  $DB=Database::getInstance();
  $countries_array = array();
  if (tep_not_null($countries_id)) {
    if ($with_iso_codes == true) {
      $countries = $DB->query("select countries_name, countries_iso_code_2, countries_iso_code_3 from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "' order by countries_name");
      $countries_values = $countries->fetchAssoc();
      $countries_array = array('countries_name' => $countries_values['countries_name'],
				'countries_iso_code_2' => $countries_values['countries_iso_code_2'],
				'countries_iso_code_3' => $countries_values['countries_iso_code_3']);
    } else {
      $countries = $DB->query("select countries_name from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "'");
      $countries_values = $countries->fetchAssoc();
      $countries_array = array('countries_name' => $countries_values['countries_name']);
    }
  } else {
      if (_cst_bool('COUNTRY_LOCALNAME')) {
	    $countries = $DB->query("select countries_id, countries_localname from " . TABLE_COUNTRIES . " where country_visible = '1' order by countries_localname");
	    while ($countries_values = $countries->fetchAssoc()) {
	    $countries_array[] = array('countries_id' => $countries_values['countries_id'],
				  'countries_name' => $countries_values['countries_localname']);
	    }
      } else {
	    $countries = $DB->query("select countries_id, countries_name from " . TABLE_COUNTRIES . " where country_visible = '1' order by countries_name");
	    while ($countries_values = $countries->fetchAssoc()) {
	    $countries_array[] = array('countries_id' => $countries_values['countries_id'],
				  'countries_name' => $countries_values['countries_name']);
	    }
      }
  }

  return $countries_array;
}


////
// Returns the zone (State/Province) name
// TABLES: zones
  function tep_get_zone_name($country_id, $zone_id, $default_zone) {
    $DB=Database::getInstance();
    $zone_query = $DB->query("select zone_name from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
    if ($zone_query->__get('numRows')) {
      $zone = $zone_query->fetchAssoc();
      return $zone['zone_name'];
    } else {
      return $default_zone;
    }
  }

////
// Returns the zone (State/Province) code
// TABLES: zones
  function tep_get_zone_code($country_id, $zone_id, $default_zone) {
    $DB=Database::getInstance();
    $zone_query = $DB->query("select zone_code from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
    if ($zone_query->__get('numRows')) {
      $zone = $zone_query->fetchAssoc();
      return $zone['zone_code'];
    } else {
      return $default_zone;
    }
  }



////
// Returns the address_format_id for the given country
// TABLES: countries;
  function tep_get_address_format_id($country_id) {
    $DB=Database::getInstance();
    $address_format_query = $DB->query("select address_format_id as format_id from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$country_id . "'");
    if ($address_format_query->__get('numRows')) {
      $address_format = $address_format_query->fetchAssoc();
      return $address_format['format_id'];
    } else {
      return '1';
    }
  }

////
// Return a formatted address
// TABLES: address_format
  function tep_address_format($address_format_id, $address, $html, $boln, $eoln) {
    $DB=Database::getInstance();
    $address_format_query = $DB->query("select address_format as format from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . (int)$address_format_id . "'");
    $address_format = $address_format_query->fetchAssoc();

    $company = tep_output_string_protected($address['company']);
    if (isset($address['firstname']) && tep_not_null($address['firstname'])) {
      $firstname = tep_output_string_protected($address['firstname']);
      $lastname = tep_output_string_protected($address['lastname']);
    } elseif (isset($address['name']) && tep_not_null($address['name'])) {
      $firstname = tep_output_string_protected($address['name']);
      $lastname = '';
    } else {
      $firstname = '';
      $lastname = '';
    }
    $street = tep_output_string_protected($address['street_address']);
    $suburb = tep_output_string_protected($address['suburb']);
    $city = tep_output_string_protected($address['city']);
    $state = tep_output_string_protected($address['state']);
    if (isset($address['country_id']) && tep_not_null($address['country_id'])) {
      $country = tep_get_country_name($address['country_id']);

      if (isset($address['zone_id']) && tep_not_null($address['zone_id'])) {
        $state = tep_get_zone_code($address['country_id'], $address['zone_id'], $state);
      }
    } elseif (isset($address['country']) && tep_not_null($address['country'])) {
      $country = tep_output_string_protected($address['country']);
    } else {
      $country = '';
    }
    $postcode = tep_output_string_protected($address['postcode']);
    $zip = $postcode;

    if ($html) {
// HTML Mode
      $HR = '<hr />';
      $hr = '<hr />';
      if ( ($boln == '') && ($eoln == "\n") ) { // Values not specified, use rational defaults
        $CR = '<br />';
        $cr = '<br />';
        $eoln = $cr;
      } else { // Use values supplied
        $CR = $eoln . $boln;
        $cr = $CR;
      }
    } else {
// Text Mode
      $CR = $eoln;
      $cr = $CR;
      $HR = '----------------------------------------';
      $hr = '----------------------------------------';
    }

    $statecomma = '';
    $streets = $street;
    if ($suburb != '') $streets = $street . $cr . $suburb;
//     if ($country == '') $country = tep_output_string_protected($address['country']);
    if ($state != '') $statecomma = $state . ', ';

    $fmt = $address_format['format'];
    eval("\$address = \"$fmt\";");

    if ( (_cst_bool('ACCOUNT_COMPANY')) && (tep_not_null($company)) ) {
      $address = $company . $cr . $address;
    }

    return $address;
  }





function tep_get_manufacturers($manufacturers_array = '') {
  $DB=Database::getInstance();
  if (!is_array($manufacturers_array)) $manufacturers_array = array();

  $manufacturers_query = $DB->query("select manufacturers_id, manufacturers_name from " . TABLE_MANUFACTURERS . " order by manufacturers_name");
  while ($manufacturers = $manufacturers_query->fetchAssoc()) {
    $manufacturers_array[] = array('id' => $manufacturers['manufacturers_id'], 'text' => $manufacturers['manufacturers_name']);
  }

  return $manufacturers_array;
}


// Output a raw date string in the selected locale date format
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
  function tep_date_long($raw_date) {
    if ( ($raw_date == '1000-01-01 00:00:00') || ($raw_date == '') ) return false;

    $year = (int)substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);

    return tep_strftime(DATE_FORMAT_LONG, mktime($hour,$minute,$second,$month,$day,$year));
  }

////
// Output a raw date string in the selected locale date format
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
// NOTE: Includes a workaround for dates before 01/01/1970 that fail on windows servers
  function tep_date_short($raw_date) {
    if ( ($raw_date == '1000-01-01 00:00:00') || empty($raw_date) ) return false;

    $year = substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);

    if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
      return date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
    } else {
      return str_replace('2037' , $year, date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, 2037)));
    }
  }

/**
 Return a product ID with attributes
*/
function tep_get_uprid($prid, $params) {
  $uprid = $prid;
  if ( (is_array($params)) && (!strstr($prid, '{')) ) {
    while (list($option, $value) = each($params)) {
      //CLR 030714 Add processing around $value. This is needed for text attributes.
      $uprid = $uprid . '{' . $option . '}' . htmlspecialchars(stripslashes(trim($value)), ENT_QUOTES);
    }
  } else {
    $uprid = htmlspecialchars(stripslashes($uprid), ENT_QUOTES);
  }

  if ( (is_array($params)) && (!strstr($prid, '{')) ) {
    while (list($option, $value) = each($params)) {
      $uprid = $uprid . '{' . $option . '}' . $value;
    }
  }

  return $uprid;
}
/**
  Return a product ID from a product ID with attributes
*/
function tep_get_prid($uprid) {
  $pieces = explode('{', $uprid);

  if (is_numeric($pieces[0]))  return $pieces[0];
  else  return false;
}
/**
  Converti un $uprid en array des attributs
*/
function tep_get_prid_array($uprid){
  $pieces = explode('{', $uprid);
  $attrib=array();
  for($i=1, $m=count($pieces); $i< $m ; $i++ ){
    $r=explode('}', $pieces[$i]);
    $attrib[$r[0]]=$r[1];
  }

  return $attrib;
}

////
// Return a customer greeting
  function tep_customer_greeting() {
    global $customer_id, $customer_first_name;

    if (tep_session_is_registered('customer_first_name') && tep_session_is_registered('customer_id')) {
      $greeting_string = sprintf(TEXT_GREETING_PERSONAL, tep_output_string_protected($customer_first_name), tep_href_link(FILENAME_PRODUCTS_NEW));
    } else {
      $greeting_string = sprintf(TEXT_GREETING_GUEST, tep_href_link(FILENAME_LOGIN, '', 'SSL'), tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'SSL'));
    }

    return $greeting_string;
  }






/** Count le nbr module installé */


function tep_create_random_value($length, $type = 'mixed') {
  if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;

  $rand_value = '';
  while (strlen($rand_value) < $length) {
    if ($type == 'digits') {
      $char = tep_rand(0,9);
    } else {
      $char = chr(tep_rand(0,255));
    }
    if ($type == 'mixed') {
      if (preg_match('/^[a-z0-9]$/i', $char)) $rand_value .= $char;
    } elseif ($type == 'chars') {
      if (preg_match('/^[a-z]$/i', $char)) $rand_value .= $char;
    } elseif ($type == 'digits') {
      if (preg_match('/^[0-9]$/', $char)) $rand_value .= $char;
    }
  }

  return $rand_value;
}


////
// Checks to see if the currency code exists as a currency
// TABLES: currencies
function tep_currency_exists($code) {
  $DB=Database::getInstance();
  $code = tep_db_prepare_input($code);

  $currency_code = $DB->query("select currencies_id from " . TABLE_CURRENCIES . " where code = '" . $DB->db_input($code) . "'");
  if ($currency_code->__get('numRows')) {
    return $code;
  } else {
    return false;
  }
}

////
// Parse and secure the cPath parameter values
function tep_parse_category_path($cPath) {
// make sure the category IDs are integers
  $cPath_array = array_map('tep_string_to_int', explode('_', $cPath));

// make sure no duplicate category IDs exist which could lock the server in a loop
  $tmp_array = array();
  $n = sizeof($cPath_array);
  for ($i=0; $i<$n; $i++) {
    if (!in_array($cPath_array[$i], $tmp_array)) {
      $tmp_array[] = $cPath_array[$i];
    }
  }

  return $tmp_array;
}


/**
  @author oscim - OscssTeam
    chargement du texte sous forme de constante ou via présent cms. cms prioritaire. si aucun des 2 renvoi commentaire élément absent
*/
function tep_draw_txt_block($text_main){
    if (($text=tep_get_cms_content ( strtolower($text_main))) !=false) echo $text;
    elseif(defined(strtoupper($text_main))) echo constant(strtoupper($text_main));
    else echo '<span class="info">'.sprintf(ALERT_CST_MAIN_ABS,$text_main ).'</span>';
}



/**
  @author featured produtc - oscommerce
*/
// function tep_array_values_to_string($array, $separator = ',') {
//     $get_string = '';
//     if (sizeof($array) > 0) {
//         while (list($key, $value) = each($array)) {
//             $get_string .= $value . $separator;
//         }
//         $remove_chars = strlen($separator);
//         $get_string = substr($get_string, 0, -$remove_chars);
//     }
//     return $get_string;
// }

/**
  @package oscss-RvBO
  @author oscim - OscssTeam
  @author featured produtc - oscommerce
  @version 1.0
  @note: appel des fonctions hors noyau, test présence avant appel
*/
function tep_call_function_mod($fct){
    $vars = '';
    if(func_num_args()>1) {
        for($i=1;$i<(func_num_args()-1);$i++){
            $t[$i] = func_get_arg($i);
            $vars.="\$t[$i],";
        }
        $t[$i] = func_get_arg($i);
        $vars.="\$t[$i]";
    }
    if (!function_exists($fct)) {
        print ('<span class="error">'.__('la fonction fait appel a un element modulaire non declaré ou inactif "'.$fct.'()"').'</span>');
        return false;
    }
    if($vars!='') {
        eval("\$ret = $fct($vars);");
        unset ($vars);unset ($t);
    }
    else eval("\$ret = $fct();");
    return $ret;
}

/**
  @package oscss-RvBO
  include validation functions (right now only email address)
*/
function tep_validate_email($email){
  require_once(DIR_WS_FUNCTIONS . 'validations.php');
  return tep_validate_email_inclus($email);
}

/**
  @package oscss-Rv
  @author OscssTeam
  @version 1.0
Clean out HTML comments code
*/
function clean_html_comments($clean_html) {
  global $its_cleaned;

  if ( strpos($clean_html,'<!--//*')>1 ) {
    $the_end1= strpos($clean_html,'<!--//*')-1;
    $the_start2= strpos($clean_html,'*//-->')+7;

    $its_cleaned= substr($clean_html,0,$the_end1);
    $its_cleaned.= substr($clean_html,$the_start2);
  }
  else  $its_cleaned= $clean_html;

  return $its_cleaned;
}

// BOF Customers extra fields
/**
  @package extra-fields
  @author package
  champs supplémentaire stocké ds db

  @note: boulon ds le Bo
*/
function tep_get_extra_fields($customer_id,$languages_id){
    $DB=Database::getInstance();
    $extra_fields_query = $DB->query("select ce.fields_id, ce.fields_input_type, ce.fields_input_value, ce.fields_required_status, cei.fields_name, ce.fields_status, ce.fields_input_type from " . TABLE_EXTRA_FIELDS . " ce, " . TABLE_EXTRA_FIELDS_INFO . " cei where ce.fields_admin = 0 and ce.fields_status=1 and cei.fields_id=ce.fields_id and cei.languages_id =" . $languages_id." order by ce.fields_group_class");
    $extra_fields_string ='';
    if($extra_fields_query->__get('numRows')>0){
      $extra_fields_string .= '<fieldset><legend>' . CATEGORY_EXTRA_FIELDS .'</legend>';

        while($extra_fields = $extra_fields_query->fetchAssoc()){
            $extra_fields_string .= '<p>';
            $value='';
            if(isset($customer_id)){
                $value_query = $DB->query("select value from " . TABLE_CUSTOMERS_TO_EXTRA_FIELDS . " where customers_id=" . $customer_id . " and fields_id=" . $extra_fields['fields_id']);
                $value_info = $value_query->fetchAssoc();
                $value_list = explode("\n", $value_info['value']);
                for($i = 0, $n = sizeof($value_list); $i < $n; $i++)
                {
                    $value_list[$i] = trim($value_list[$i]);
                }
                $value = $value_list[0];
            }
            $extra_fields_string .='<label for="fields_' . $extra_fields['fields_id'].'">' . $extra_fields['fields_name'] . ': </label>';


            $select_values_list = explode("\n", $extra_fields['fields_input_value']);
            $select_values = array();
            foreach($select_values_list as $item)
            {
                $item = trim($item);
                $select_values[] = array('id' => $item, 'text' => $item);
            }

            switch($extra_fields['fields_input_type'])
            {
              case  0:
                $extra_fields_string .= tep_draw_input_field('fields_' . $extra_fields['fields_id'],'fields_' . $extra_fields['fields_id'],$value). (($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '');
              break;
              case  1:
                $extra_fields_string .= tep_draw_textarea_field('fields_' . $extra_fields['fields_id'],'fields_' . $extra_fields['fields_id'], 'soft', 50, 6,$value,'style="width:400px;"'). (($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '');
              break;
              case  2:
                foreach($select_values_list as $item) {
                  $item = trim($item);
                  $extra_fields_string .= tep_draw_radio_field('fields_' . $extra_fields['fields_id'],'fields_' . $extra_fields['fields_id'] . '_' . ($cnt++), 'radio', $item, (($value == $item)?(true):(false))).$item. (($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '').'';
                  $extra_fields['fields_required_status']  = 0;
                }
              break;
              case  3:
                $cnt = 1;
                foreach($select_values_list as $item) {
                  $item = trim($item);
                  $extra_fields_string .= tep_draw_checkbox_field('fields_' . $extra_fields['fields_id'] . '_' . ($cnt++),'fields_' . $extra_fields['fields_id'] . '_' . ($cnt++), 'checkbox', $item, ((@in_array($item, $value_list))?(true):(false))).$item. (($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '').'<br />';
                  $extra_fields['fields_required_status']  = 0;
                }
                $extra_fields_string .= tep_draw_hidden_field('fields_' . $extra_fields['fields_id'] . '_total' , $cnt);
              break;
              case  4: $extra_fields_string .= tep_draw_pull_down_menu('fields_' . $extra_fields['fields_id'],'fields_' . $extra_fields['fields_id'], $select_values, $value).(($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '');
              break;
              case  5:
                $extra_fields_string .= tep_draw_hidden_field('fields_' . $extra_fields['fields_id'] , $value);
              break;
              default: $extra_fields_string .= tep_draw_input_field('fields_' . $extra_fields['fields_id'],'fields_' . $extra_fields['fields_id'],$value). (($extra_fields['fields_required_status']==1) ? '<span class="inputRequirement">*</span>': '');
            }

            $extra_fields_string .='</p>';
        }
        $extra_fields_string .= '</fieldset>';

    }
    return $extra_fields_string;
}
// EOF Customers extra fields


/**
 * \fn tep_values_name($values_id)
 * \brief Recup le nom des options , lors utilisation attribut produits
 * \a int l'ID de l'option
*/
function tep_values_name($values_id) {
  $DB=Database::getInstance();
  global $languages_id;

  $values = $DB->query("select products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where products_options_values_id = '" . (int)$values_id . "' and language_id = '" . (int)$languages_id . "'");
  $values_values = $values->fetchAssoc();

  return $values_values['products_options_values_name'];
}


/**
  EPF
  Recup du label d'un champs epf
*/
function tep_epf_label($id){
  global $languages_id;
  $DB=Database::getInstance();
  $resobj=$DB->query("SELECT epf_label  FROM ".TABLE_PRODUCTS_EXTRA_FIELDS_LABELS." WHERE epf_id='".(int)$id."' and languages_id='".(int)$languages_id."' ");
  $res=$resobj->fetchAssoc();
  return $res['epf_label'];
}


/**
 * \fn  tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address)
 * \brief
  		Send email (text/html) using MIME
  		This is the central mail function. The SMTP Server should be configured correct in php.ini
  * \a
  $to_name           The name of the recipient, e.g. "Jan Wildeboer"
  $to_email_address  The eMail address of the recipient,
  e.g. jan.wildeboer@gmx.de
  $email_subject     The subject of the eMail
  $email_text        The text of the eMail, may contain HTML entities
  $from_email_name   The name of the sender, e.g. Shop Administration
  $from_email_adress The eMail address of the sender,
  e.g. info@mytepshop.com
*/
function tep_mail($to_name, $to_email_address, $email_subject, $email_array, $from_email_name, $from_email_address) {

    if (!_cst_bool('SEND_EMAILS')) return false;
    // Instantiate a new mail object
    $message = new PHPMailer();

    if (EMAIL_TRANSPORT == 'smtp'){
      $message->IsSMTP(); // telling the class to use SMTP

      if( !tep_not_null($from_email_address) ) $from_email_address = SMTP_SENDMAIL_FROM;
      if( !tep_not_null($from_email_name) ) $from_email_name = SMTP_FROMEMAIL_NAME;
      // Config
      $message->Host = SMTP_MAIL_SERVER; // SMTP server
    }else{
      $message->IsSendmail();
//       $mail->Sendmail ='/usr/sbin/sendmail';
      //////(EMAIL_TRANSPORT == 'sendmail')
      //////You need to implement here if you are using sendmail
      if(empty($from_email_address))$from_email_address=EMAIL_FROM;
      if(empty($from_email_name))$from_email_name=STORE_OWNER;
    }


    $message->From = $from_email_address;
    $message->FromName = $from_email_name;

    $message->CharSet = strtoupper(CHARSET );

    if( !tep_not_null($to_name) ) $to_name = '';

    if( !tep_not_null($to_email_address) ) return false;


    $message->AddAddress($to_email_address, $to_name);
    $message->Subject = $email_subject;

    ///retro compatibilité
    if(!is_array($email_array)) $email_array=array('text'=>$email_array, 'html'=>$email_array);

    // Build the text version
    $text = str_replace( array('<br>','<br />','<br/>',  '&nbsp;','&euro;'), array("\n","\n",' ','euro'),$email_array['text']);
    $text = strip_tags(html_entity_decode($text ,ENT_QUOTES ));
//     $text = iconv ( 'ISO-8859-1',strtoupper(CHARSET ), strip_tags(html_entity_decode($text ,ENT_QUOTES, strtoupper(CHARSET ) ) ,"\n\r"));

    if (EMAIL_USE_HTML == 'true') {
      $message->Body = $email_array['html'];// tep_convert_linefeeds(array("\r\n", "\n", "\r"), '<br>', $email_text);
      $message->AltBody = $text;
      $message->IsHTML(true);
    } else {
      $message->Body = $text;
      $message->IsHTML(false);
    }

    // Send message
    if(!$message->Send()){
      trigger_error(sprintf(__FUNCTION__.'Mailer error: %s', $message->ErrorInfo), E_USER_ERROR);
      return false;
    }
    else return true;

}

/**
  @package oscss-Rv
  @author oscim - OscssTeam
  @version 2.0
  Construteur de mise en forme des email avant envoi; remplace les code raccouris et ajoute si necessaire l'entete html
  @param string nom du template
  @param string path du language utilis pour le mail
  @param array $myarray key/value des var perso
  @param boolean return / print
*/
function tep_post_prepare_email($gabarit_template,$language,$myarray,$print=false){
  global $title_email,$messageStack,$page;

  $gabarit_template=(tep_not_null($gabarit_template))? $gabarit_template : 'defaut.tpl' ;

  if ( ($template=page::TestFile(DIR_FS_CATALOG.DIR_WS_MODULES . 'template_email/'.$gabarit_template)) !=false)
    $new_file=DIR_WS_MODULES . 'template_email/'.$gabarit_template;
  elseif ( ($template=page::TestFile(DIR_FS_CATALOG.$page->getPathTemplate().DIR_WS_MODULES . 'template_email/'.$gabarit_template)) !=false)
    $new_file=$page->getPathTemplate().DIR_WS_MODULES . 'template_email/'.$gabarit_template;
  elseif ( ($template=page::TestFile(DIR_FS_CATALOG.DIR_WS_MODULES . 'template_email/'.'defaut.tpl')) !=false)
    $new_file=DIR_WS_MODULES . 'template_email/'.'defaut.tpl';
  elseif ( ($template=page::TestFile(DIR_FS_CATALOG.$page->getPathTemplate().DIR_WS_MODULES . 'template_email/'.'defaut.tpl')) !=false)
    $new_file=$page->getPathTemplate().DIR_WS_MODULES . 'template_email/'.'defaut.tpl';
  else
    trigger_error(sprintf(__FUNCTION__.'Mailer template error no found : %s', $gabarit_template), E_USER_ERROR);

  $file = basename($new_file);
  if ( ($fileLang=page::fix_file(DIR_FS_CATALOG.DIR_WS_LANGUAGES . $language .'/modules/template_email/'.substr($file, 0, strlen($file)-4) .'.txt')) !=false)
    include($fileLang);

  $title_email=$lang['EMAIL_TEXT_SUBJECT'];
  if(!defined('EMAIL_TEXT_SUBJECT'))define('EMAIL_TEXT_SUBJECT',$lang['EMAIL_TEXT_SUBJECT']);

  $tpl = &Template::singleton();

  $myarray['br']="\n";
  if (!empty($tpl->error)) {
    trigger_error(sprintf(__FUNCTION__.'Mailer template error: %s', $message->ErrorInfo), E_USER_ERROR);
    return false;
  }
  $tpl->template_dir =  dirname($new_file).'/'; //DIR_WS_MODULES . 'template_email/';
  $tpl->assign("STORE_LOGO_PRINT",STORE_LOGO_PRINT);
  $tpl->assign("DIR_WS_CATALOG", DIR_WS_CATALOG);
  $tpl->assign("HTTP_SERVER", HTTP_SERVER);
  $tpl->assign("DIR_WS_IMAGES", DIR_WS_IMAGES.'mail/');
  $tpl->assign("DIR_WS_LANGUAGES", DIR_WS_LANGUAGES);
  $tpl->assign("CHARSET", CHARSET);
  $tpl->assign("STORE_NAME", STORE_NAME);
  $tpl->assign("myarray", $myarray);
  $tpl->assign("TPL_CONTENT", addslashes($myarray['message']));
  if (isset($lang) && is_array($lang))$tpl->assign("lg", $lang);

  if (!empty($tpl->error)) {
    trigger_error(sprintf(__FUNCTION__.'Mailer template error: %s', $message->ErrorInfo), E_USER_ERROR);
    return false;
  }

  if(!$print) {
    $mess['html']=$tpl->get($file);

    // force calcul txt
    $myarray['email_use_html']=false;
    $tpl->assign("myarray", $myarray);

    $mess['text']=$tpl->get($file);

    return $mess;
  }
  else return $tpl->display($file);
}


/**
  \brief Chargement des fichiers de gabarit html
  \a string name file sans ext
*/
function tep_get_include_contents($filename) {
  global $page;
  if ( ($file=page::fix_file(DIR_FS_CATALOG.DIR_WS_INCLUDES.'gabarit/'.$filename.'.gab')) != false){
    ob_start();
    include $file;
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
  }
  return false;
}


/** Alias */
function tep_get_countries_with_iso_codes($countries_id) { return tep_get_countries($countries_id, true); }
function tep_get_country_name($country_id) { $country_array = tep_get_countries($country_id); return $country_array['countries_name']; }
function tep_count_credit_modules() { return tep_count_modules(MODULE_CREDIT_INSTALLED); }
function tep_count_payment_modules() { return tep_count_modules(MODULE_PAYMENT_INSTALLED); }
function tep_count_shipping_modules() { return tep_count_modules(MODULE_SHIPPING_INSTALLED); }


/**
  Fonctions remplacé par des class
  => Retrocompatibilité
*/

function tep_count_customer_orders($id = '', $check_session = true) { return customer::count_customer_orders($id , $check_session ); }
function tep_count_customer_address_book_entries($id = '', $check_session = true) {return customer::count_customer_address_book_entries($id , $check_session ); }
function tep_address_label($customers_id, $address_id = 1, $html = false, $boln = '', $eoln = "\n") {return customer::address_label($customers_id, $address_id , $html , $boln, $eoln ); }


function tep_get_tax_rate($class_id, $country_id = -1, $zone_id = -1)   { global $price; return $price->get_tax_rate($class_id, $country_id, $zone_id); }
function tep_get_tax_description($class_id, $country_id, $zone_id)      { global $price; return $price->get_tax_description($class_id, $country_id, $zone_id); }
function tep_add_tax($products_price, $tax, $force=false, $strict=true) { global $price; return $price->display_with_tax($products_price, $tax, $force, $strict); }
function tep_calculate_tax($products_price, $tax,$strict=false)         { global $price; return $price->get_tax_amount($products_price, $tax,$strict=false); }
function tep_display_tax_value($value, $padding = TAX_DECIMAL_PLACES)   { global $price; return $price->display_tax_value($value, $padding); }


function product_info($pID)		  { return product::get_item($pID); }
function tep_has_product_attributes($pID) { return product::get_has_product_attributes($pID); }
function tep_get_product_path($pID) 	  { return product::get_product_path($pID); }
function tep_get_products_stock($pID, $attributes=array()) { return product::get_products_stock($pID,$attributes); }
function product_attribut_info($pID)	  { return product::get_product_attribut_info($pID); }
function tep_get_products_name($id) 	  { $content=product::get_item($id); return $content->name; }
// function tep_get_products_special_price($product_id) {returnproduct::isplay_tax_value($value, $padding);}

function tep_get_path($current_category_id = '',$value=false) {return categorie::get_path($current_category_id,$value); }
function tep_count_products_in_category($category_id, $include_inactive = false){return categorie::get_count_products_in_category($category_id, $include_inactive = false); }
function tep_has_category_subcategories($category_id){return categorie::get_has_category_subcategories($category_id); }
function tep_get_parent_categories(&$categories, $categories_id) { return categorie::get_parent_categories($categories, $categories_id); }
function tep_get_subcategories(&$subcategories_array, $parent_id = 0)  { return categorie::get_subcategories($subcategories_array, $parent_id); }
function tep_get_categories($categories_array = '', $parent_id = '0', $indent = '')  { return categorie::get_categories($categories_array , $parent_id, $indent); }

function tep_get_content_cat($content_id){ return content::get_content_cat($content_id); }
function tep_get_content_path($content_id) { return content::get_content_path($content_id); }
function tep_get_cms_title_in_cat($current_category_id=0, $exclude=''){ return content::get_content_in_cat($current_category_id, $exclude); }
function tep_retrun_cms_liste_byDate($max=10, $exclude='') { return content::get_cms_liste_byDate($max, $exclude); }
/**
 * \fn tep_get_cms_title($content_id)
 * \a $content_id string/int ID or name
*/
function tep_get_cms_title($content_id) {
  global $languages_id;
  $content=content::get_item($content_name);
  if($content ==false) return false;
  return $content->title;
}

/**
  @fn tep_get_cms_content($content_string, $title=false, $string="<h2>%s</h2><div>%s</div>")
  @param $content_string string name [ id
  @param $title boolean false/true
  @param $string string  format titre
  @brief Recuperation des elements contenu du texte
    Tranformation des images
*/
function tep_get_cms_content($content_string, $title=false, $string="<h2>%s</h2><div>%s</div>") {
  global $languages_id;
  $content=content::get_item($content_string);
  if($content ==false) return false;
  else
   return (($title) ? sprintf($string, $content->title,$content->text) :sprintf($string, '',$content->text) );
}

/**
 * \fn tep_retrun_cms_title($content_name, $exclude='')
 * \brief
  	 Recupere la liste des article cms dont le nom est passé en arguement
 	 Tri part sort_order etcontent_name
  \author oscim - <mail aurelien@oscim.fr> <www http://www.oscim.fr>
    \a string content_name le nom du titre
    \a array tableau d'exclusion

*/
function tep_retrun_cms_title($content_name, $exclude='') {
  global $languages_id;

  $tabl=array();
  $content_query=content::get_query('',$content_name,$exclude,array('limit'=>20));
  if($content_query ==false) return false;

  foreach($content_query as $content){
    if(is_object($content)){
      $tabl[$content->id]['title']=$content->title;
      $tabl[$content->id]['href']=tep_href_link(FILENAME_CONTENT,'content=' . $content->id/* . '&amp;language=' . $display_lang['code']*/);
      $tabl[$content->id]['key']=$content->name;
    }
  }
   return $tabl;
}




?>