<?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  26/01/11, 21:42
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
 *\file
 *\dir includes/functions/
 *\brief Librairie function sortie html
*/

/**
  Ultimate SEO URLs v2.1
  The HTML href link wrapper function
*/
function tep_href_link($page = '', $parameters = '', $connection = 'SSL', $add_session_id = true, $search_engine_safe = true) {
  if (_cst_bool('SEO_ENABLED')){
    global $languages_id;
    $seo_urls = seo_url::getInstance($languages_id);
    return preg_replace('/&/','&',$seo_urls->href_link($page, $parameters, $connection, $add_session_id));

  } else {
    global $request_type, $session_started, $SID;

    if (!tep_not_null($page))  $page=basename(preg_replace("/[?].*/i",'',$_SERVER['REQUEST_URI']));

    if ($connection == 'NONSSL')  $link = HTTP_SERVER . DIR_WS_HTTP_CATALOG;
    elseif ($connection == 'SSL')  $link = tep_get_httpdir();
    else die('<br /><br /><span class="erreur"><strong>Error!</strong><br /><br /><strong>Unable to determine connection method on a link!<br /><br />Known methods: NONSSL SSL</strong> <br /> cf tep_href_link</span><br />');

    if (tep_not_null($parameters)) {
      $link .= $page . '?' . tep_output_string($parameters);
      $separator = '&';
    } else {
      $link .= $page;
      $separator = '?';
    }

    while ( (substr($link, -1) == '&') || (substr($link, -1) == '?') ) $link = substr($link, 0, -1);

    // Add the session ID when moving from different HTTP and HTTPS servers, or when SID is defined
    if ( (_test_bool($add_session_id)) && (_test_bool($session_started)) && (!_cst_bool('SESSION_FORCE_COOKIE_USE')) ) {
      if (tep_not_null($SID))  $_sid = $SID;
      elseif ( ( ($request_type == 'NONSSL') && ($connection == 'SSL') && (_cst_bool('ENABLE_SSL')) ) || ( ($request_type == 'SSL') && ($connection == 'NONSSL') ) ) {
	if (HTTP_COOKIE_DOMAIN != HTTPS_COOKIE_DOMAIN)  $_sid = tep_session_name() . '=' . tep_session_id();
      }
    }

    if (isset($_sid))  $link .= $separator . tep_output_string($_sid);

    return $link;
  }
}



/**
 * \fn  tep_hide_session_id()
 * \brief Hide form elements
*/
function tep_hide_session_id() {
  global $session_started, $SID;
  if (($session_started == true) && tep_not_null($SID))  return tep_draw_hidden_field(tep_session_name(), tep_session_id());
}

/**
 * \fn tep_get_country_list($name,$id, $selected = '', $parameters = '')
 * \brief Creates a pull-down list of countries
 * @param $name string
 * @param $id integer
 * @param $selected null|
 * @param $parameters null | string
 */
function tep_get_country_list($name,$id, $selected = '', $parameters = '') {
  $countries_array = array(array('id' => '', 'text' => PULL_DOWN_DEFAULT));
  $countries = tep_get_countries();

  for ($i=0, $n=sizeof($countries); $i<$n; $i++) {
    $countries_array[] = array('id' => $countries[$i]['countries_id'], 'text' => $countries[$i]['countries_name']);
  }

  return tep_draw_pull_down_menu($name,$id, $countries_array, $selected, $parameters);
}

/**
 *\fn unhtmlentities([[$chaineHtml string],$utf8 (option) boolean])
 *\brief Nettoyeur de chaine de caratére, ou le reverse de htmlentites
 * @param $chaineHtml string
 * @param $utf8 boolean
 */
function unhtmlentities($chaineHtml,$utf8=false) {
  $tmp = array_flip (get_html_translation_table(HTML_ENTITIES));
  return ($utf8==true) ?utf8_encode(strtr ($chaineHtml, $tmp)) : strtr ($chaineHtml, $tmp);
}

/**
 * \version 1.3
 * \fn tep_include_file ($value,$force=false)
 * \brief Appel des fichiers est evite doublon
 * @param $value
 * @param $force boolean
 */
function tep_include_file ($value,$force=false) {
  static $deja_charge;
  if (!tep_not_null($value)) return false;

  $refe['url']=  tep_get_httpdir();
  $refe['path']= DIR_FS_CATALOG;

  $long=strlen($value);
  $key=md5(basename($value));
  if (!isset($deja_charge[$key]) || $force) {
    if (substr($value,($long-3),$long)=='css') print "<link rel=\"stylesheet\" href=\"".$refe['url'].$value."\"  type=\"text/css\" media=\"all\" />\n";
    elseif (substr($value,($long-2),$long)=='js') print '<script type="text/javascript" src="'.$refe['url'].$value.'"></script>'."\n";
    elseif(substr($value,($long-3),$long)=='php'||substr($value,($long-3),$long)=='inc'){
      if(substr($refe['path'],-1) !='/')$refe['path']=$refe['path'].'/';
      include ($refe['path'].$value);
    }
  }
  $deja_charge[$key]=basename($value);
}

/**
  \version 2
  \brief  Generate the menu, full or the cat
  \a int l'id de la categorie ou null pour tous
  \a bollean choix type retour, sting de sortie ou return tableau
  \return tableau ou string
*/
function oscss_navlinks($parent_id=0,$repeat=false) {
  global $languages_id, $customer_id,$seo_urls;
  $DB=Database::getInstance();

  $niveau=($repeat===false)? (int)0 : $repeat;
  $sql="select n.nav_link_id, n.nav_css_id, n.nav_file, n.nav_link_type as type, n.customers_status, nd.nav_name  from " . TABLE_NAVIGATION_LINKS . " n, ".TABLE_NAVIGATION_LINKS_DESCRIPTION . " nd  where n.nav_link_id = nd.nav_link_id and parent_id=".(int)$parent_id." and nd.language_id = '".(int)$languages_id."' and n.nav_link_status = '1'  order by  n.nav_sort_order, parent_id ASC";
  $nav_links_query = $DB->query($sql);
  $tableau=array();
  while ($nav_links = $nav_links_query->fetchAssoc()) {
    /// liens interne (avec GET)
    if($nav_links['type'] == '0' && ($pos=strpos($nav_links['nav_file'],'?')) && $pos>1  )  $url=tep_href_link(substr($nav_links['nav_file'],0,$pos), substr($nav_links['nav_file'],($pos+1)) );
    /// lien externe
    elseif($nav_links['type'] == '1') $url=$nav_links['nav_file'];
    /// function
    else $url=$nav_links['nav_file'];

    $ssmenu=oscss_navlinks($nav_links['nav_link_id'],($niveau+1));
    $nbr=count($ssmenu);
    /**
      $nav_links['customers_status']=='0' Aucunne
      $nav_links['customers_status']=='1' non logué
      $nav_links['customers_status']=='2' logué
    */
    if( ($nav_links['customers_status']=='1' && (!tep_session_is_registered('customer_id')))
	|| ($nav_links['customers_status'] =='2' && (tep_session_is_registered('customer_id')) )
	|| empty($nav_links['customers_status']) /*|| $nav_links['customers_status'] =='2'*/
      )
      $tableau[]=array('id'=>$nav_links['nav_link_id'],'type'=>$nav_links['type'],'css'=>$nav_links['nav_css_id'], 'url'=>$url, 'text'=>$nav_links['nav_name'], 'niveau'=>$niveau, 'count'=>$nbr);
  }
  return $tableau;
}


/**
 * \fn tep_manufacturers_list($current_category_id='', $cPath='')
  \version 2.1
  \brief  Generate the menu, full or the cat
   index_products/index/index_listing/index_categories_nesteds
 * @param $current_category_id int  de la categorie  courante ou null
 * @param $cPath var  categorie  courante ou null
    @b int $_GET['manufacturers_id']
    @b string $_GET['sort']
  \return string
*/
function tep_manufacturers_list($current_category_id='', $cPath=''){
  global $languages_id;
  $DB=Database::getInstance();
  $manufacturer_filter = '';
  if (_cst_bool('PRODUCT_LIST_FILTER')) {
    if (isset($_GET['manufacturers_id'])) {
      $filterlist_sql = "select distinct c.categories_id as id, cd.categories_name as name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where p.products_status = '1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p2c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' and p.manufacturers_id = '" . (int)$_GET['manufacturers_id'] . "' order by cd.categories_name";
    } else {
      $filterlist_sql= "select distinct m.manufacturers_id as id, m.manufacturers_name as name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_MANUFACTURERS . " m where p.products_status = '1' and p.manufacturers_id = m.manufacturers_id and p.products_id = p2c.products_id and p2c.categories_id = '" . (int)$current_category_id . "' order by m.manufacturers_name";
    }

    $filterlist_query = $DB->query($filterlist_sql);
    $manufacturer_filter = '';
    if ($filterlist_query->__get('numRows') > 1) {
      $manufacturer_filter .= tep_draw_form('filter', FILENAME_DEFAULT, 'get') . "\n";
      $manufacturer_filter .= '<fieldset class="manufacturerFilter">' . "\n";
      $manufacturer_filter .= '<p>'. "\n" ;
      $manufacturer_filter .= '<label for="filter_id">' . TEXT_SHOW . '</label>' . "\n";
      if (isset($_GET['manufacturers_id'])) {
	$manufacturer_filter .= tep_draw_hidden_field('manufacturers_id', $_GET['manufacturers_id']);
	$options = array(array('id' => '', 'text' => TEXT_ALL_CATEGORIES));
      } else {
	$manufacturer_filter .= tep_draw_hidden_field('cPath', $cPath);
	$options = array(array('id' => '', 'text' => TEXT_ALL_MANUFACTURERS));
      }
      if(isset($_GET['sort'])) $manufacturer_filter .= tep_draw_hidden_field('sort', $_GET['sort']);
      while ($filterlist = $filterlist_query->fetchAssoc()) {
	$options[] = array('id' => $filterlist['id'], 'text' => $filterlist['name']);
	if (isset($_GET['manufacturers_id']) && $filterlist['id']==$_GET['manufacturers_id']) $categ =$filterlist['name'];
      }
      $manufacturer_filter .= tep_draw_pull_down_menu('filter_id', 'filter_id',$options, (isset($_GET['filter_id']) ? $_GET['filter_id'] : ''), 'onchange="this.form.submit()"');
      $manufacturer_filter .= '</p>'. "\n". '</fieldset>' . "\n";
      $manufacturer_filter .= '</form>'. "\n";
    }
    tep_db_free_result($filterlist_query);
  }
  return $manufacturer_filter;
}


/**
 * \fn print_products_price_rv($product_info)
 * \version 2
 * \brief Retour du prix d'un produits, apres control sur special
 * @param $product_info array
 * @return string
*/
function print_products_price_rv($product_info){ // fonction obsolète dans le corps d'oscss2 (cf class price)
  global $price;
  // retro compatibilité
  if(is_object($product_info)) {
    return $price->print_products_price($product_info->products_id);
  }
  elseif (is_array($product_info)) {
    if ((!isset($product_info['products_id']) || !$product_info['products_id']) && isset($product_info['products_price']))
      return $price->display_products_price($product_info['products_price'], isset($product_info['products_tax_id'])?$product_info['products_tax_id']:0, isset($product_info['specials_new_products_price'])?$product_info['specials_new_products_price']:0);
    else return $price->print_products_price($product_info['products_id']);
  }
}

/**
  \fn CanonicalUrl
  \brief canonical tag function -
  \return url
*/
function CanonicalUrl() {
  global $request_type;
  $domain = substr((($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER), 0, -1);
  $string = $_SERVER['REQUEST_URI'];
  $search = '/\&osCsid.*|\?osCsid.*/';
  $replace = '';
  return $domain . preg_replace( $search, $replace, $string );
}


/**
  Fonctions remplacé par des class
  => Retrocompatibilité
*/
function tep_image($src, $alt = '', $width = '', $height = '', $parameters = '',$mode=false) { $img=image_ratio::getInstance(); return $img->tep_image($src, $alt, $width, $height, $parameters,$mode); }


function tep_image_submit($image, $alt = '', $parameters = '') { return formUtility::image_submit($image, $alt, $parameters ); }
function tep_image_button($image, $alt = '', $params = ''){ return formUtility::image_button($image, $alt, $parameters ); }
function tep_draw_form($name, $action,  $method = 'post', $params = ''){ return formUtility::draw_form($name, $action, ''/*$parameters*/, $method, $params ); }
function tep_draw_input_field($name, $id='', $value = '', $parameters = '', $required = false, $type = 'text', $reinsert_value = true) { return formUtility::draw_input_field($name, $id, $value, $parameters, $required , $type, $reinsert_value ); }
function tep_draw_password_field($name, $id='', $value = '', $required = false) { return formUtility::draw_input_field($name, $id, $value, 'maxlength="40"', $required, 'password', false); }
function tep_draw_file_field($name, $id='', $required = false,$parameters = '') { return formUtility::draw_input_field($name, $id, '', $parameters, $required, 'file' ); }
function tep_draw_selection_field($name, $id='', $type, $value = '', $checked = false, $compare = '', $parameters = ''){ return formUtility::draw_selection_field($name, $id, $type, $value , $checked , $compare, $parameters ); }
function tep_draw_checkbox_field($name, $id = '', $value = '', $checked = false,  $parameters = '') { return formUtility::draw_selection_field($name, $id, 'checkbox', $value, $checked, '', $parameters ); }
function tep_draw_radio_field($name, $id = '', $value = '', $checked = false,  $parameters = ''){ return formUtility::draw_selection_field($name, $id, 'radio', $value, $checked, '', $parameters ); }


function tep_draw_textarea_field($name, $id = '', $width, $height, $text = '', $parameters = '', $reinsert_value = true) { return formUtility::draw_textarea_field($name, $id , $width, $height, $text , $parameters , $reinsert_value); }
function tep_draw_hidden_field($name, $value = '', $parameters = '') { return formUtility::draw_hidden_field($name, $name , $value, $parameters ); }
function tep_draw_pull_down_menu($name, $id= '', $values, $default = '', $parameters = '', $required = false) { return formUtility::draw_pull_down_menu($name, $values, $default, $parameters, $required );}
function tep_draw_pull_down_radio($name, $id= '',$values, $default = '', $parameters = '', $required = false) { return formUtility::draw_pull_down_radio($name, $id,$values, $default, $parameters , $required); }
function tep_draw_pull_down_checkbox($name, $id= '',$values, $default = '', $parameters = '', $required = false)  { return formUtility::draw_pull_down_checkbox($name, $id,$values, $default, $parameters, $required ); }
?>