<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @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  19/12/10, 09:26
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class fileUtility
*/
class fileUtility {

  public static $GError=array();

  private static $Comport=false;

  /**
    Collecteur error
  */
  private static function ComportForError( $text,$error='error'){
    global $messageStack;
    self::$GError[]=array($text,$error);

    if(!self::$Comport)$messageStack->add( $text, $error);
  }

  /**
    @param bool true, block messageSatck
  */
  public static function CfgComport($value){
    self::$Comport=(bool)$value;
  }

  /**
    @return array error
  */
  public static function GetError(){
    return self::$GError;
  }

  /**
    @package oscss
    @author OscssTeam
  */
  public static function get_file_permissions($mode) {
  // determine type
    if ( ($mode & 0xC000) == 0xC000) $type = 's'; // unix domain socket
    elseif ( ($mode & 0x4000) == 0x4000)  $type = 'd'; // directory
    elseif ( ($mode & 0xA000) == 0xA000) $type = 'l'; // symbolic link
    elseif ( ($mode & 0x8000) == 0x8000)  $type = '-'; // regular file
    elseif ( ($mode & 0x6000) == 0x6000) $type = 'b'; //bBlock special file
    elseif ( ($mode & 0x2000) == 0x2000) $type = 'c'; // character special file
    elseif ( ($mode & 0x1000) == 0x1000) $type = 'p'; // named pipe
    else  $type = '?'; // unknown

  // determine permissions
    $owner['read']    = ($mode & 00400) ? 'r' : '-';
    $owner['write']   = ($mode & 00200) ? 'w' : '-';
    $owner['execute'] = ($mode & 00100) ? 'x' : '-';
    $group['read']    = ($mode & 00040) ? 'r' : '-';
    $group['write']   = ($mode & 00020) ? 'w' : '-';
    $group['execute'] = ($mode & 00010) ? 'x' : '-';
    $world['read']    = ($mode & 00004) ? 'r' : '-';
    $world['write']   = ($mode & 00002) ? 'w' : '-';
    $world['execute'] = ($mode & 00001) ? 'x' : '-';

  // adjust for SUID, SGID and sticky bit
    if ($mode & 0x800 ) $owner['execute'] = ($owner['execute'] == 'x') ? 's' : 'S';
    if ($mode & 0x400 ) $group['execute'] = ($group['execute'] == 'x') ? 's' : 'S';
    if ($mode & 0x200 ) $world['execute'] = ($world['execute'] == 'x') ? 't' : 'T';

    return $type .
	    $owner['read'] . $owner['write'] . $owner['execute'] .
	    $group['read'] . $group['write'] . $group['execute'] .
	    $world['read'] . $world['write'] . $world['execute'];
  }


  /**
    @package oscss
    @author  OscssTeam
    @param string path element a supprimer
  */
  public static function _rmdir($source) {
    global $messageStack, $tep_remove_error;

    if (isset($tep_remove_error)) $tep_remove_error = false;
    if (is_dir($source)) {
      while ($file = self::_scandir($source)) {
	if ( ($file != '.') && ($file != '..') ) {
	  if (is_writeable($source . '/' . $file)) self::_rmdir($source . '/' . $file);
	  else {
	    self::ComportForError(__CLASS__.'->'.__FUNCTION__.'::'.__LINE__.__('error file not removeable'). $source . '/' . $file, 'error');
	   return false;
	  }
	}
      }
      if (is_writeable($source)) rmdir($source);
      else {
	 self::ComportForError(__CLASS__.'->'.__FUNCTION__.'::'.__LINE__.__('error directory not removeable'). $source, 'error');
	return false;
      }
    }
    else $tep_remove_error =  self::_unlink($source);
    return $tep_remove_error;
  }


  public static function _unlink($source){
    if (is_writeable($source)) return unlink($source);
    else  self::ComportForError(__CLASS__.'->'.__FUNCTION__.'::'.__LINE__.__('error file not removeable'). $source, 'error');
    return false;
  }

  /**
  */
  public static function _mkdir($path, $mod=0777) {
    if (!file_exists($path)) {
      if (is_dir($path))self::_chmod($path);
      else {
	self::_mkdir(dirname($path));
	if (!is_writeable(dirname($path))) {
	 self::ComportForError(__CLASS__.'->'.__FUNCTION__.'::'.__LINE__.__('error file not removeable'). $source, 'error');
	  return false;
	}
	if(!@mkdir($path, $mod)) {
	 self::ComportForError(__CLASS__.'->'.__FUNCTION__.'::'.__LINE__.__("cant create dir text"), 'error');
	  return false;
	}
	self::_chmod($path);
      }
    }
    return true;
  }

  /**
    @fn _chmod($path, $mod=0777)
  */
  public static function _chmod($path, $mod=0777) {
    $path=(substr($path,0, strlen(DIR_FS_ADMIN)) == DIR_FS_ADMIN)? $path : DIR_FS_ADMIN.$path;
    if (is_dir($path) && $path!='/') {
      self::_chmod(dirname($path));
      if(!@chmod($path, $mod)) return false;
    }
    elseif(file_exists($path) && $path!='/') {
      if(!@chmod($path, $mod)) return false;
    }
    return true;
  }

  /**
  */
  public static function _chown($mypath, $uid, $gid) {
    while(($file =self::_scandir($d)) !== false) {
      if ($file != "." && $file != "..") {
	  $typepath = $mypath . "/" . $file ;
	  if (filetype ($typepath) == 'dir') self::_chown($typepath, $uid, $gid);
	  self::_chmod($typepath, $uid);
	  chgrp($typepath, $gid);
      }
    }
  }

  /**
    @fn _copy($src,$dst)
    @brief Copy repertoire recursif
  */
  public static function _copy($src,$dst){
//     self::_chmod($dst);

    if(!is_dir($src)) return @copy($src,$dst);
    else {
      while(( $file = self::_scandir($src)) && $file !==false ) {
	if (( $file != '.' ) && ( $file != '..' )) {
	  if ( is_dir($src . '/' . $file) ) {
	    self::_copy($src . '/' . $file,$dst . '/' . $file);
	  }
	  else {
	    copy($src . '/' . $file,$dst . '/' . $file);
	  }
	}
      }
      return true;
    }
  }

  /**
    @fn _scandir($strFolder)
    @brief Scan a directory and return its files and folders as array
    @original-code TYPOlight Open Source CMS Copyright (C) 2005-2010 Leo Feyer
    @param string
    @return array
  */
  public static function _scandir($strFolder) {
    $arrScanCache=array();
    static $arrScanCache;
    if (substr($strFolder, -1, 1) != '/') $strFolder .= '/';

    // Load from cache
    if (isset($arrScanCache[$strFolder]))  return $arrScanCache[$strFolder];

    $arrReturn = array();
    // Scan directory
    foreach (scandir($strFolder) as $strFile) {
      if ($strFile == '.' || $strFile == '..') continue;
      $arrReturn[] = $strFile;
    }

    $arrScanCache[$strFolder] = $arrReturn;
    return $arrReturn;
  }

  /**
    Checksum 2 files
    @return bool
  */
  public static function equal_files($file1, $file2) {
    if (is_file($file1) && is_file($file2))  return (md5_file($file1) == md5_file($file2));
    return false;
  }

  /**
  */
  public static function compress_dir($directory, $file_in, $ext='zip', $delete_file = false, $level = 6) {
    switch ($ext) {
      case 'zip':
      case 'gz':
	$in_file = $directory . $file_in;
	$out_file = $directory . $file_in . '.gz';
	if (!file_exists ($in_file) || !is_readable ($in_file))return false;

	if (file_exists($out_file)) return false;

	$fin_file = fopen($in_file, "rb");
	if (!$fout_file = gzopen($out_file, "wb".$level)) return false;

	while (!feof ($fin_file)) {
	    $buffer = fread($fin_file, 8192); // 8 kB is maximum value
		    gzwrite($fout_file, $buffer, 8192);
	}

	fclose($fin_file);
	gzclose($fout_file);
	if ($delete_file == true) {
	  unlink($in_file);
	}
      break;
    }
    return true;
  }


  /**
    @package oscss
    @author oscim - OscssTeam
    @version 1.2
    Control la présence d'une constante de langue en remplacement de l'intitulé des menu de l'admin. Si cette constante n'est pas défini, une alerte est produite
    ne préciser que le contenu de la colonne key
  */
   public static function extractto($archive, $destination,$ext='zip') {
    switch ($ext) {
      case 'zip':
      if(function_exists("zip_open")) {
	require_once(DIR_WS_FUNCTIONS.'unzip.php');
	return unzip($archive, $destination);
      } else {
	$archive = new PclZip($archive);
	if ($archive->extract(PCLZIP_OPT_PATH, $destination, PCLZIP_OPT_REMOVE_PATH, 'tmp') == 0)return false;
      }
      break;
      case 'tbz':
      case 'tbz2':
      case 'bz2':
      case 'bz':
//         if(CI_ARCHIVER_BZIP2)    @ exec(CI_ARCHIVER_BZIP2.' '.$this->full_path_to_zip().' -d > '. DIR_FS_CIP.'/'.self::$cip_name, $output);
      break;
      case 'gz':
//         if(CI_ARCHIVER_GUNZIP)    @ exec(CI_ARCHIVER_GUNZIP.' '.$this->full_path_to_zip() .' -c > '. DIR_FS_CIP.'/'.self::$cip_name, $output);
      break;
    }
      return true;
  }

  /**
    read remote file
  */
  public static function url_fopen($src,$timeout=5){
    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');
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      $content = @curl_exec($ch);
      @curl_close($ch);
      if ($content !== false) return $content;
      else return false;
    }

    if ((boolean)ini_get('allow_url_fopen')) {
      // Create the stream context
      $context = stream_context_create(array(
	  'http' => array(
	      'timeout' => $timeout      // Timeout in seconds
	  )
      ));
      $content = @file_get_contents($src, 0, $context);
      if ($content !== false) return $content;
      else return false;
    }

    return false;
  }
}
?>