<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @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  25/03/11, 15:42
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class oscss_cstr
  Constructeur de page et ordonanceur.
  Prend en charge l'appel des extensions

  NOTE:


    chargement d'une extension
    ex: $oscss->_add_ext('dsrte','editeur/');

    Appel init top de l'extension
    ex: echo $oscss->_call('dsrte','_top',[option]);

    Appel script extension
    ex: echo $oscss->_call('dsrte','_head',[option]);

    Appel / exe extension
    ex: echo $oscss->_call('dsrte','_draw',[option]);

*/

class oscss_cstr {

  private static $PileFile=array();
  /**
    @p string name file cache file exists
  */
  private static $key_file_cache;

  protected static $_instance;

  protected function __construct(){
    $this->vars=array();

    /**
      Pile des file de lang
    */
    $this->PileFileLang=array();

    //! key cache file
    self::$key_file_cache= 'BO_files-'.md5(basename($_SERVER['REQUEST_URI']).(isset($_SESSION['login_firstname'])? $_SESSION['login_firstname']: 'guest'));



  }

  public static function getInstance() {
    if(self::$_instance == null)  self::$_instance = new self();
    return self::$_instance;
  }

  /**
    Add constructeur
  */
  private function add_obj($class){
    if (class_exists($class)) $this->$class = new $class();
    else return false;
  }

  public static function afterAppliTop(){
    /**
      @brief init class
    */
    new CsrtAction;
  }


  /**
    Ajout d'element a l'object precisé
  @param
    @p object $object nom du sous l'object a qui ajoute l'element
    @p string nom de var ajouté
    @p string type de var
    @p array/string/int/... valeur
  */
  public function _add_in($object, $name, $value){
    if (!isset($this->$object) && !$this->add_obj($object) ){
      die(_('pas d\'oject de ce nom')) ;
    }

    //! operator
    $obj=$this->$object;
    if(is_object($value)){
      $this->$name=$value;
    }elseif(is_array($value)) {
      $obj[$name]=$value;
      $this->$object=$obj;
    }
    elseif(is_string($value)){
      $obj[$name]=addslashes($value);
      $this->$object=$obj;
    }
  }

  /**
    init d'un object
    @p string nom de l'object
  */
  public function _add_init($object){
     if (!isset($this->$object) && !$this->add_obj($object) ){
      die(_('pas d\'oject de ce nom')) ;
    }
    return $this->$object;
  }


  /**
    Init d'un plugin via un fichier oscss_init
    Les functions seront aouté aux sous object
    @p string path generic (ex:DIR_WS_PLUGIN) (terminé par /)
  @p string $name_object nom de l'object
  */
  public function _add_ext($name_object, $path){
    if(is_dir($path) && self::TestFile($path.$name_object.'/oscss_init.php') ) {
      include($path.$name_object.'/oscss_init.php');
      $this->add_obj($name_object.'_oscss');
    } else die(_('Error extenion introuvable'));
  }


  /**
    Appel public des function de chargeur des extensions
    @p string object key de l'obj (ex 'dsrte' pour la class 'dsrte_oscss' )
    @p string $function de construction block (_top, _head, _draw)
    @p all tous les arguement a passer à la function
  */
  public function _call($key_object, $funct/*[arg functions] */){
    $oscss=$this;
    $object=$key_object.'_oscss';
    if(!isset($this->$object)) return false;
    $vars='';
    if(func_num_args()>2) {
      for($i=2;$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 ($vars !='') {
      eval("\$ret = \$this->\$object->$funct($vars);");
      return  $ret;
    }
    else return $this->$object->$funct();
  }

  /**
    stock var in array
    key => value
  */
  public function add_var($key,$value){
      $this->vars[(string)$key]=$value;
  }

  /**
    Retour du contenu var
  */
  public function the_var($key){
      if(isset($this->vars[(string)$key])) return $this->vars[(string)$key];
      else return false;
  }
//   public function


  /**
    Chargeur de fichier de langues
    Specifique au .txt
  */
  public function pile_file_lang($path_file){
    global $lang;
    if(substr($path_file,0,strlen(DIR_FS_ADMIN)) !=DIR_FS_ADMIN) $path_file= DIR_FS_ADMIN.$path_file;

    if(!in_array($path_file,$this->PileFileLang))
      if(self::TestFile($path_file)) include_once($path_file);

  }

  /**
    Appelé en debut et fin d'appli
    Charge et stock le cache des fichier de lang en .txt
    Fichier concatene en un seul
  */
  public function cache_lang($load=true){
    global $osCSS_Cache,$lang;

    $key_file= 'BO_lang-'.$this->the_var('languages_id').'-'.md5(basename($_SERVER['REQUEST_URI']).(isset($_SESSION['login_firstname'])? $_SESSION['login_firstname']: 'guest'));

    if($load){
      if ($osCSS_Cache->read($key_file, 3600) ) {
        $res= $osCSS_Cache->getCache();
        global $lang;
        $lang=$res['lang'];
        $this->PileFileLang=$res['PileFile'];
      }
    } else{
      if(!isset($this->PileFileLang)) $this->PileFileLang=array();
      $osCSS_Cache->read($key_file, 3600);
      $PileFile=array();
      foreach(get_included_files() as $e)
        if(substr($e,-3)=='txt') $PileFile[]=$e;

      if(count($PileFile)>0) {
        $variable = array('lang'=>$lang,'PileFile'=>array_merge($PileFile,$this->PileFileLang) );
        $osCSS_Cache->writeBuffer($variable);
      }
    }
  }


  /**
    test si fichier existe et cache du test
    enregsitrement a la volee
    return boolean
  */
  public static function TestFile($file){
    global $osCSS_Cache,$lang;

    $keytemp=md5($file);

    if ($osCSS_Cache->read(self::$key_file_cache, 3600) ) {
      $res= $osCSS_Cache->getCache();
      self::$PileFile=$res;
      $result=self::Testfile_exists($file,$keytemp);
      if(count($res) < count(self::$PileFile)){
	$osCSS_Cache->clear(self::$key_file_cache);
	$osCSS_Cache->writeBuffer(self::$PileFile);
      }
    }
    else {
      $result=self::Testfile_exists($file,$keytemp);
      $osCSS_Cache->writeBuffer(self::$PileFile);
    }
    return _test_bool($result);
  }

  private static function Testfile_exists($file,$keytemp){
    if(isset(self::$PileFile[$keytemp])) return self::$PileFile[$keytemp];
    elseif(file_exists($file)) return self::$PileFile[$keytemp]='true';
    else return 'false';
  }

  /**
    @fn oscss_cstr::test_gab_theme($element,$ext='php')
    @brief load Template Environement
      test présence élément de gabarit, retour false ou path
    @return (bool)false OR string path file
  */
  public static function test_gab_theme($element,$ext='php'){
    if (self::TestFile(DIR_WS_TEMPLATE.$element.'-'.$_SESSION['login_groups_id'].'.'.$ext) ) return DIR_WS_TEMPLATE.$element.'-'.$_SESSION['login_groups_id'].'.'.$ext;
    elseif (self::TestFile(DIR_WS_TEMPLATE.$element.'-'.$_SESSION['login_id'].'.'.$ext) ) return DIR_WS_TEMPLATE.$element.'-'.$_SESSION['login_id'].'.'.$ext;
    elseif (self::TestFile(DIR_WS_TEMPLATE.$element.'-1.'.$ext) ) return DIR_WS_TEMPLATE.$element.'-1.'.$ext;
    elseif (self::TestFile(DIR_WS_TEMPLATE.$element.'.'.$ext) ) return DIR_WS_TEMPLATE.$element.'.'.$ext;
    else return false;
  }


  /**
    @fn oscss_cstr::linkDocs($page_module)
    @brief link for online docs, in http://wiki.oscss.org/documentation/
    @param $page_module nom page courante
  */
  public static function linkDocs($page_module){
    $url ="http://wiki.oscss.org/documentation/?";
    $url.="version=2.1.0&lang=fr_FR&page=".$page_module."&path=".$page_module;
    if(isset($_REQUEST['type'])) $url.="/".$_REQUEST['type'];
    if(isset($_REQUEST['action'])) $url.="&action=".$_REQUEST['action'];
    return $url;
  }

  public function debugg(){
    print_r( $this);
  }
}



/**
  @brief class de gestion des boutons , liens et commande d'action.
  @class
  TODO:  integrer ACL
*/

class CsrtAction {

  public static $SimpleP;

  function __construct(){
    $FeedUrl = DIR_WS_TEMPLATE.'/data/icon_set.xml';

    if(!self::$SimpleP = @simplexml_load_file($FeedUrl))
      if(!self::$SimpleP = @simplexml_load_file('includes/template/defaut/data/icon_set.xml'))
	return ;
  }

  /**
    @brief check and return file for icon code
    @param $code unique id icon in data xml
    @return string file name
  */
  public static function getIcon($code){
    $ref=self::$SimpleP->img->icon;
    if(isset($ref->$code)) return (string)$ref->$code;
  }

  /**
    @brief check and return file for icon code
    @param $code unique id icon in data xml
    @return string file name
  */
  public static function getFormat($code){
    $ref=self::$SimpleP->format;
    if(isset($ref->$code)) return (string)$ref->$code;
  }

  /**
    @brief construit le formatage des liens et bouton d'action
      Organise le formatage des format destiné au spintf
      Definis si texte ou image , si image ok
    @param $code string (ex: row_action_right)
    @param type string (button|link)
    @param $txt string texte du bouton
    @param $codeImg string le code de l'image, de l'incone
    @return string for sptrinf
  */
  protected static function getbalise($code,$type,$txt,$codeImg=''){
    $ref=self::$SimpleP->gabarit;
    $mode='simple';
    if(isset($ref->$code)){
      $obj = $ref->$code->$type;
      if(!empty($codeImg) ) {
      $w=( ( (int)$obj->icon[0]['width']>0)? (int)$obj->icon[0]['width'] : '');
      $h=( ( (int)$obj->icon[0]['height']>0)? (int)$obj->icon[0]['height'] : '');

	if(isset($obj->icon[0]['src']) && (bool)$obj->icon[0]['src']){
	  $i=image_ratio::get_image(DIR_WS_ICONS .self::getIcon($codeImg) ,$txt , $w,$h);
	  $img=$i['src'];
	  $mode='complexe';
	}
	else
	  $img= tep_image(DIR_WS_ICONS . self::getIcon($codeImg) ,$txt , $w,$h );
      }
      else $img =false;

      if( $img != false ){
	if($mode==='simple') return str_replace('%_TEXT_%' , $img, (string)$obj->icon );
	else return str_replace(array('%_TEXT_%','%_SRC_%') , array($txt,$img), (string)$obj->icon );
      }
      else return str_replace('%_TEXT_%', $txt, (string)$obj->text );
    }
  }

  /**
    @brief Alias getFormat($code,$type,$txt,$codeImg='')
  */
  static public function getLink($code,$txt,$codeImg=''){
    return self::getbalise($code,'link',$txt,$codeImg);
  }

  /**
    @brief Alias getFormat($code,$type,$txt,$codeImg='')
  */
  static public function getButton($code,$txt,$codeImg=''){
    return self::getbalise($code,'button',$txt,$codeImg);
  }

  /**
    @brief Alias getFormat($code,$type,$txt,$codeImg='')
  */
  static public function getSubmit($code,$txt,$codeImg=''){
    return self::getbalise($code,'submit',$txt,$codeImg);
  }

  /**
    @brief Alias getFormat($code,$type,$txt,$codeImg='')
  */
  static public function getImage($code,$txt,$codeImg=''){
    return self::getbalise($code,'image','',$codeImg);
  }
}
?>