<?php
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @package oscss-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  03/01/11, 09:32
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @modified Ayatus <www http://www.ayatus.org>
  @encode UTF-8
*/
error_reporting(E_ALL);

Class core {
  /**
    Pile de message
  */
  public $Pile;

  private static $class;

  function __construct(){
    /**
      LAnguages
      Reperoire portant le nom de cla clef dans /includes/language/
    */
    $this->available_languages = array(
      'fr_FR' => 'Français [FR]',
//       'en_EN' => 'English [EN]',
    );


    /**
      Ordre des etape de l'install
      Fichier present dans /includes/content/
    */
    $etape=array(
      /**
	Check etat fichier et repertoire (droit fichier)
	Cherche fichier configure pour detreminer mode d'install
      */
                'core.base'=>1,
      /**
	2 Etpape
	Choix mode install (install|update)
	Information DB , SSL
	Information path , url
      */
                'core.modes'=>2,
      /**
      */
                'core.update'=>3,
      /**
	Recup svn
      */
                'core.installdb'=>4,
      /**

      */
                'core.configuration'=>5,
                'core.template_sample'=>6,
                'core.finition'=>7,
                );

    $i=0;
    if (!function_exists('curl_init') && !(boolean)ini_get('allow_url_fopen')){
      foreach($etape as $k=>$v)
	if($k!='core.update') $this->order_etape[$k]=$i++;

    }
    else
      $this->order_etape =$etape;

    $this->Pile=array();
  }

  /**
    Delete repertoire recursif
  */
  function recurse_delete($src){
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
    if (( $file != '.' ) && ( $file != '..' )) {
        if ( is_dir($src . '/' . $file) ) {
        core::recurse_delete($src . '/' . $file);
        }
        else {
        unlink($src . '/' . $file);
        }
    }
    }
    closedir($dir);
    rmdir($src);
  }

  /**
  Copy repertoire recursif
  */
  function recurse_copy($src,$dst){
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
    if (( $file != '.' ) && ( $file != '..' )) {
        if ( is_dir($src . '/' . $file) ) {
        core::recurse_copy($src . '/' . $file,$dst . '/' . $file);
        }
        else {
        copy($src . '/' . $file,$dst . '/' . $file);
        }
    }
    }
    closedir($dir);
  }

  /**
    retour lang item
  */
  public function l10n($str) {
    global $lang;
    return isset($lang[$str]) ? $lang[$str] : $str;
  }

  /**
  */
  function getLanguage() {
    global $lang;

    if (isset($_GET['language']) and isset($this->available_languages[$_GET['language']])) {
      $language = $_GET['language'];
    }
    else {
      $language = 'fr_FR';
      // Try to get browser language
      foreach ($this->available_languages as $language_code => $language_name) {
    if (substr($language_code,0,2) == @substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2)) {
      $language = $language_code;
      break;
    }
      }
    }
    // Retrieve traductions
    $lang = array();
    if (include(WS_LANGUAGE.$language.'/install.base.txt')) define('DC_LOADER_LANG', $language);
  }


  /**
    Recup post, et passage dans object des info de db
  */
  public function get_db_conf(){
      $this->db = array();
      $this->db['DB_SERVER'] = trim(stripslashes($_POST['DB_SERVER']));
      $this->db['DB_SERVER_USERNAME'] = trim(stripslashes($_POST['DB_SERVER_USERNAME']));
      $this->db['DB_SERVER_PASSWORD'] = trim(stripslashes($_POST['DB_SERVER_PASSWORD']));
      $this->db['DB_DATABASE'] = trim(stripslashes($_POST['DB_DATABASE']));
      $this->db['DB_TABLE_PREFIX'] = trim($_POST['DB_TABLE_PREFIX']);
  }

  /**
    Calcul Cookies, domain
  */
  public function  get_server_conf($path_install='install'){
    $this->ws_document_root=$this->cookie_path = substr(dirname(getenv('SCRIPT_NAME')), 0, -strlen($path_install));
//     $this->fs_document_root=substr(dirname(__FILE__), 0, -strlen('includes/'.$path_install.basename(__FILE__)));
    $this->cookie_domain =getenv('HTTP_HOST');
    $www_location = 'http://' . getenv('HTTP_HOST') . getenv('SCRIPT_NAME');
    $this->www_location = substr($www_location, 0, strpos($www_location, $path_install));
    $this->https_www_address = str_replace('http://', 'https://', $this->www_location);
    $this->ws_admin_rand=(!isset($_POST['WS_STORE_ADMIN'])? 'admin'.rand(10,1000) :$_POST['WS_STORE_ADMIN']) ;

    $this->get_fs_document_root();
  }

  /**
    Calcul racine doc
  */
  public function get_fs_document_root($path_install='install'){
    $dir_fs_document_root = ((!isset($_POST['DIR_FS_DOCUMENT_ROOT']))? substr(dirname($_SERVER['SCRIPT_FILENAME']),0, -strlen($path_install) ): $_POST['DIR_FS_DOCUMENT_ROOT'] );
    if (substr($dir_fs_document_root, -1) != '/')  {
      $where = strrpos($dir_fs_document_root, '\\');
      if (is_string($where) && !$where)  $dir_fs_document_root .= '/';
      else  $dir_fs_document_root .= '\\';
    }
    $this->fs_document_root=$dir_fs_document_root;
  }

  /**
    Repost Post
  */
  function repet_post(){
    reset($_POST);
    while (list($key, $value) = each($_POST)) {
      if (!in_array($key,array('DB_TEST_CONNECTION','DC_LOADER_LANG','submit') )) {
        if (is_array($value)) {
          foreach($value as $k=>$v){
            echo "<p>".osc_draw_hidden_field($key . '['.$k.']', '', $v)."</p>\n";
          }
        } else {
          echo "<p>".osc_draw_hidden_field($key, '', $value)."</p>\n";
        }
      }
    }
    echo "<p>".osc_draw_hidden_field('current_e', '', @$_GET['etape'])."</p>\n";
  }

  /**
    Mise en Pile des messages
  */
  function PileMessage($level,$title='',$lines=array()) {
    $this->Pile[]=array(  'level'=>$level,
              'title'=>$title,
              'line'=>$lines
            );
  }

  /**
    Sortie Message
  */
  function writeMessage() {
    global $install;
    if(count($this->Pile)==0) return ;
    echo '<div class="msg">'."\n";
    foreach ($this->Pile as $item) {
      if(isset($item['title']))echo '<span class="'.@$item['level'].'">'.$item['title'].'</span>'."\n";
      if(isset($item['lines']) && is_array($item['lines'])){
        echo '<p class="msg '.$level.'">'."\n";
        foreach ($item['lines'] as $line) echo $line.'<br />'."\n";
        echo '</p>'."\n";
      }
    }
    echo '</div>'."\n";
  }

  /**
    Browse repertoire
    @param string path du rep
    @param array tableau pour sort
  */
  public static function browse_rep($open,$orderby=array()){
    if(!is_dir($open))return array();
    $fichier=opendir($open);
    $res=array();
    $count=0;
    while($file = readdir($fichier)){
      if(!in_array($file, array(".","..")) && !is_dir($file)){
	$count++;
	$name=substr($file, 0,-4);
	$res[(isset($orderby[$name])?$orderby[$name] : $count)]=
	    array('file'=>$file,
		  'name'=>$name,
		  'count'=>$count
		  );

      }
    }
    closedir($fichier);
    ksort($res);
    return $res;
  }

  /**
    Test presence configure courant
    NE charge que le fichier du FO !
  */
  public function update_shop(){
    $this->get_server_conf();
    if(file_exists($this->fs_document_root.'includes/configure.php')){
      include($this->fs_document_root.'includes/configure.php');
      $_POST['install']['modes']='update';
      $_POST['DB_SERVER']=DB_SERVER;
      $_POST['DB_SERVER_USERNAME']=DB_SERVER_USERNAME;
      $_POST['DB_SERVER_PASSWORD']=DB_SERVER_PASSWORD;
      $_POST['DB_DATABASE']=DB_DATABASE;
      $_POST['DB_TABLE_PREFIX']=DB_TABLE_PREFIX;
      $_POST['DB_TABLE_PREFIX']=DB_TABLE_PREFIX;
      $_POST['USE_PCONNECT']=USE_PCONNECT;
      $_POST['STORE_SESSIONS']=(STORE_SESSIONS =='mysql')? 'mysql' : 'files';
      $_POST['ENABLE_SSL']=(ENABLE_SSL =='true') ?'true' : false;

      return true;
    }
    return false;
  }

  /**
    Construction Liste des etapes
    @param
      @a string $_GET['etape']
  */
  private function draw_etape(){

    echo '<div id="stepList">'."\n".'<ol id="step">'."\n";
      foreach(core::browse_rep('includes/content/',$this->order_etape ) as $k=>$element){
	if(isset($this->order_etape[$element['name']]) ){
	  if(isset($_GET['etape']) && $_GET['etape']>$k)$class =  'class="finished"';
	  elseif(( isset($_GET['etape']) && $_GET['etape']==$k) || (!isset($_GET['etape']) && $k==1) )$class =  'class="selected"';
	  else $class='';

	  echo "<li $class>".core::l10n('etape '.$element['name']).'</li>'."\n";
	}
      }
    echo '</ol>'."\n".'</div>'."\n";
  }

  /**
    Sortie button + passage hidden permanent
  */
  public function draw_button($bloque_prev=false, $bloque_next=false){
    $s='';
    if(defined('DC_LOADER_LANG')) $s .='<p>'.osc_draw_hidden_field('DC_LOADER_LANG', '', DC_LOADER_LANG).'</p>'."\n";
    $s .='<p id="bt">'."\n";
    if(!$bloque_prev)$s .='<input type="button" id="backBt" class="submitBt" name="backBt" value="'.core::l10n('Précédent').'" onclick="javascript: history.go(-1)" />'."\n";
    if(!$bloque_next)$s .='<input type="submit" id="nextBt" class="submitBt" name="nextBt" value="'.core::l10n('Suivant').'" />'."\n";
    $s .='</p>'."\n";
    return $s;
  }

  /**
    Return current etape id
    @param bool true = etape id +1
  */
  public function get_current_etape($inc=''){
    $num=(!isset($_GET['etape']))? '1' : (!is_numeric($_GET['etape']) ? $this->order_etape['core.'.$_GET['etape']] :$_GET['etape'] ) ;
    return (($inc =='')? $num : ((int)$num+(int)$inc));
  }

  /**
    Callback
    @param int $etape
  */
  public function exe_callback($etape){
    if($etape==0) return;
    $tab=array_flip($this->order_etape);
    $class=(!isset($etape))? 'base' : (is_numeric($etape) ? substr($tab[$etape],5) :$etape ) ;
    if(!class_exists($class)) require('includes/content/core.'.$class.'.php');

    $etape= new $class();
    if(!method_exists($etape,'exe_prev'))return;
    if(call_user_func(array($etape,'exe_prev')))    return $etape->exe_prev();

  }

  /**
    Construction de l'aide contextuelle
    @param
      @a string $id
      @a string $longDesc
      [@a string $shortDesc option]
  */
  public static function draw_help($id, $longDesc, $shortDesc=''){

    $s = '<a class="help" href="#"><img src="images/help_icon.png" width="15" height="15" alt="Help" />'."\n";
    if (!empty($shortDesc)) $s .= '<span id="'.$id.'SD" class="shortDescription">'.$shortDesc.'</span>'."\n";
    $s .= '<span id="'.$id.'" class="longDescription">'.$longDesc.'</span></a>';
    return $s;
  }


  public static function team_pub(){
    if(!file_exists('includes/team_info/'.self::$class.'.inc')) return;
    echo  '<div id="team_info"><hr />'."\n";
	     include('includes/team_info/'.self::$class.'.inc');
    echo '</div>'."\n";

  }

  /**
  */
  public static function block_etape() {
    if(!isset($_POST)) header('Location: index.php' );
  }

  /**
    Construction de la page
    @param
      @a string $_GET['etape']
  */
  public function draw_page(){

    $this->getLanguage();
    $tab=array_flip($this->order_etape);
    $class=(!isset($_GET['etape']))? 'base' : (is_numeric($_GET['etape']) ? substr($tab[$_GET['etape']],5) :$_GET['etape'] ) ;
    require('includes/content/core.'.$class.'.php');
    self::$class=$class;
    $etape= new $class();

    $this->get_fs_document_root();
    $this->get_server_conf();

    /**
      execute element etape precedente
    */
    $dec=(isset($_POST['current_e']) ? ((int)$_POST['current_e']) : 1);
    if(!isset($_GET['upgrade'])) $this->exe_callback(( ( ($this->get_current_etape()- $dec) >1) ? $this->get_current_etape() - $dec -1: $this->get_current_etape() -1 ) );

    include('templates/header.php');
    echo '<h1 id="title">'.core::l10n('Welcome to osCSS-2 install!').'</h1>'."\n";
      // list des etape
      $etape->draw_etape();
    echo '<div id="content">'."\n";
      // content
      $etape->draw();

      self::team_pub();
    // message
    $this->writeMessage();
    echo '</div>'."\n";
    include('templates/footer.php');
  }


}
?>
