<?php
/*
Copyright (C) 2008 by oscim   Project lossim  [created : 30.07.2009, 10:54:30] @oscim
// kate: replace-trailing-space-save true; space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; word-wrap-marker-color #41C2A4
ENCODE UTF-8
*/

/**
*/
function NewFct($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)/* !defined('_FCT_'.strtoupper($fct).'_')*/) {
    if(@include_once ("$chemin"."include/lib/inc/$fct.inc"))
      define('_FCT_'.strtoupper($fct).'_',true);
    elseif(@include_once (REP_LIB_PARTAGE.$fct.".inc"))
      define('_FCT_'.strtoupper($fct).'_',true);
    else return false;
  }
  if($vars!='') {
    eval("\$ret = $fct($vars);");
    unset ($vars);unset ($t);
  }
  else eval("\$ret = $fct();");
  return $ret;
}


/**
* @author oscim
* @arg le non de la constante
* @note renvoi true si constante defini et egale à true, sinon false
*/
function test_const($constante){
  $e=@constant(strtoupper($constante));
  if( (is_string($e) && strtoupper($e)=='TRUE')||( is_bool($e) && $e==TRUE)  )  return true;
  elseif( (is_string($e) && (strtoupper($e)=='FALSE'))  || ( is_bool($e) && $e==FALSE)  ) return false;
  return false;
}

/**
 Test boolean ou equivalent ('true', 'True', 'TRUE', true)
 @param
  @a string/boolean

 @return boolean
*/
function test_bool($var){
  if(empty($var)) return false;
  if( (is_string($var) && strtoupper($var)=='TRUE')||(is_numeric($var) && $var==1)||( is_bool($var) && $var==TRUE)  )  return true;
  elseif( (is_string($var) && (strtoupper($var)=='FALSE'))  || (is_numeric($var) && $var==0)||( is_bool($var) && $var==FALSE)  ) return false;
  return false;
}


/**
* @author oscim - LossimTeam
* @version 1.3
* @arg
* @note return etat module public Uniquement (rep/include/modules/) true ou false
        Prend en charge le choix entre class ou module, dans le cas d'une class active, renvoi le module actif si different de false
*/
function test_addon_activ($name,$type='module'){
  $NAME=strtoupper($name);
  if ($type=='module') {
    if (defined('PX_CONFIG_MODULE_'.$NAME)AND @constant('PX_CONFIG_MODULE_'.$NAME)=='true') return true;
    else return false;
  } elseif ($type=='class') {
    if (defined('PX_CONFIG_CLASS_'.$NAME)AND @constant('PX_CONFIG_CLASS_'.$NAME) !='false') return @constant('PX_CONFIG_CLASS_'.$NAME);
    else return false;
  }
}


/**
* @author oscim - LossimTeam
* @version 1.35
* @arg  $module name extension
        $lib nom de la librairie (suffixe)
        $type (module/class)
        $type_file (lib,tbl)
* @note
* @include class page
*/
function include_addon_activ($module,$lib,$type='module',$type_file='lib'){
    if ($type=='module'){
      $NAME=($type_file=='lib') ? strtoupper('_'.$module.'_'.$lib) : strtoupper($module);
    }elseif ($type=='class') {
      $NAME=($type_file=='lib') ? strtoupper('_'.@constant('PX_CONFIG_CLASS_'.strtoupper($module)).'_'.$lib) : strtoupper('tbl_'.@constant('PX_CONFIG_CLASS_'.strtoupper($module)).'_'.$lib);
    }
    page::include_file(@constant($NAME),'');
}

/**
 Construit sortie title + medta descri et tag,. entrée string . 2 type sortie en focntion appel ajax ou classi
 Blok mes sortie de meta si ajax
*/
function format_title($title,$meta_desc='',$meta_tag=''){
    if  (!test_const('AJAX_REQUEST')) {
        print "<title>".$title."</title>\n";
        if (!empty($meta_desc))print "<meta name=\"description\" content=\"".$meta_desc."\" />\n";
        if (!empty($meta_tag))print "<meta name=\"keywords\" content=\"".$meta_tag."\" />\n";
    } else {
        print "<p id=\"hidden_title\" style=\"display:none;\">".$title."</p>\n";
        if (!empty($meta_desc))print"<p id=\"hidden_descri\" style=\"display:none;\">".$meta_desc."</p>\n";
        if (!empty($meta_tag))print"<p id=\"hidden_tag\" style=\"display:none;\">".$meta_tag."</p>\n";
    }
}

/**
string en entree, sortie tableau key/value. separation des element par & et sepraration key value par =
*/
function extract_option($option){
    if(!empty($option)) {
        if (!ereg("&$",$option)) $option.='&';
        $opt=explode ('&',$option);
        while ($r=each($opt))
            if (!empty($r['value'])) {
                $key=trim(substr($r['value'],0, (strpos($r['value'],'='))));
                $val=trim(substr($r['value'],(strpos($r['value'],'=')+1), strlen($r['value'])));
                $options[$key] = $val;
            }
    }
    return $options;
}


/**
* @author oscim - LossimTeam
* @version 1.0
* @arg
* @note retour de la date sous la forme mktime (HismdY)
*/
function tep_return_mktime($date, $format='m-d-Y'){
    if(!tep_not_null($date)) return mktime(0,0,0,0,0,0);
    $d_=explode('-',$date);
    if($format=="m-d-Y") return mktime(0,0,0,$d_[0],$d_[1],$d_[2]);
    elseif($format=="d-m-Y") return mktime(0,0,0,$d_[1],$d_[0],$d_[2]);
    elseif($format=="Y-m-d") return mktime(0,0,0,$d_[1],$d_[2],$d_[0]);
}


/**
* @author oscim - LossimTeam
* @version 1.53
* @arg
* @note test le fichir dater pour affichage ou non test aussi etat
*/
function test_file_name_dater($dest_sans_lg,$mode='norm'){
  $i_links='';
  static $i_links;
  if (!is_array($i_links)) include(TBL_INDEX_LINKS_INC);
  if  ($dest_sans_lg ==false) return false;
  $key=md5($dest_sans_lg);

  $pub_c=$dt_c=$pub_r=mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
  if  (isset($i_links[$key]['date_publi']) && !in_array($i_links[$key]['date_publi'], array('00-00-0000','')) )
    $pub_c=tep_return_mktime($i_links[$key]['date_publi']).'<br />';;

  if  (isset($i_links[$key]['date_retrait'])&& !in_array($i_links[$key]['date_retrait'], array('00-00-0000','')) )
      $pub_r=tep_return_mktime($i_links[$key]['d_retrait']);

  if ( ($mode=='norm') && ( $pub_c <= $dt_c OR !isset($i_links[$key]['date_publi']) )&&( $pub_r >= $dt_c OR !isset($i_links[$key]['date_retrait']) ) ) return true;

  switch($mode) {
  case 'futur_strict':
      if ( $pub_c >= $dt_c /*AND $pub_r>$dt_c*/ ) return true;
      else return false;
  break;
  case 'passe_strict':
      if  ( $pub_c < $dt_c /*AND $pub_r<$dt_c*/)return true;
      else return false;
  break;
  case 'now':
    if (  $pub_c==$dt_c || $pub_r==$dt_c ) return true;
  default:
  case 'norm':
  default:
    if ( ( $pub_c <= $dt_c OR !isset($i_links[$key]['date_publi']) )&&( $pub_r >= $dt_c OR !isset($i_links[$key]['date_retrait']) ) ) return true;
  }
  return false;
}


/**
  Appel dabelau de langue, ne charge le fichie qu'une seul fois

  @def constant
    LANG_MULTI true (si multilangue)
    LANG_DEFAUT (fr/)
    LANG_CODE_DEFAUT (fr)
  @return tableau de langue
*/
function appel_lang(){
  $lg= '';  static $lg;
  if (!is_array($lg)) require(TBL_LANG_INC);
  $multi = (count($lg)>1) ? true: false ;
  if ( ($multi==true)AND (!defined('LANG_MULTI'))) define('LANG_MULTI',true);
  ## Definition de la constante de lang par default
  if (!defined('LANG_DEFAUT')) define('LANG_DEFAUT',$lg[LANG]['lang']."/");
  if (!defined('LANG_CODE_DEFAUT')) define('LANG_CODE_DEFAUT',LANG);
  return $lg;
}

/**
*/
function nett_acen($data){
        $data = stripslashes($data);
        $data= str_replace("\r\n", "<br />", "$data");
        $data= str_replace("\n\r", "<br />", "$data");
        $array_1 = array("&","^","\'","ç","é","è","ê","ë","à","â","ù","û","ü","ô","ö","î","ï","Ç","É","È","Ê","Ë","À","Â","Ù","Û","Ü","Ô","Ö","Î","Ï");
        $array_2 = array("&amp;","-","'","&ccedil;","&eacute;","&egrave;","&ecirc;","&euml;","&agrave;","&acirc;","&ucirc;","&ugrave;","&uuml;","&ocirc;","&ouml;","&icirc;","&iuml;","&Ccedil;","&Eacute;","&Egrave;","&Ecirc;","&Euml;","&Agrave;","&Acirc;","&Ugrave;","&Ucirc;","&Uuml;","&Ocirc;","&Ouml;","&Icirc;","&Iuml;");
        $data = str_replace($array_1, $array_2, $data);
        return $data;
}


/**
  Not null = true
*/
function tep_not_null($value) {
    if (is_array($value)) {
        if (sizeof($value) > 0) return true;
        else return false;
    } else {
        if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) return true;
        else return false;
    }
}

/**
*/
function tep_setcookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = 0) {
   return  setcookie($name, $value, $expire, $path, (tep_not_null($domain) ? $domain : ''), $secure);
}


/**
 penser a modifier les element des page modifier_un_fichier et creer_une_page et menu_ajax_complet  pour les liens de visiter cet articles, si l extention des fichier et modifier
gestion des liens et construction des url. si option $get >> ajout de parametre get (tec=1&tec=2)
*/
function tep_url_link($link='',$ext=true,$url=true,$get='',$ancre=''){
  $ext='.'.EXT;
  if (!empty($link))$link=  /*str_replace ('&',"&amp;",*/$link/*)*/ ;
  else {
    $r=extract_nom('');
    $link= $r['url'];
  }

  $get=(!empty($get)) ? '&'./*str_replace (array('&amp;','&'),"&amp;",$get)*/ $get: '';
  if (!@eregi("(^http:|^#|mailto|.(zip|tar|gz|pdf|ps|png|jpg|gif)$)",$link)){
    if($url==true){
      if (defined('LANG_MULTI') && LANG_MULTI==true && !eregi("(^[a-z]{2}/)",$link)) $link=LANG_POST.'/'.$link;
      $link = (URL_FORMAT=='simple') ? URL_DU_SITE."?".$link.$get : URL_DU_SITE.$link.$get;
    }
    if($ext==true) $link = $link.$ext.$ancre;
  }elseif (eregi("(^#)",$link)) {
    $resl=NewFct('extract_nom','');
    $lin  = (URL_FORMAT=='simple') ? URL_DU_SITE."?".$resl['url'].$get : URL_DU_SITE.$resl['url'].$get;
    if($ext==true) $lin = $lin.$ext.$ancre;
    $link = $lin.$link;
  }
  return $link;
}

/**
*/
function redirect($destination){
    print "<meta HTTP-EQUIV=\"refresh\" content=\"0; URL=".tep_url_link($destination)."\"> ";
    exit();
}

/**
 recuperation key du tableau php
*/
function recup_name_tabl_php($file){
    require(TBL_CONFIG_GEN);
    while($r=each($_Config_gen['key_tableau']))
            if (eregi("(/".$r['key'].")",str_replace('.','_',$file))) return $r['value'];
    print (' nom de tableau inconnu dans TBL_CONFIG_GEN '."\n");
}


/**
 function recuperation des $_GET et correction
*/
function construct_get(){
    $lg_ext=strlen('.html');
    $querystring=substr($_SERVER['QUERY_STRING'],0,-$lg_ext);
    $res=explode('&',$querystring);
    reset($res);
    while ($r=each($res)){
      if(($e=strpos($r['value'],'='))>0){
        $key=substr(trim($r['value']),0,$e);
        $value=substr(strchr($r['value'],'='),1);
        $get[$key]=$value;
      }
    }
    return @$get;
}

/**
*/
function unhtmlentities($chaineHtml,$utf8=false) {
   $tmp = get_html_translation_table(HTML_ENTITIES);
   $tmp = array_flip ($tmp);
   $chaineTmp = ($utf8==true) ?utf8_encode(strtr ($chaineHtml, $tmp)) : strtr ($chaineHtml, $tmp);
   return $chaineTmp;
}

/// ATTENTION REQUTE SUR TABLE UNIQUE
/**
SI id=!'' >> requete sur tableau a 2 dimension, sinon, tabl a 1 dimension (Revoir necessité)
*/
function exe_sql($action,$tables,$prefix,$query,$id=''){
  require_once("lib_partage/class.sql_php.php");
  /**   AJOUTER PRISE EN CHARGE REQUTE SUR PLSUEIRS TABLES */
  $sql= new sql_php($tables,true);
  if(!$sql) die(ERROR);
  if ($prefix =='')/* Insertion gestion prefix auto pour element de congig_general*/
   $prefix=recup_name_tabl_php($tables);

  $sql->prefix($prefix);
//   echo$prefix;
  if(tep_not_null($id))$sql->id($id);
  ereg(".*(UPDATE|SELECT|DELETE|INSERT|COUNT).*",$query,$reg);
  $action_select=(tep_not_null($reg[1]))? $reg[1] : $action ;
  switch ($action_select){
    case 'UPDATE':
      $g=$sql->update($query);
      if(!$sql) die(ERROR);
    break;
    case 'SELECT':
      $g=$sql->select($query);
      if(!$sql) die(ERROR);
    break;
    case 'COUNT':
      $s=$sql->select($query);
      if(!$sql) die(ERROR);
      $g=count($s);
    break;
    case 'DELETE':
      $g=$sql->deletes($query);
      if(!$sql) die(ERROR);
    break;
    case 'INSERT':
      $g=$sql->insert($query);
      if(!$sql) die(ERROR);
    break;
    case 'AUTOINC':
      $g=$sql->id_auto($query);
      if(!$sql) die(ERROR);
    break;
  }
  /* Var debug retour des class */
  if(DEBUG_SQL=='true')print_r(@$sql->retour_debugg);
  return $g;
}

/**
 Gestion des conevrtion de date

 f_sortie de sortie (dd - mm - YYYY) par defaut
*/
 function date_convert($var_date,$opt=''){
 /* modele */
 $mod_e=array('dd'      ,'d'            ,'d_3',         'mm',           'm',            'm_txt',        'm_3',          'YYYY',         'YY');
//  $mod_s=array('d'    ,'j'            ,'D'            ,'m' ,          'n',            'F'    ,        'M'             ,'Y'            ,'y');
 $masq= array('([0-9]{2})','([0-9]{1,2})'       ,'([a-z]{3})',  '([0-9]{2})',   '([0-9]{1,2})', '([a-z]*)',     '([0-9]{2})',   '([0-9]{4})',   '([0-9]{2})');

 /* options */
 $f_entree=(isset($opt['f_entree']))? $opt['f_entree'] :  'YYYY-mm-dd' ;
 $f_sortie=(isset($opt['f_sortie']))? $opt['f_sortie'] :  'dd-mm-YYYY' ;

        if (eregi("([0-9a-z]*)[ -]*([0-9a-z]*)[ -]*([0-9a-z]*)",$f_entree))$cara='-';
        elseif (eregi("([0-9a-z]*)[ ]*([0-9a-z]*)[ ]*([0-9a-z]*)",$f_entree))$cara=' ';

        $dd=explode($cara,$var_date);
        $ee=explode($cara,$f_entree);
//      $ss=explode($cara,$f_sortie);
 /* Exe */
        for($i=0,$max=count($ee);$i<$max;$i++){
                $dde[trim($ee[$i])]=@$dd[$i];
                $sse[trim($ee[$i])]=trim($ee[$i]);
        }

        return str_replace($sse,$dde,$f_sortie);// implode($cara,$sse);
 }


/**
  @author  OscssTeam
  @note  nettoyage de chaine de cratére (secu)
  @param string la chaine a nettoyer
*/
function tep_sanitize_string($string) {
  $string = ereg_replace(' +', ' ', trim($string));
  return preg_replace("/[<>]/", '_', $string);
}

/**
*/
function tep_db_prepare_input($string) {
  if (is_string($string)) {
    return trim(tep_sanitize_string(stripslashes($string)));
  } elseif (is_array($string)) {
    reset($string);
    while (list($key, $value) = each($string)) {
      $string[$key] = tep_db_prepare_input($value);
    }
    return $string;
  } else {
    return $string;
  }
}

/**
  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);
    }
  }
}

?>