<?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  08/02/11, 15:04
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class packageInstaller
*/
if(!class_exists('package')) include_once(DIR_WS_MODULES .'pages/package.php');


class packageInstaller
  extends package {

  public function __construct(){

    define('DB_PREFIX', DB_TABLE_PREFIX);
    define('PATH_ADMIN', substr(DIR_WS_ADMIN,strlen(DIR_WS_CATALOG)));

    if(!tep_class_exists('exts_package_CIP')) parent::$Rightlist[]='Class cip no founs';
  }

  /**
    Recup du package distant
  */
  public function download_exts($pkgID){
    global $messageStack;

    $obj=parent::load_db_values($pkgID);
    $obj=$obj[0];

    if((string)$obj->item->sourceTitle =='local'){
      $cip= new CIP( (string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip');
      tep_redirect(tep_href_link(self::FILENAME, 'action=view&pkgID='.(int)$obj->item->internalID ));
    }
    else {
      $dest=fopen(DIR_FS_CIP.(string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip',"wb");

      if($this->fetchRemote((string)$obj->item->url_src,$dest)) {
	$messageStack->add_session('good', 'succes');
	fclose($dest);

	$cip= new CIP( (string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip');
	tep_redirect(tep_href_link(self::FILENAME, 'action=view&pkgID='.$pkgID));
      }
      else{
	$messageStack->add_session('error recup zip url ', 'error');
	tep_redirect(tep_href_link(self::FILENAME));
      }
    }
  }


  /**
    View et check package
  */
  public function view_exts($pkgID){
    global $messageStack;

    //! retro compatibilite
    $message=$messageStack;

    $obj=parent::load_db_values($pkgID);
    $obj=$obj[0];

    $cip= new CIP( (string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip');

    $cip->read_xml();

    if($cip->get_count_php_tags()) {
      parent::$Rightlist['get_count_php_tags']= CIP_USES.' &#060;<strong>php</strong>&#062 ('.$cip->get_count_php_tags().')!';
    }

    //Print description:
    $description=$cip->get_data($cip->get_description_id());
    if ($description) {
	$array=$this->cip_description($description->data);
	parent::$Rightlist=array_merge(parent::$Rightlist,ErrorAndBlockProcess::$ArrayError);
    }
    else $array[]= '<strong style="color:red;">'.CIP::CONFIG_FILENAME. __('text doesnt exists').'!!!</strong>';



    $s ='<div class="button_nav">';
    if($cip->check_bylevel(1)) $s .='<a class="button ActionYes" href="'.tep_href_link(parent::FILENAME,'action=install&amp;pkgID='.$pkgID).'" title="'.__('icon install').'"> '.__('image cip install').'</a>';
    $s .=tep_js_back(tep_href_link(parent::FILENAME), IMAGE_CANCEL).
	  '</div>';
    $array[]=$s;

    return $array;
  }

  public function install_exts($pkgID){
    global $messageStack;

    $array=array();
    //! retro compatibilite
    $message=$messageStack;

    $obj=parent::load_db_values($pkgID);
    $obj=$obj[0];
    $cip= new CIP( (string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip');

    $cip->install();
    if (ErrorAndBlockProcess::$error) $messageStack->add('error in process install', 'error');
    else $messageStack->add(__('msg was installed'), 'installed');

    //! Show post install message:
    if ($cip->post_install_notes()) {
      $array[]=	'<h4>'.$cip->getIdent().'<h4>'.
		'<strong>'.__('text post install notes').':</strong><br />'.
		$cip->post_install_notes();
    }

    $cips = $cip->getDependedCips($cip);

    if (is_array($cips) and count($cips)>0 ){
      foreach($cips as $cp){
        $cp->compute_dependencies();
        if ($cp->get_error()) {
	  parent::$Rightlist=array_merge(parent::$Rightlist,ErrorAndBlockProcess::$ArrayError);
	  return $array;
	}
	$messageStack->add_session("CIP ".$cp->getIdent().__('msg was applied'), 'installed');
        $array[]= '<h4>'.$cp->getIdent().'<h4>'.
		  '<strong>'.__('text post install notes').':</strong><br />'.
		  $cp->post_install_notes();
      }
    }
    $array=array_merge($array,(array)ErrorAndBlockProcess::$ArrayError);

    /// NOTE: force init menu admin
      $menu=menu::getInstance();
      $menu->cstr_return(array('for_user'=>'1'));

    $array[]='<div class="button_nav">'.
	      '<a class="button ActionYes" href="'.tep_href_link(parent::FILENAME,'action=config&class='.(string)$obj->item->ident).'" >'.__('config extension').'</a> '.
	      tep_js_back(tep_href_link(parent::FILENAME), IMAGE_CANCEL).
	     '</div>';

    return $array;

  }


  public function remove_exts($pkgID){
    global $messageStack;

    //! retro compatibilite
    $message=$messageStack;

    $array=array();

    $obj=parent::load_db_values($pkgID);
    $obj=$obj[0];
    $cip= new CIP( (string)$obj->item->ident.'_'.(string)$obj->item->level.'.zip');


    $res=$cip->remove();


//     if ($cip->get_error())

    if(!$cip->check_bylevel(1)){
      parent::$Rightlist=array_merge(parent::$Rightlist,ErrorAndBlockProcess::$ArrayError);
      return $array;
    }

    $array[]=__('msg was removed');

//     $cips = $cip->getDependedCips();
//     if (is_array($cips) and count($cips)>0 ){
//       foreach($cips as $cp){
//         $cp->compute_dependencies();
//         if ($cp->get_error())     return ErrorAndBlockProcess::$ArrayError;
//         $array[]="CIP ".$cp->getIdent().__('msg was applied');
//       }
//     }
//     unlink(DIR_FS_CIP.$var['pkg'].'_'.$var['level'].'.zip');

    $cip->unregister();
//     ci_remove(DIR_FS_CIP.'/'.$this->cip);
//     if (is_dir(DIR_FS_CIP.'/'.$this->cip)) {
//         $message->add(ci_remove(DIR_FS_CIP.'/'.$this->cip));
//     } else {
//         $message->add("Couldn't remove ".DIR_FS_CIP.'/'.$this->cip);
//     }

    $array[]='<div class="button_nav">'.
	      tep_js_back(tep_href_link(parent::FILENAME), IMAGE_CANCEL).
	     '</div>';
    return $array;
  }


  /**
  */
  private function cip_description($data='') {
    if (!$data)    return null;
    $contents =  array();

    $contents[] = '<h3>'.__('text info support').':</h3>';
    if (isset($data['oscss_forum_ref']) && $data['oscss_forum_ref'] !=0)
      $contents[]='<strong>&#8226;&nbsp;<a href="'.__('text link contr oscss') . $data['oscss_forum_ref'].'" title= "'. __('contribs page oscss alt') . '">' . __('contribs page oscss') .'</a></strong>';

    if (isset($data['contrib_ref']) && $data['contrib_ref'] !=0)
      $contents[]='<strong>&#8226;&nbsp;<a href="'. __('text link contr '). $data['contrib_ref'].'" title= "'. __('contribs page alt') . '">' . __('contribs page').'</a></strong>';

    if (isset($data['forum_ref']) && $data['forum_ref'] !=0)
      $contents[]='<strong>&#8226;&nbsp;<a href="'. __('text link forum').$data['forum_ref']. '" title="'. __('contribs forum alt'). '">'. __('contribs forum').'</a></strong>';

    if (isset($data['author_pkg']) && $data['author_pkg'] !='')
	$contents[]='<strong>&#8226;&nbsp;<a href="http://'. $data['author_pkg'].'">' . __('contribs cip pkg'). $data['author_pkg'] .'</a></strong>';

    $contents[] =  '<br /><h3>'.__('text info contrib').':</h3>';

    foreach ($data as $key=>$value) {
        $value=htmlspecialchars($value);//convert to entries...
        if (!in_array($key,array('post_install_notes','author_pkg','contrib_ref','forum_ref','oscss_forum_ref'))) {
              $contents[]='<strong>'.$key.'</strong>: '.nl2br($value);
        }
    }
    return $contents;
  }

  /**
  */
  private function fetchRemote($src,&$dest,$step=0) {

      if (($content=fileUtility::url_fopen($src)) ==false) return false;
      else $this->write_dest($content, $dest);

      return true;

  }

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

}


?>