<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: ImageModel.php, v 1.0 2011/06/14 20:52:11
//
//FOR RACKSPACE
require('vendor/autoload.php');
use OpenCloud\Rackspace;
//FOR AMAZON S3
$awsfolder = 'amazon';//($_SERVER['HTTP_HOST']=='test.jihazi.com') ? 'amazonv1':'amazon';
require(__DIR_LIBRARY . '/'.$awsfolder.'/aws-autoloader.php');
use Aws\S3\S3Client;
use Guzzle\Http\EntityBody; 
use OpenCloud\Common\Constants\Header;  
class ImageModel extends Model {
    public $imageSizeX;
    public $imageSizeY;
    public $resizeX;
    public $resizeY;
    public $reduction_height;
    public $reduction_width;
    public $fileName;
    public $msg;
    public $image; 
    public $imageType;
    public $upload_images;
    public $aws_access_key;
    public $aws_secret_key;
    public $image_bucket;
    public $containerName;
    public $client;
    public $objectStoreService;
    public $rackspace_username;
    public $rackspace_apikey;
    public $rackspace_region_code;
    public $container;
    //Constructor for Controller class
    public function __construct() { 
        $this->upload_images = $this->getSettingValue('site_settings', 'upload_images_to');
        if ($this->upload_images == 'amazon') {
            $this->aws_access_key = $this->getSettingValue('site_settings', 'access_key_images');
            $this->aws_secret_key = $this->getSettingValue('site_settings', 'secret_key_images');
            $this->image_bucket   = $this->getSettingValue('site_settings', 'bucket_name_images');
            $awsfolder = 'amazon';
            if($awsfolder=='amazonv1') {
                $this->client         = S3Client::factory(array(
                    'key' => $this->aws_access_key,
                    'secret' => $this->aws_secret_key
                ));
            } else {
                $this->client         = S3Client::factory(array(
                    'version' => 'latest',
                    'region'  => 'eu-west-1', 
                    'credentials' => array(
                            'key' => $this->aws_access_key,
                            'secret'  => $this->aws_secret_key,
                      ),
                    'http'    => [
                            'verify' => false
                    ]
                ));
            }
        } else if ($this->upload_images == 'rackspace') {
            $this->rackspace_username    = $this->getSettingValue('site_settings', 'rackspace_username');
            $this->rackspace_apikey      = $this->getSettingValue('site_settings', 'rackspace_apikey');
            $this->client                = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array(
                'username' => $this->rackspace_username,
                'apiKey' => $this->rackspace_apikey
            ));
            $this->rackspace_region_code = $this->getSettingValue('site_settings', 'rackspace_region_code');
            $this->objectStoreService    = $this->client->objectStoreService(null, $this->rackspace_region_code);
            $this->containerName         = $this->getSettingValue('site_settings', 'rackspace_container_name');
            $this->container             = $this->objectStoreService->getContainer($this->containerName);
        }
    }
    //FUNCTION TO RESIZE IMAGE 
    public function resizeImage($imgName, $target_path = '', $red_width='', $red_height='', $imageQuality = "") {
        $this->reduction_height = $red_height;
        $this->reduction_width  = $red_width;
        if (is_file($imgName)) {
            if (file_exists($imgName)) {
                $this->fileName = $imgName;
                $this->getSize();
                $this->setSize();
                $this->resizeIt();
                $this->saveImage($imgName, $imageQuality, $target_path);
            } else {
                $this->errorState(0);
            }
        } else {
            $this->errorState(2);
        }
    }
    //END OF FUNCTION
    //FUNCTION TO SET IMAGE SIZE   
    public function setSize() {
        $ratio_image = $this->imageSizeX / $this->imageSizeY;
        $ratio       = $this->reduction_width / $this->reduction_height;
        if ($ratio_image < $ratio) {
            $ratio_image   = $this->imageSizeX / $this->imageSizeY;
            $this->resizeY = $this->reduction_height;
            $this->resizeX = round($ratio_image * $this->resizeY);
        } else {
            $ratio_image   = $this->imageSizeY / $this->imageSizeX;
            $this->resizeX = $this->reduction_width;
            $this->resizeY = round($ratio_image * $this->resizeX);
        }
    }
    //END OF FUNCTION      
    //FUNCTION TO SAVE IMAGE 
    public function saveImage($imgName, $imageQuality = "", $target_path = "") {
        if ($imageQuality == "") {
            //Defined in application.php
            $imageQuality = JPEG_IMAGE_QUALITY;
        }
        if ($target_path != "") {
            //Defined in application.php
            $imgName = $target_path;
        }
        switch ($this->imageType) {
            case "gif":
                imagegif($this->image, $imgName);
                break;
            case "jpg":
                imagejpeg($this->image, $imgName, $imageQuality);
                break;
            case "png":
                $scaleQuality       = round(($imageQuality / 100) * 9);
                $invertScaleQuality = 9 - $scaleQuality;
                imagepng($this->image, $imgName, $invertScaleQuality);
                break;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO GET SIZE       
    public function getSize() {
        $this->imgParams  = getimagesize($this->fileName);
        $this->imageSizeX = $this->imgParams[0];
        $this->imageSizeY = $this->imgParams[1];
        switch ($this->imgParams[2]) {
            case 1:
                $this->imageType = "gif";
                $this->image     = imagecreatefromgif($this->fileName);
                break;
            case 2:
                $this->imageType = "jpg";
                $this->image     = imagecreatefromjpeg($this->fileName);
                break;
            case 3:
                $this->imageType = "png";
                $this->image     = imagecreatefrompng($this->fileName);
                //$this->image=imagealphablending($this->image, false);
                //	$this->image=imagesavealpha($this->image, true);
                break;
            default:
                $this->errorState(1);
        }
    }
    //END OF FUNCTION
    //FUNCTION  TO RESIZE     
    public function resizeIt() {
        $imageWidth  = $width = $this->reduction_width;
        $imageHeight = $height = $this->reduction_height;
        list($width_orig, $height_orig) = $this->imgParams;
        $ratio_orig = $width_orig / $height_orig;
        if ($width / $height > $ratio_orig) {
            $width = $height * $ratio_orig;
        } else {
            $height = $width / $ratio_orig;
        }
        $copy  = imagecreatetruecolor($imageWidth, $imageHeight);
        /* Setting transparent background for png */
        $white = imagecolorallocate($copy, 255, 255, 255);
        // Fill the background with white
        imagefill($copy, 0, 0, $white);
        // Alpha blending must be enabled on the background!
        imagealphablending($copy, TRUE);
        /* Setting transparent background for png */
        if ($copy) {
            if (imagecopyresampled($copy, $this->image, ($imageWidth - $width) / 2, ($imageHeight - $height) / 2, 0, 0, $width, $height, $width_orig, $height_orig)) {
                if (imagedestroy($this->image)) {
                    $this->image = $copy;
                } else {
                    $this->errorState(6);
                }
            } else {
                $this->errorState(4);
            }
        } else {
            $this->errorState(5);
        }
        // $copy  = imagecreatetruecolor($this->resizeX, $this->resizeY);
        // /* Setting transparent background for png */
        // $color = imagecolorallocate($copy, 255, 255, 255);
        //Fill the background with white
        // imagefill($copy, 0, 0, $color);
        //Alpha blending must be enabled on the background!
        // imagealphablending($copy, TRUE);
        // /* Setting transparent background for png */
        // if ($copy)
        // {
        // if (imagecopyresampled($copy, $this->image, 0, 0, 0, 0, $this->resizeX, $this->resizeY, $this->imageSizeX, $this->imageSizeY))
        // {
        // if (imagedestroy($this->image))
        // {
        // $this->image = $copy;
        // }
        // else
        // {
        // $this->errorState(6);
        // }
        // }
        // else
        // {
        // $this->errorState(4);
        // }
        // }
        // else
        // {
        // $this->errorState(5);
        // }
    }
    //END OF FUNCTION
    //FUNCTION FOR ERROR SHOW      
    public function errorState($err) {
        switch ($err) {
            case 0:
                $this->msg = "File Not Found.";
                break;
            case 1:
                $this->msg = "Invalid File Type.";
                break;
            case 2:
                $this->msg = "Invalid Input.";
                break;
            case 3:
                $this->msg = "Could Not Save.";
                break;
            case 4:
                $this->msg = "Could not Create Image.";
                break;
            case 5:
                $this->msg = "Could not Create Blank File.";
                break;
            case 6:
                $this->msg = "Unable to Destroy Old File.";
                break;
        }
        print $this->msg;
    }
    //END OF FUNCTION
    //FUNCTION TO GENERATE CODE	
    function generateCode($ObjSession, $characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = '23456789bcdfghjkmnpqrstvwxyzYUIJHNMVSEDF';
        $code     = '';
        $i        = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible) - 1), 1);
            $i++;
        }
        return $code;
    }
    //END OF FUNCTION
    //FUNCTION FOR CAPTCHA
    function CaptchaSecurityImages($width, $height, $characters = '6', $style) {
        $ObjSession = isset($ObjSession) ? $ObjSession : '';
        $code       = $this->generateCode($ObjSession, $characters);
        /* font size will be 75% of the image height */
        $font_size  = $height * 0.70;
        switch ($style) {
            case 'style 1':
                /// black////
                $font_size = $height * 0.52;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Kids.ttf';
                $background_color = imagecolorallocate($image, 0, 0, 0);
                $text_color       = imagecolorallocate($image, 255, 255, 255);
                $noise_color      = imagecolorallocate($image, 0, 0, 0);
                break;
            case 'style 2':
                //// blue///	
                $font_size = $height * 0.50;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Almagro Regular.ttf';
                $background_color = imagecolorallocate($image, 255, 255, 255);
                $text_color       = imagecolorallocate($image, 0, 0, 220);
                $noise_color      = imagecolorallocate($image, 192, 192, 192);
                break;
            case 'style 3':
                /// grey////
                $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/monofont.ttf';
                $background_color = imagecolorallocate($image, 240, 240, 240);
                $text_color       = imagecolorallocate($image, 171, 171, 171);
                $noise_color      = imagecolorallocate($image, 240, 240, 240);
                break;
            case 'style 4':
                $font_size = $height * 0.50;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Verdana.TTF';
                $background_color = imagecolorallocate($image, 0, 200, 0);
                $text_color       = imagecolorallocate($image, 252, 255, 255);
                $noise_color      = imagecolorallocate($image, 0, 200, 0);
                break;
        }
        /* generate random dots in background */
        for ($i = 0; $i < ($width * $height) / 3; $i++) {
            imagefilledellipse($image, mt_rand(0, $width), mt_rand(0, $height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for ($i = 0; $i < ($width * $height) / 150; $i++) {
            imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4]) / 2;
        $y = ($height - $textbox[5]) / 2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $font, $code) or die('Error in imagettftext function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        unset($_SESSION['captcha_val']);
        echo $_SESSION['captcha_val'] = $code; // carry the data through session
    }
    //END OF FUNCTION     
    function copy_file($source_path, $destination_path,$file_root='') {
        if($file_root=='') {
            $file_exists_path = __ROOT_PATH . '/' . $source_path;
        } else {
            $file_exists_path =  $source_path;
        }
		
		static $exts = array(
			'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif',
			'png' => 'image/png', 'ico' => 'image/x-icon', 'pdf' => 'application/pdf',
			'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'svg' => 'image/svg+xml',
			'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 
			'zip' => 'application/zip', 'gz' => 'application/x-gzip',
			'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
			'bz2' => 'application/x-bzip2',  'rar' => 'application/x-rar-compressed',
			'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload',
			'cab' => 'application/vnd.ms-cab-compressed', 'txt' => 'text/plain',
			'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
			'css' => 'text/css', 'js' => 'text/javascript',
			'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
			'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
			'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
			'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
		);
		$ext = strtolower(pathinfo($source_path, PATHINFO_EXTENSION));
		$type = isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
        if (file_exists($file_exists_path)) {            
            if ($this->upload_images == 'amazon') {
                $fullfilename = __ROOT_PATH . '/' . $source_path;
                $result       = $this->client->putObject(array(
                'ACL' => 'public-read',
                'Bucket' => $this->image_bucket,
                'Key' => __DIR_PUBLIC . $destination_path,
                'Body' => EntityBody::factory(fopen($fullfilename, 'r')),
				'CacheControl' => 'max-age=604800',
				'ContentType' => $type
            ));
            } else if ($this->upload_images == 'rackspace') {
                $localFileName  = __ROOT_PATH . '/' . $source_path;
                $remoteFileName = __DIR_PUBLIC . $destination_path;
                $handle         = fopen($localFileName, 'r');
                $this->container->uploadObject($remoteFileName, $handle);
                fclose($handle);
            } else {
                if (!empty($source_path)) {                    
                    copy($source_path, __CORE_PUBLIC_PATH . $destination_path);                        
                }
            }
        }
    }
    function copy_to_temp($source_path) {
        $info            = pathinfo($source_path);
        $filename_image  = $info['filename'] . "__" . rand() . "." . $info['extension'];
        $rel_fs_path_tmp = __ROOT_PATH . '/' . __DIR_PUBLIC . '/uploads/temp/' . $filename_image;
        $sub_source_path = substr($source_path, strpos($source_path, "/") + 1);
        if ($this->file_exist($sub_source_path)) {
            if ($this->upload_images == 'amazon') {
                $result = $this->client->getObject(array(
                    'ACL' => 'public-read',
                    'Bucket' => $this->image_bucket,
                    'Key' => $source_path,
                    'command.response_body' => EntityBody::factory(fopen($rel_fs_path_tmp, 'w+'))
                ));
            } else if ($this->upload_images == 'rackspace') {
                $object  = $this->container->getObject($source_path);
                $stream  = $object->getContent();
                $content = (string) $stream;
                $stream->rewind();
                $localFilename = $rel_fs_path_tmp;
                file_put_contents($localFilename, $stream->getStream());
            }
            return $filename_image;
        }
    }
    function file_exist($filename) {
        
        if ($this->upload_images == 'amazon') {
            $result = $this->client->doesObjectExist($this->image_bucket, __DIR_PUBLIC . '/' . $filename);
            
            return $result;
        } else if ($this->upload_images == 'rackspace') {
            $result = $this->container->objectExists(__DIR_PUBLIC . '/' . $filename);
            return $result;
        } else {
            $fullfilename = __CORE_PUBLIC_PATH . '/' . $filename;
            if (file_exists($fullfilename)) {
                return true;
            } else {
                return false;
            }
        }
    }
    //unlink image file
    function unlinkImage($fileName = '') {
        if ($fileName != '') {
            $validImageFiles = explode(",", VALID_IMAGE_FILES);
            $fileExtension   = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
            //Checking Valid Image File Extension
            if (in_array(trim($fileExtension), $validImageFiles) && $this->file_exist($fileName)) {
                if ($this->upload_images == 'amazon') {
                    $result = $this->client->deleteObject(array(
                        'ACL' => 'public-read',
                        'Bucket' => $this->image_bucket,
                        'Key' => __DIR_PUBLIC . '/' . $fileName
                    ));
                    return $result;
                } else if ($this->upload_images == 'rackspace') {
                    $file_name = __DIR_PUBLIC . '/' . $fileName;
                    $object    = $this->container->getObject($file_name);
                    $result    = $object->delete();
                    return $result;
                } else {
                    $fullPath = __CORE_PUBLIC_PATH . "/" . $fileName;
                    if (unlink($fullPath)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    
    //unlink image file
    function unlinkAWSImage($fileName = '',$destiantion='product') {
        $upload_images      = $this->getSettingValue('site_settings', 'upload_images_to');
        $image_bucket   = $this->getSettingValue('site_settings', 'bucket_name_images');
        if ($fileName != '') {
            $validImageFiles = explode(",", VALID_IMAGE_FILES);
            $fileExtension   = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
            //Checking Valid Image File Extension
            $directory_path = array(__DIR_PUBLIC . '/' .__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/thumb/',
                                    __DIR_PUBLIC . '/' .__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/large/',
                                    __DIR_PUBLIC . '/' .__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/preview/',
                                    __DIR_PUBLIC . '/' .__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/small/',
                                    __DIR_PUBLIC . '/' .__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/preview-main/',
                                );
            for($i=0;$i<count($directory_path);$i++){
                if (in_array(trim($fileExtension), $validImageFiles) && $this->aws_file_exist($fileName,$directory_path[$i])) {
                if ($upload_images == 'amazon') {
                    $result = $this->client->deleteObject(array(
                        'ACL' => 'public-read',
                        'Bucket' => $this->image_bucket,
                        'Key' => $directory_path[$i] . $fileName
                    ));
                    return $result;
                } else if ($upload_images == 'rackspace') {
                    $file_name = __DIR_PUBLIC . '/' . $fileName;
                    $object    = $this->container->getObject($file_name);
                    $result    = $object->delete();
                    return $result;
                } else {
                    $fullPath = __CORE_PUBLIC_PATH . "/" . $fileName;
                    if (unlink($fullPath)) {
                        return true;
                    }
                }
            }
            }
            
        }
        return false;
    }
    
    function aws_file_exist($filename, $directory_path) {
        //echo $directory_path . $filename; exit;
        if ($this->upload_images == 'amazon') {
            $result = $this->client->doesObjectExist($this->image_bucket, $directory_path . $filename);
            
            return $result;
        } else if ($this->upload_images == 'rackspace') {
            $result = $this->container->objectExists(__DIR_PUBLIC . '/' . $filename);
            return $result;
        } else {
            $fullfilename = __CORE_PUBLIC_PATH . '/' . $filename;
            if (file_exists($fullfilename)) {
                return true;
            } else {
                return false;
            }
        }
    }
}
