Search This Blog

Tuesday, October 26, 2021

Ubuntu Linux - Connect Postgresql from Psql and also PGadmin Remotely

 Step 1 :

> sudo su

> vi /etc/postgresql/10/main/postgresql.conf

#listen_addresses = 'localhost'
to 
listen_addresses = '*'

>vi /etc/postgresql/10/main/pg_hba.conf
# IPv4 local connections:
host all all 127.0.0.1/32 md5

to
host all all 0.0.0.0/0 md5


>sudo ufw allow 5432/tcp
>sudo systemctl restart postgresql


>psql -h localhost -d databasename -U userrolename
...enterpasswordfor-userrolename






Wednesday, October 13, 2021

Security : Java PHP encryption decryption for AES-128-CTR or AES/CTR/NoPadding

 Java

package com.security;

import java.util.Base64;


import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;


/**

 * @author drvijay

 * @date 13-0ct-2021

 */


public class EncryptDecrypt

{

private static String encrypt ( String data, String cipherType, String key, String iv )

{

String encrypted = "";


try

{

Cipher encryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, encryptionCipher.getBlockSize () );

encryptionCipher.init ( Cipher.ENCRYPT_MODE, new SecretKeySpec ( key.getBytes (), "AES" ), ivv );

// encrypt

byte [] cipherText = encryptionCipher.doFinal ( data.getBytes () );


encrypted = new String ( Base64.getEncoder ().encode ( cipherText ) );

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return encrypted;

}


private static String decrypt ( String encryptData, String cipherType, String key, String iv )

{

String decrypted = "";

try

{


Cipher decryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, decryptionCipher.getBlockSize () );


SecretKeySpec secretKeySpec = new SecretKeySpec ( key.getBytes (), "AES" );

decryptionCipher.init ( Cipher.DECRYPT_MODE, secretKeySpec, ivv );

// decrypt

byte [] finalCipherText = decryptionCipher.doFinal ( Base64.getDecoder ().decode ( encryptData ) );

// converting to string

String finalDecryptedValue = new String ( finalCipherText );

decrypted = finalDecryptedValue;

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return decrypted;

}


public static void main ( String [] args )

{

String cipherType = "AES/CTR/NoPadding";

String valueToEncrypt = "hello, vijay";

String key = "0123456789abcdef";

String iv = "2208250639374785";


String encrypted = encrypt ( valueToEncrypt, cipherType, key, iv );

String decrypted = decrypt ( encrypted, cipherType, key, iv );


//System.out.println(Base64.getDecoder ().decode ( "ycbnIE8vn2lTUi/9F/FEa+5v86qzOU09yjdxfGDc8wA=" ));

// END OF ENCODE CODE

System.out.println ( "encrypted and saved as Base64 : " + encrypted );


System.out.println ( "decrypted from Base64->aes128 : " + decrypted );

// END OF DECRYPT CODE


}

}




PHP code

<!DOCTYPE html>

<html>

<body>

<?php

$simple_string = "hello, vijay";

echo ($simple_string .'<br/>');

        $ciphering = 'AES-128-CTR';

        $iv_length = openssl_cipher_iv_length($ciphering);

        $options = 0;

        // Non-NULL Initialization Vector for encryption

        $iv = '2208250639374785';


       

        $key = '0123456789abcdef';


                $encryption = openssl_encrypt($simple_string, $ciphering,

                    $key, $options, $iv); 

                    echo($encryption .'<br/>');

                    

                  $decryption=openssl_decrypt ($encryption, $ciphering,

                $key, $options, $iv);

                echo($decryption .'<br/>');

                

?>


</body>

</html>



output

hello, vijay
0iQoUVC/QZG3cM20
hello, vijay

Monday, October 11, 2021

Java to Do ImageMagick Call

 package com.product.zilly;


import java.io.File;

import java.util.Map;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


/**

 * @author drvijay

 * @description img class

 * @version 1.0

 */


@SuppressWarnings ("all")

public class TestModules implements Constants

{

private static final Logger logger = LoggerFactory.getLogger ( TestModules.class );


public static void main ( String args[] )

{

ImageHelper imageHelper = new ImageHelper ();

String renditionPath = "/home/drvijay/images"; 

String rendtionPathCategory = "/home/drvijay/images"; 

String startingMainPath = renditionPath + PATH_SEPARATOR + SkuRendition.main;

String startingCategoryMainPath = rendtionPathCategory + PATH_SEPARATOR + SkuRendition.main; // for category images main path

imageHelper.loadSkuImageProperties ();

boolean imageOverride = false; 

File rotated = null;

File file = new File ( startingMainPath + PATH_SEPARATOR + "sample.png" );

if ( file.isFile () && file.exists () )

{

Map <SkuRendition, Map <Resolution, DimInfo>> dimensions = imageHelper.getAllDimensions ();

logger.debug ( dimensions.toString () );

for ( SkuRendition skuRendition : dimensions.keySet () )

{

try

{

Map <Resolution, DimInfo> resolutions = dimensions.get ( skuRendition );

for ( Resolution resolution : resolutions.keySet () )

{

DimInfo dimInfo = resolutions.get ( resolution );


File isExist = new File ( renditionPath + PATH_SEPARATOR + skuRendition.name () + PATH_SEPARATOR + resolution.name () + UNDER_SCORE + file.getName () );

if ( ( imageOverride && isExist.isFile () && isExist.exists () ) || ( !isExist.isFile () && !isExist.exists () ) )

{

rotated = imageHelper.processImage ( file, imageHelper.getOutputDir ( renditionPath, skuRendition.name () ), dimInfo, resolution.name () );

logger.debug ( "Generated : " + rotated.getAbsolutePath () );

}


}

}

catch ( Exception e )

{

logger.error ( "Error : " + e );

}

finally

{


/*

* if ( rotated != null )

* {

* rotated.delete ();

* }

*/


}

}

}

}

}


//Iamge Process

public File processImage ( File inFile, File outputDir, DimInfo dimInfo, String resolution ) throws Exception

{

String fileName = resolution + UNDER_SCORE + inFile.getName ();

// String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

// String fileNameExt = FilenameUtils.getExtension ( fileName );


// check for windows and set the image magick home manually to avoid error.

String OS = System.getProperty ( "os.name" ).toLowerCase ();

if ( ( OS.indexOf ( "win" ) >= 0 ) )

{

// linux - "/usr/lib/mime/packages/imagemagick-6.q16";

String myPath = "C:/Program Files/ImageMagick-6.9.2-Q16"; // globalMaster.getSystemProperties ().get ( KEY_PATH_HOME_IMAGE_MAGICK ).getValue ();

ProcessStarter.setGlobalSearchPath ( myPath );

}

ConvertCmd convert = new ConvertCmd ();

IMOperation operation = new IMOperation ();

String input = inFile.getAbsolutePath ();

int tmbWidth = dimInfo.getWidth ();

int tmbHeight = dimInfo.getHeight ();


operation.addImage ( input );

operation.gravity ( LocalProperties.getPropertyValue ( "render.image.gravity" ) );

operation.thumbnail ( tmbHeight, tmbWidth );

operation.units ( LocalProperties.getPropertyValue ( "render.image.units" ) );

operation.density ( Integer.parseInt ( LocalProperties.getPropertyValue ( "render.image.density" ) ) );

operation.strip ();

operation.interlace ( LocalProperties.getPropertyValue ( "render.image.interlace" ) );

operation.gaussianBlur ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.gaussian.blur" ) ) );

operation.quality ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.quality" ) ) );


File retVal = new File ( outputDir, fileName );

operation.addImage ( retVal.getAbsolutePath () );

convert.run ( operation );


logger.debug ( "Preview file: " + retVal.getAbsolutePath () );

return retVal;

}


Install Latest ImageMagick to support PNG, JPG convertions

 #These are the steps required in order to Install ImageMagick with JPG, PNG and TIFF delegates.

sudo apt-get update 

#Install Build-Essential in order to configure and make the final Install

sudo apt-get install build-essential 

#libjpg62-dev required in order to work with basic JPG files

sudo apt-get install -y libjpeg62-dev 

#libtiff-dev is required in order to work with TIFF file format

sudo apt-get install -y libtiff-dev 

#libpng-dev required in order to work with basic PNG files

sudo apt-get install -y libpng-dev

#Download ImageMagick

wget https://www.imagemagick.org/download/ImageMagick.tar.gz 

#Untar Imagemagick

tar xvzf ImageMagick.tar.gz 

#Access the working directory

cd ImageMagick-[version_number] 

#Configure and make sure to disable the "shared" option

./configure --disable-shared

#Make

sudo make

#Install

sudo make install

#Final Check

sudo make check

Tuesday, September 7, 2021

Eclipse - Python Import Libraries or Error issues fixes

 step 1) Removing the interpreter, auto configuring it again

step 2) Window - Preferences - PyDev - Interpreters - Python Interpreter Go to the Forced builtins tab Click on New... Type the name of the module (tensorflow in my case) and click OK

step 3) Right click in the project explorer on whichever module is giving errors. Go to PyDev->Code analysis.

Tuesday, August 31, 2021

Python - ImportError: cannot import name 'signature' from 'sklearn.utils.fixes'

 Please install funcsigs directly using

pip install funcsigs

and use from funcsigs import signature instead.


#ex:

#from sklearn.utils.fixes import signature

from funcsigs import signature



-- enjoy

Friday, July 23, 2021

How to install Gnome Extensions

 Extract the downloaded file. Copy the folder to ~/.local/share/gnome-shell/extensions directory. Go to your Home directory and press Crl+H to show hidden folders. Locate .local folder here and from there, you can find your path till extensions directory. 

Once you have the files copied in the correct directory, go inside it and open metadata.json file. Look for the value of uuid. 

Make sure that the name of the extension’s folder is same as the value of uuid in the metadata.json file. If not, rename the directory to the value of this uuid.

Manually install GNOME Shell extension
Name of extension folder should be the same as uuid

Almost there! Now restart GNOME Shell. Press Alt+F2 and enter r to restart GNOME Shell.

Restart GNOME Shell
Restart GNOME Shell

Restart GNOME Tweaks tool as well. You should see the manually installed GNOME extension in the Tweak tool now. You can configure or enable the newly installed extension here.

And that’s all you need to know about installing GNOME Shell Extensions.

Remove GNOME Shell Extensions

It is totally understandable that you might want to remove an installed GNOME Shell Extension.

If you installed it via a web browser, you can go to the installed extensions section on GNOME website and remove it from there (as shown in an earlier picture).

If you installed it manually, you can remove it by deleting the extension files from ~/.local/share/gnome-shell/extensions directory.

Monday, July 19, 2021

Ubuntu KAZAM Screencast Recorder Audio Problem - FIX

1. Install Kazam 

    sudo apt install kazam

 2. modify this file:

/usr/lib/python3/dist-packages/kazam/pulseaudio/pulseaudio.py

and replace

time.clock()

with

time.perf_counter()
OR SIMPLE CLI COMMAND
sudo sed "s/time.clock()/time.perf_counter()/g" -i /usr/lib/python3/dist-packages/kazam/pulseaudio/pulseaudio.py
3. Open Kazam, Go to File -> Preferences. General
    Speakers -> SELECT from the list like 
                   Monitor of Built-in Audio ...



ENJOY


Wednesday, June 30, 2021

How to Host Flask Applications on Namecheap cPanel

Very good. 


1. Follow the link, 

 https://dev.to/lordghostx/how-to-host-flask-applications-on-namecheap-cpanel-299b


2. In Execute Python Script 

-m pip install --upgrade pip

-m pip install -r requirements.txt






Restart the server for app.py changes.


Joomla Wordpress - Friendly URL not working


1. Open Cpanel -> File Manager
    Top right corner ->Settings or find settings 
    Show Hidden Files. 

2. Goto public_html folder/.htaccess
paste the below block, save & close.

<IfModule mod_rewrite.c>
RewriteEngine On
# Removes index.php from ExpressionEngine URLs
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

3. Now goto global configuration ->joomla -> turn on Friend URL redirection.

Python - Image to Pdf

1. Install img2pdf

> pip/pip3 install img2pdf

2. img2pdfown.py


# importing necessary libraries

import img2pdf

from PIL import Image

import os

  

# CLI  img2pdf *jpg -o output_all_pngs.pdf

'''

img_path = "image1.jpg";

pdf_path = "output.pdf";

image = Image.open(img_path);

pdf_bytes = img2pdf.convert(image.filename);

file = open(pdf_path, "wb");

file.write(pdf_bytes);

image.close();

file.close();

'''


# convert all files ending in .jpg inside a directory

dirname = "dump/images/"

imgs = []

#dpix = dpiy = 300;

#layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

for fname in os.listdir(dirname):

    if not fname.endswith(".jpg"):

        continue

    path = os.path.join(dirname, fname)

    if os.path.isdir(path):

        continue

    imgs.append(path)

    print ("\n" + path);

with open("dump/output.pdf", "wb") as f:

    #f.write(img2pdf.convert(imgs, layout_fun=layout_fun));

    f.write(img2pdf.convert(imgs));

  

'''    

imgs = ['dump/images/page_1.jpg', 'dump/images/page_2.jpg', 'dump/images/page_10.jpg']

with open("dump/output1.pdf", "wb") as f:

    f.write(img2pdf.convert(imgs))


# specify paper size (A4)

a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))

layout_fun = img2pdf.get_layout_fun(a4inpt)

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# use a fixed dpi of 300 instead of reading it from the image

dpix = dpiy = 300;

layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# create a PDF/A-1b compliant document by passing an ICC profile

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', pdfa="/usr/share/color/icc/sRGB.icc"))    

'''

    


Friday, June 18, 2021

React Native - Check Application is in Background or ForeGround with Time Diff - 10 seconds Move to Login Session Expired

 1. Install the below two mandatory npm plugins.

npm install --save react-native-async-storage

npm install --save moment


2. app.js


import React, { Component } from 'react';
import { StyleSheet, Text, View, AppState } from 'react-native';
//import Routing from "./src/routing/routing";
import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
//import { Actions } from 'react-native-router-flux';

export default class App extends Component {
constructor() {
super();
this.state = {
appState: AppState.currentState
}
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = async(nextAppState) => {
this.setState({ appState: nextAppState });
if (nextAppState === 'background') {
var previousTime = new Date();
await AsyncStorage.setItem( "previousTime", previousTime.toString() );
// Do something here on app background.
console.log( "App is in Background Mode @ ", previousTime );
}
if (nextAppState === 'active') {
// Do something here on app active foreground mode.
const start = moment( await AsyncStorage.getItem('previousTime') );
const end = moment();
//in original implementation, use minutes and check with N value.
//const range = end.diff(start,'minutes');
const range = end.diff(start,'seconds');
if ( range >= 10 ){
console.log ( "App is exit the Active Range, So moving to Login screen." );
/* Actions.login({"message":"Session Exit"} ); */
}
else{
console.log( "App is in Active Range, So continue your process ...");
}
}
if (nextAppState === 'inactive') {
// Do something here on app inactive mode.
console.log("App is in inactive Mode.")
}
};
render() {
return (
<View style={styles.MainContainer}>
{/* <Routing /> */}
<Text>Current state is: {this.state.appState}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
color: '#000'
}
});

Friday, May 28, 2021

Eclipse - boto3 botocore.exceptions.ProfileNotFound: The config profile () could not be found

1.  If terminal is not opening, 

Go and update the eclipse from Help->MarketPlace.

2. See whether you installed boto3 and awscli from sudo or root and now you login as same user or different, 

   if different, then uninstall the above two plugin and install with the current user. 

    pip/pip3 install boto3

    pip/pip3 install awscli


3.type aws configure

            Enter Key, access scret, region

4. type vi ~/.aws/credentials

        [default]

            aws_access_key_id = xxx

            aws_secret_access_key = xx+xx

        [vijay]

            aws_access_key_id = x

            aws_secret_access_key = x+xx


5. your python program
   
          import csv
import datetime
import os
import smtplib, ssl
import boto3

botSession=boto3.session.Session(profile_name="vijay")
iam_mag_con=botSession.client(service_name="ec2",region_name='us-east-2')
resp = iam_mag_con.describe_regions()

....... 

Tuesday, May 11, 2021

Eclipse - PHP Fatal error: Call to undefined function json_decode()

Add PHP 

1. Window->Preferences->Installed PHPs-> Add

    /usr/bin/<search php> select /usr/bin/php7.4.x

2. Check "Window->Preferences->Installed PHPs" checkbox "Use system default php.ini configuration" must be enabled. And I had to setup "apt install php-json" on my Ubuntu.

3. Enable Debug

   Open Terminal -> sudo apt-get install php-xdebug

4. Check "Window->Preferences->Installed PHPs" ->Debuger -> XDebug [from dropdown]



Enjoy

Wednesday, April 7, 2021

Filezilla FTP zip file Uncompress / Extract

1. Copy the below code and paste it into a file and name it unzip.php

2. Copy this file to your current directory in ftp location where zip files are there. 

3. type your url/unzip.php  [ ex: infovijay.com/unzip.php ]

4. now you can see the screen like below. select the zip file and click unzip archieve. ENJOY.

tkx Andreas.



unzip.php


<?php

/**

 * 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'])) {

  // Check if an archive was selected for unzipping.

  $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';

  $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';

  $unzipper->prepareExtraction($archive, $destination);

}


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() {

    // Read directory and pick .zip, .rar and .gz files.

    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' => '.zip or .gz or .rar files found, ready for extraction');

      }

      else {

        $GLOBALS['status'] = array('info' => 'No .zip or .gz or rar files found. So only zipping functionality available.');

      }

    }

  }


  /**

   * Prepare and check zipfile for extraction.

   *

   * @param string $archive

   *   The archive name including file extension. E.g. my_archive.zip.

   * @param string $destination

   *   The relative destination path where to extract files.

   */

  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);

    }

  }


  /**

   * Checks file extension and calls suitable extractor functions.

   *

   * @param string $archive

   *   The archive name including file extension. E.g. my_archive.zip.

   * @param string $destination

   *   The relative destination path where to extract files.

   */

  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;

    }


  }


  /**

   * Decompress/extract a zip archive using ZipArchive.

   *

   * @param $archive

   * @param $destination

   */

  public static function extractZipArchive($archive, $destination) {

    // Check if webserver supports unzipping.

    if (!class_exists('ZipArchive')) {

      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');

      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' => 'Files unzipped successfully');

      }

      else {

        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');

      }

    }

    else {

      $GLOBALS['status'] = array('error' => 'Error: Cannot read .zip archive.');

    }

  }


  /**

   * Decompress a .gz File.

   *

   * @param string $archive

   *   The archive name including file extension. E.g. my_archive.zip.

   * @param string $destination

   *   The relative destination path where to extract files.

   */

  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.');

    }


  }


  /**

   * Decompress/extract a Rar archive using RarArchive.

   *

   * @param string $archive

   *   The archive name including file extension. E.g. my_archive.zip.

   * @param string $destination

   *   The relative destination path where to extract files.

   */

  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

 *

 * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719

 * @author umbalaconmeogia

 */

class Zipper {

  /**

   * Add files and sub-directories in a folder to zip file.

   *

   * @param string $folder

   *   Path to folder that should be zipped.

   *

   * @param ZipArchive $zipFile

   *   Zipfile where files end up.

   *

   * @param int $exclusiveLength

   *   Number of text to be exclusived from the file path.

   */

  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);

  }


  /**

   * Zip a folder (including itself).

   *

   * Usage:

   *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');

   *

   * @param string $sourcePath

   *   Relative path of directory to be zipped.

   *

   * @param string $outZipPath

   *   Relative path of the resulting output zip file.

   */

  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);

  }

}

?>


<!DOCTYPE html>

<html>

<head>

  <title>File Unzipper + Zipper</title>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <style type="text/css">

    <!--

    body {

      font-family: Arial, sans-serif;

      line-height: 150%;

    }


    label {

      display: block;

      margin-top: 20px;

    }


    fieldset {

      border: 0;

      background-color: #EEE;

      margin: 10px 0 10px 0;

    }


    .select {

      padding: 5px;

      font-size: 110%;

    }


    .status {

      margin: 0;

      margin-bottom: 20px;

      padding: 10px;

      font-size: 80%;

      background: #EEE;

      border: 1px dotted #DDD;

    }


    .status--ERROR {

      background-color: red;

      color: white;

      font-size: 120%;

    }


    .status--SUCCESS {

      background-color: green;

      font-weight: bold;

      color: white;

      font-size: 120%

    }


    .small {

      font-size: 0.7rem;

      font-weight: normal;

    }


    .version {

      font-size: 80%;

    }


    .form-field {

      border: 1px solid #AAA;

      padding: 8px;

      width: 280px;

    }


    .info {

      margin-top: 0;

      font-size: 80%;

      color: #777;

    }


    .submit {

      background-color: #378de5;

      border: 0;

      color: #ffffff;

      font-size: 15px;

      padding: 10px 24px;

      margin: 20px 0 20px 0;

      text-decoration: none;

    }


    .submit:hover {

      background-color: #2c6db2;

      cursor: pointer;

    }

    -->

  </style>

</head>

<body>

<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; ?> seconds</span>

</p>

<form action="" method="POST">

  <fieldset>

    <h1>Archive Unzipper</h1>

    <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>

    <select name="zipfile" size="1" class="select">

      <?php foreach ($unzipper->zipfiles as $zip) {

        echo "<option>$zip</option>";

      }

      ?>

    </select>

    <label for="extpath">Extraction path (optional):</label>

    <input type="text" name="extpath" class="form-field" />

    <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>

    <input type="submit" name="dounzip" class="submit" value="Unzip Archive"/>

  </fieldset>


  <fieldset>

    <h1>Archive Zipper</h1>

    <label for="zippath">Path that should be zipped (optional):</label>

    <input type="text" name="zippath" class="form-field" />

    <p class="info">Enter path to be zipped without leading or trailing slashes (e.g. "zippath"). If left empty current directory will be used.</p>

    <input type="submit" name="dozip" class="submit" value="Zip Archive"/>

  </fieldset>

</form>

<p class="version">Unzipper version: <?php echo VERSION; ?></p>

</body>

</html>


Hit Counter


View My Stats