<?php
error_reporting(0);
/**
 * The Unzipper extracts .zip or .rar archives and .gz files on webservers.
 * It's handy if you do not have shell access. E.g. if you want to upload a lot
 * of files (php framework or image collection) as an archive to save time.
 * As of version 0.1.0 it also supports creating archives.
 *
 * @author  Andreas Tasch, at[tec], attec.at
 * @license GNU GPL v3
 * @package attec.toolbox
 * @version 0.1.1
 */
define('VERSION', '0.1.1');

$timestart = microtime(TRUE);
$GLOBALS['status'] = array();

$unzipper = new Unzipper;
if (isset($_POST['dounzip'])) {
    
    $lis = mysqli_real_escape_string($con,$_POST['lis']);
    IF($lis==$lisensi){
      $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
      $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
      $unzipper->prepareExtraction($archive, $destination);
    }else{
      echo '
      <script>
      swal("Good Job","Kode Lisensi Salah","Error");
      </script>
      ';    
    }       
}

if (isset($_POST['dozip'])) {
  $zippath = !empty($_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
  // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip.
  $zipfile = 'zipper-' . date("Y-m-d--H-i") . '.zip';
  Zipper::zipDir($zippath, $zipfile);
}

$timeend = microtime(TRUE);
$time = round($timeend - $timestart, 4);

/**
 * Class Unzipper
 */
class Unzipper {
  public $localdir = '.';
  public $zipfiles = array();

  public function __construct() {
    if ($dh = opendir($this->localdir)) {
      while (($file = readdir($dh)) !== FALSE) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'zip'
          || pathinfo($file, PATHINFO_EXTENSION) === 'gz'
          || pathinfo($file, PATHINFO_EXTENSION) === 'rar'
        ) {
          $this->zipfiles[] = $file;
        }
      }
      closedir($dh);

      if (!empty($this->zipfiles)) {
        $GLOBALS['status'] = array('info' => 'File Update Auto BiznisTop tersedia. Pilih Update tanggal terakhir');
      }
      else {
        $GLOBALS['status'] = array('info' => 'Tidak ada File .zip. Lakukan upload otomatis.');
      }
    }
  }

  
  public function prepareExtraction($archive, $destination = '') {
    // Determine paths.
    if (empty($destination)) {
      $extpath = $this->localdir;
    }
    else {
      $extpath = $this->localdir . '/' . $destination;
      // Todo: move this to extraction function.
      if (!is_dir($extpath)) {
        mkdir($extpath);
      }
    }
    // Only local existing archives are allowed to be extracted.
    if (in_array($archive, $this->zipfiles)) {
      self::extract($archive, $extpath);
    }
  }

  
  public static function extract($archive, $destination) {
    $ext = pathinfo($archive, PATHINFO_EXTENSION);
    switch ($ext) {
      case 'zip':
        self::extractZipArchive($archive, $destination);
        break;
      case 'gz':
        self::extractGzipFile($archive, $destination);
        break;
      case 'rar':
        self::extractRarArchive($archive, $destination);
        break;
    }

  }

  
  public static function extractZipArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('ZipArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Ektensi zip pada Versi PHP Anda tidak aktif, baca petunjuk diatas cara mengaktifkannya.');
      return;
    }

    $zip = new ZipArchive;

    // Check if archive is readable.
    if ($zip->open($archive) === TRUE) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $zip->extractTo($destination);
        $zip->close();
        $GLOBALS['status'] = array('success' => 'File Update Berhasil diinstal');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Ada problem pada file atau Direktory.');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Tidak dapat dibaca file zip nya.');
    }
  }

  
  public static function extractGzipFile($archive, $destination) {
    // Check if zlib is enabled
    if (!function_exists('gzopen')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
      return;
    }

    $filename = pathinfo($archive, PATHINFO_FILENAME);
    $gzipped = gzopen($archive, "rb");
    $file = fopen($destination . '/' . $filename, "w");

    while ($string = gzread($gzipped, 4096)) {
      fwrite($file, $string, strlen($string));
    }
    gzclose($gzipped);
    fclose($file);

    // Check if file was extracted.
    if (file_exists($destination . '/' . $filename)) {
      $GLOBALS['status'] = array('success' => 'File unzipped successfully.');

      // If we had a tar.gz file, let's extract that tar file.
      if (pathinfo($destination . '/' . $filename, PATHINFO_EXTENSION) == 'tar') {
        $phar = new PharData($destination . '/' . $filename);
        if ($phar->extractTo($destination)) {
          $GLOBALS['status'] = array('success' => 'Extracted tar.gz archive successfully.');
          // Delete .tar.
          unlink($destination . '/' . $filename);
        }
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error unzipping file.');
    }

  }

  
  public static function extractRarArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('RarArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support .rar archive functionality. <a class="info" href="http://php.net/manual/en/rar.installation.php" target="_blank">How to install RarArchive</a>');
      return;
    }
    // Check if archive is readable.
    if ($rar = RarArchive::open($archive)) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $entries = $rar->getEntries();
        foreach ($entries as $entry) {
          $entry->extract($destination);
        }
        $rar->close();
        $GLOBALS['status'] = array('success' => 'Files extracted successfully.');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive.');
    }
  }

}


class Zipper {
 
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);

    while (FALSE !== $f = readdir($handle)) {
      // Check for local/parent path or zipping file itself and skip.
      if ($f != '.' && $f != '..' && $f != basename(__FILE__)) {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);

        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        }
        elseif (is_dir($filePath)) {
          // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  
  public static function zipDir($sourcePath, $outZipPath) {
    $pathInfo = pathinfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];

    $z = new ZipArchive();
    $z->open($outZipPath, ZipArchive::CREATE);
    $z->addEmptyDir($dirName);
    if ($sourcePath == $dirName) {
      self::folderToZip($sourcePath, $z, 0);
    }
    else {
      self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    }
    $z->close();

    $GLOBALS['status'] = array('success' => 'Successfully created archive ' . $outZipPath);
  }
}

if (isset($_POST['delzip'])) {
    $zipfile = mysqli_real_escape_string($con,$_POST['zipfile']);
    unlink($zipfile);
    echo '
            <script>
            	swal("Good Job","Berhasil dihapus","success");
            </script>
             <script language="JavaScript">document.location="index.php?page=up"</script>
    		';

} 

if (isset($_POST['upload'])){
    
    $lis = mysqli_real_escape_string($con,$_POST['lis']);
        
        $json_url = 'http://app.biznis.top/member/cekvalid2.php?user='.$lis.'&url='.$weburl;
        $ch = curl_init ($json_url);
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json'),
        );
        curl_setopt_array ($ch, $options); 
        $result = curl_exec($ch); 
        
        $decode = json_decode($result, true);
        foreach ($decode['artikel'] as $row) {
            $userr = $row['user'];
            $urr = $row['url'];
        }    
    
        IF($lis==$lisensi){
            
            $remote = base64_decode('aHR0cHM6Ly95YW50b25haW0ud2ViLmlkL2RlbW9fYXV0by91cGRhdGUuemlw');
            
            $tgl = date("d-m-Y");
            $local_file = 'Upload-'.$tgl.'.zip';
            $copy = copy( $remote, $local_file );
            if( !$copy ) {
                echo '
                    <script>
                    	swal("Good Job","Gagal Upload Otomatis, kemungkinan File Update Belum ada" atau silahkan upload secara manual,"error");
                    </script>
            		';
            }
            else{
                echo '
                    <script>
                    	swal("Good Job","Sukses Upload Otomatis ","Sukses");
                    </script>
                     <script language="JavaScript">document.location="index.php?page=up"</script>
            		';
            } 
        }else{
            echo '
            <script>
                swal("Good Job","Kode Lisensi Salah","error");
                    </script>
            ';    
        }       
}

if (isset($_POST['ubah'])){
    
    If (empty($_FILES["filegbr"]["tmp_name"])){
            echo '
            <script>
            	swal("Good Job","Anda belum memilih file .zip untuk diupload","error");
            </script>
    		';
    		
    } else {    
        
        $lis = mysqli_real_escape_string($con,$_POST['lis']);
        
        $json_url = 'http://app.biznis.top/member/cekvalid2.php?user='.$lis.'&url='.$weburl;
        $ch = curl_init ($json_url);
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json'),
        );
        curl_setopt_array ($ch, $options); 
        $result = curl_exec($ch); 
        
        $decode = json_decode($result, true);
        foreach ($decode['artikel'] as $row) {
            $userr = $row['user'];
            $urr = $row['url'];
        }    
        
        IF($lis==$lisensi){
        
            $ekstensi_diperbolehkan	= array('zip');
			$nama = $_FILES['filegbr']['name'];
			$x = explode('.', $nama);
			$ekstensi = strtolower(end($x));
			$ukuran	= $_FILES['filegbr']['size'];
			$file_tmp = $_FILES['filegbr']['tmp_name'];	
 
			if(in_array($ekstensi, $ekstensi_diperbolehkan) === true){
				if($ukuran < 9044070){			
					move_uploaded_file($file_tmp, $nama);
					echo '
                    <script>
                    	swal("Good Job","Anda berhasil mengupload file .zip","success");
                    </script>
                    <script language="JavaScript">document.location="index.php?page=up"</script>
            		';
				}else{
					echo '
                    <script>
                    	swal("Good Job","File .zip terlalu besar","error");
                    </script>
            		';
				}
			}else{
				echo '
                    <script>
                    	swal("Good Job","Bukan ekstensi .zip","error");
                    </script>
            		';
			}
        }else{
            echo '
                <script>
                    swal("Good Job","Kode Lisensi Salah","error");
                        </script>
                '; 
        }    
     
    }

}
?>

    <div class="card-header">
          
          <nav aria-label="breadcrumb">
                      <ol class="breadcrumb bg-warning text-white-all">
                        <li class="breadcrumb-item"><a href="#"><i class="fas fa-tachometer-alt"></i> Home</a></li>
                        <li class="breadcrumb-item"><a href="#"><i class="far fa-file"></i> Update</a></li>
                        <li class="breadcrumb-item active" aria-current="page"><i class="fas fa-list"></i> Auto BiznisTop</li>
                      </ol>
                    </nav>
          </div>
          
<div class="card-body">
    <div class="alert alert-primary alert-has-icon p-4">
            <div class="alert-icon"><i class="far fa-lightbulb"></i></div>
            <div class="alert-body">
            <div class="alert-title">Petunjuk:</div>
            1. Masukkan kode lisensi kemudian klik tombol upload otomatis.<br>
            2. Pilih File Update tanggal terakhir dan Instal. <br>
            3. Anda sekarang ini menggunakan Auto BiznisTop v3.0 update <b><?php echo $versi ?></b>. Alamat web yang diregistrasi: <b><?php echo $weburl ?></b><br>
            4. Proses Update tidak menghilangkan data anda sebelumnya. <br>
            5. Jika proses instalasi update gagal, kemungkinan ektensi zip dalam versi php anda belum aktif. <a href="https://blog.biznis.top/2019/11/mengaktifkan-ekstensi-zip-di-php-71.html" target="_blank">Klik Disini</a> cara mengaktifkannya. <br>
            6. Jika terinstal di Addon Domain dan saat proses Instal Update tidak berhasil, lakukan Instal Update Manual (Upload Manual).
            </div>
            </div>      
            
 <div class="alert alert-success alert-dismissable" style="margin-top:20px">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                <h6><i class="icon glyphicon glyphicon-remove"></i> 
                <?php
                $sumber ="aHR0cHM6Ly9iaXpuaXMudG9wL3VybC9jZWt1cC5odG1s";
				$sumber =  bacaURL(base64_decode($sumber));
                $split = explode('<h6>', $sumber);
                $splitLagi = explode('</h6>', $split[1]);
                echo $splitLagi[0];
                ?>
                </div> 
 
 
 <h4>1. Upload File Update Auto BiznisTop</h4>
 <form action="" method="POST" enctype="multipart/form-data"> 
     <div class="form-group">
         <div class="col-sm-10">
             Masukkan Kode Lisensi Anda
    <input class='form-control' type="text" name="lis" class="form-field" required />
    </div></div>
    
      <div class="form-group">
                            
         <div class="col-sm-10">
        <input class='form-control' type='file' name='filegbr' id='Filegambar'>
        </div> 
        </div> 
                    
    <div class="form-group">
     <div class  ="col-sm-6">
     <button type="submit" class="btn btn-primary" name="ubah"><span class="glyphicon glyphicon-pencil"></span> Upload Manual</button> 
    <button type="submit" class="btn btn-primary" name="upload"><span class="glyphicon glyphicon-pencil"></span> Upload Otomatis</button> <br>
    <i>Jika mengklik tombol Upload Otomatis tidak perlu memasukkan file</i> <br>
    </div></div>
 </form>
  
 <hr>

<form action="" method="POST">
  <fieldset>
    <h4>2. Install Update Auto BiznisTop</h4>
    <p class="status status--<?php echo strtoupper(key($GLOBALS['status'])); ?>">
      Status: <?php echo reset($GLOBALS['status']); ?><br/>
      <span class="small">Processing Time: <?php echo $time; ?> Detik</span>
    </p>
    <div class="form-group">
         <div class="col-sm-10">
             Masukkan Kode Lisensi Anda
    <input class='form-control' type="text" name="lis" class="form-field" required />
    </div></div>
    <div class="form-group">
         <div class="col-sm-10">
    <label for="zipfile">Pilih File Update Auto BiznisTop:</label>
    <select name="zipfile" size="1" class="form-control" class="select">
      <?php foreach ($unzipper->zipfiles as $zip) {
        echo "<option>$zip</option>";
      }
      ?>
    </select>
    </div></div>
    <!--<label for="extpath">Extraction path (optional):</label>-->
    <input type="hidden" name="extpath" class="form-field" />
    <input type="submit" name="dounzip" class="btn btn-primary" value="Instal Update"/>
    <input type="submit" name="delzip" class="btn btn-primary" value="Hapus File Update"/>
  </fieldset>

  
</form>
</div>
