<?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:20
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @modified Ayatus <www http://www.ayatus.org>
  @encode UTF-8
  @class update
    Prise en charge recup version courante svn / par rapport revision enregitré
    Utilise l'exporte n zip de trac
*/

define('URL_OSCSS_ORG_TRAC', 'http://sourceforge.net/apps/trac/oscss/changeset/?format=zip&new=SVN_REV_MAX&old=SVN_REV&new_path=branches%2F2.1.0%2Fcatalog&old_path=branches%2F2.1.0%2Fcatalog');
define('URL_OSCSS_GET_REV', 'http://oscss.svn.sourceforge.net/viewvc/oscss?view=revision');

define('PATH_SVN_BRANCHE', 'branches/2.1.0/catalog/');
define('FILEPATH_SVN_CORE', 'common/oscss.version.xml');

class update extends core {


  /**
  */
  private function fetchRemote($src,&$dest,$step=0) {
      if ($step > 3) return false;

      // Try curl to read remote file
      if (function_exists('curl_init')) {
        $ch = @curl_init();
        @curl_setopt($ch, CURLOPT_URL, $src);
        @curl_setopt($ch, CURLOPT_HEADER, 0);
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        @curl_setopt($ch, CURLOPT_USERAGENT, 'osCSS-2 Net Install');
        $content = @curl_exec($ch);
        @curl_close($ch);
        if ($content !== false) {
          $this->write_dest($content, $dest);
          return true;
        }
      }

      // Try file_get_contents to read remote file
      if ((boolean)ini_get('allow_url_fopen')) {
        $content = @file_get_contents($src);
        if ($content !== false) {
          $this->write_dest($content, $dest);
          return true;
        }
      }

      // Try fsockopen to read remote file
      $src = parse_url($src);
      $host = $src['host'];
      $path = $src['path'];

      if (($s = @fsockopen($host,80,$errno,$errstr,5)) === false) {
        return false;
      }

      fwrite($s,
          'GET '.$path." HTTP/1.0\r\n"
          .'Host: '.$host."\r\n"
          ."User-Agent: osCSS-2 Svn upadte \r\n"
          ."Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*\r\n"
          ."\r\n"
      );

      $i = 0;
      $in_content = false;
      while (!feof($s)) {
        $line = fgets($s,4096);

        if (rtrim($line,"\r\n") == '' && !$in_content)  {
          $in_content = true;
          $i++;
          continue;
        }
        if ($i == 0) {
          if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/',rtrim($line,"\r\n"), $m)) {
        fclose($s);
        return false;
          }
          $status = (integer) $m[2];
          if ($status < 200 || $status >= 400) {
        fclose($s);
        return false;
          }
        }
        if (!$in_content) {
          if (preg_match('/Location:\s+?(.+)$/',rtrim($line,"\r\n"),$m)) {
        fclose($s);
        return $this->fetchRemote(trim($m[1]),$dest,$step+1);
          }
          $i++;
          continue;
        }
        $this->write_dest($line, $dest);
        $i++;
      }
      fclose($s);
      return true;
  }

  /**
    Recuperation des element de svn basé sur le fichier oscss.version.xml
    @package oscss-2 <www http://www.oscss.org>
    @date  15/05/10, 16:19
    @author oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
  */
  private function get_info_core($file,$name='svn'){
    if(!file_exists($file)) return $this->PileMessage('alert', core::l10n("Erreur récupération fichier") );
    $SimpleParser = simplexml_load_file($file);
    if(!isset($SimpleParser->$name)) $this->PileMessage('alert', core::l10n("Erreur récupération n° révision courant") );
    else return $SimpleParser->$name;
  }


  /**
    Recup current version svn, basé sur ViewVC fournis pas Sourceforge , vieVC 1.0.5
    @package oscss-2 <www http://www.oscss.org>
    @date  15/05/10, 16:19
    @author oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
  */
  private function get_current_rev($src) {
    if (function_exists('curl_init')) {
      $ch = @curl_init();
      @curl_setopt($ch, CURLOPT_URL, $src);
      @curl_setopt($ch, CURLOPT_HEADER, 0);
      @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      @curl_setopt($ch, CURLOPT_USERAGENT, 'osCSS-2 Net Install');
      $content = @curl_exec($ch);
      @curl_close($ch);
      if ($content !== false){
		preg_match("#.oscss..Revision.([0-9]*).*#i",strip_tags($content),$val );
		if(is_numeric($val[1])) return $val[1];
      }
      else return false;
    }
    elseif (($content = @file_get_contents($src)) != false) {

      preg_match("#.oscss..Revision.([0-9]*).*#i",strip_tags($content),$val );
      if(is_numeric($val[1])) return $val[1];
      else return false;
    }
    else return false;
  }


  /**
  */
  static private function write_dest($str, &$dest) {
    if (is_resource($dest)) fwrite($dest, $str);
    else $dest .= $str;
  }


  /**
    Callback
  */
  public function exe_prev(){
    $this->get_fs_document_root();
    $this->get_server_conf();

    if(isset($_POST['USE_SVN']) && $_POST['USE_SVN'] =='on') {

      // recup version svn core
      $corre_rev=$this->get_info_core($this->fs_document_root.FILEPATH_SVN_CORE);
      // version current svn
      $c_v=$this->get_current_rev(URL_OSCSS_GET_REV);
      $curent_rev=((isset($_POST['CURENT_REV']) && $c_v != $_POST['CURENT_REV'])? $_POST['CURENT_REV']: $c_v);

      if((int)$corre_rev>=(int)$curent_rev) {
	$this->PileMessage('succes', core::l10n("Aucune mise à jour effectuée. pas de version plus récente") );
	return;
      }
      osc_set_time_limit(0);
      $file=$this->fs_document_root.'install/old'.$corre_rev.'new'.$curent_rev.'_patch.zip';
      $oscss_zip = @fopen($file,'wb');
      // recup zip
      $tp=@file_get_contents(str_replace( array('SVN_REV_MAX', 'SVN_REV'), array($curent_rev, $corre_rev), URL_OSCSS_ORG_TRAC));
      fputs( $oscss_zip,$tp);
      fclose($oscss_zip);
      if ($file!=false)  $this->PileMessage('succes', core::l10n("Le fichier à été enregistré") ) ;
      else  $this->PileMessage('alert', core::l10n("Le fichier n'as pas été enregistré") ) ;

      // add img sample
      sleep(1);
      tep_zip_extractto( $file,'../');

      // remplacement fichier de version
      $tmp='<?xml version="1.0" encoding="utf-8"?>'."\n".
        '<core>'."\n".
          '<version>'.$this->get_info_core($this->fs_document_root.FILEPATH_SVN_CORE, 'version').'(dev)</version>'."\n".
          '<svn>'.$curent_rev.'</svn>'."\n".
        '</core>'."\n";
      $file_vers= @fopen($this->fs_document_root.FILEPATH_SVN_CORE,'w');
      fputs( $file_vers,$tmp); //$this->write_dest($tmp, $file_vers);
      fclose($file_vers);

      // report branche dans le core
      if(file_exists($this->fs_document_root.PATH_SVN_BRANCHE)){
	$this->recurse_copy($this->fs_document_root.PATH_SVN_BRANCHE,$this->fs_document_root);
	$this->recurse_delete($this->fs_document_root.'branches/');
      }
      // deplacement admin
      if(file_exists($this->fs_document_root.'admin')){
	$this->recurse_copy($this->fs_document_root.'admin',$this->fs_document_root.$this->ws_admin_rand);
	if($this->ws_admin_rand !='admin')$this->recurse_delete($this->fs_document_root.'admin/');
      }
    }
  }

  /**
  */
  function draw_form(){
    $this->writeMessage();
    echo '<h2>'.core::l10n("Version svn(développement) de osCSS-2 " ).'</h2>'."\n";
    echo '<p>'.core::l10n("Les  version svn contienent les dernières correction et mise à jour. Les revisions sont calculé sur votre version, et, en dehors des beta, vous devriez utiliser cette option. L'ecart entre les versions signifie qu'aucun paquet n'as été proposé depuis, et donc souligne qu'il s'agit de revision et correction mineure " )."\n" .'</p><br/>'."\n";
    echo '<p>'.core::l10n("Version svn actuelle: " )."\n"
        .$this->get_info_core($this->fs_document_root.FILEPATH_SVN_CORE)."\n"
        .'</p>'."\n";
    echo '<form id="install" action="?etape='.( (isset($_POST['install']['modes'])&& $_POST['install']['modes'] == 'install')? $this->get_current_etape(1) : $this->get_current_etape(2) ).'" method="post">'."\n";
    $this->repet_post();
    if((int)$this->get_current_rev(URL_OSCSS_GET_REV) > (int)$this->get_info_core($this->fs_document_root.FILEPATH_SVN_CORE) ){
      echo '<p class="smallDesc">'."\n"
	  .'<label>'.core::l10n('Récupérer le patch de la version courante du dépôt subversion').'</label>'."\n"
	  .osc_draw_checkbox_field('USE_SVN')."\n"
	  .core::draw_help('patchsvn', core::l10n("Patcher votre shop avec les dernières modification du svn"))."\n"
	  .'</p>'."\n";

      echo '<p class="smallDesc">'."\n"
	  .'<label>'.core::l10n('Revision N° precis :').'</label>'."\n"
	  .osc_draw_input_field('CURENT_REV', '', $this->get_current_rev(URL_OSCSS_GET_REV) )."\n"
	  .core::draw_help('revsvn', core::l10n("Le numéro de révision svn (basé sur :https://oscss.svn.sourceforge.net/svnroot/oscss )pour patcher votre shop "))."\n"
	  .'</p>'."\n";
    }

    echo $this->draw_button();
    echo '</form>'."\n";
  }

  /**
  */
  function draw(){
    // conf
    $this->get_fs_document_root();
    $this->get_server_conf();

    $this->draw_form();
  }
}

?>