<?php

/**
 * Tomthumb contains our dependencies 
 * (imageProcessor, autoload)
 */
if(isset($_GET['debug'])){
	error_reporting(-1);
	ini_set('display_errors',1);
}
if(is_file('image/tomthumb.loader.php')) {
    require_once('image/tomthumb.loader.php');
} elseif(is_file(dirname(dirname(dirname(dirname(__FILE__)))) . '/image/tomthumb.loader.php')) {
    require_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/image/tomthumb.loader.php');
} elseif(is_file('/usr/share/php/image/tomthumb.loader.php')){
    require_once('/usr/share/php/image/tomthumb.loader.php');
}


class s3resizer extends ImageProcessor {
 
    /**
     * Build our image processor
     * Bucket: cms-image-content
     */
    function __construct() {
        
        // aws_lambda.ini
        $conf = parse_ini_file('aws_lambda.ini');
    
        $this->aws_access_key   = $conf['AWS_KEY'];
        
        $this->aws_secret_access_key = $conf['AWS_SECRET'];
        
        if(isset($conf['PHP_COMMAND'])) {
            $this->php_command = $conf['PHP_COMMAND'];
        } else {
		$this->php_command = 'php74';
	}
        
        $this->setBucket('cms-image-contents');
    }
    
    /**
     * Create thumbs without forks.
     * 
     * @return type
     */
    public function createResizedImages() {
        $default = 
            $this->extra_thumb(559, 420, '_default');
            $this->extra_thumb(338, 224, '_large');
            $this->extra_thumb(295, 125, '_medium');
            $this->extra_thumb(126, 83,  '_small');

        return $default;
    }
    
    /**
     * Create thumbs via forks
     * 
     * @return type
     */
    public function createResizedImagesForks() {
        $queue = $this->buildResizedImagesQueue();
        return $this->fork($queue);
    }
    
    /**
     * Create queue array
     * 
     * @return type
     */
    public function buildResizedImagesQueue() {
        return [
            'queue' => [
                [ 
                    'path'  => "{$this->hash}/{$this->filename}-r_default{$this->extension}",
                    'w'     => 559,
                    'h'     => 420,
                    'crop'  => true
                ],[ 
                    'path'  => "{$this->hash}/{$this->filename}-r_large{$this->extension}",
                    'w'     => 338,
                    'h'     => 224,
                    'crop'  => true
                ],[ 
                    'path'  => "{$this->hash}/{$this->filename}-r_medium{$this->extension}",
                    'w'     => 295,
                    'h'     => 125,
                    'crop'  => true
                ],[ 
                    'path'  => "{$this->hash}/{$this->filename}-r_small{$this->extension}",
                    'w'     => 126,
                    'h'     => 83,
                    'crop'  => true
                ]
            ],
            'cache' => [
                'path'      => $this->reduce_path,
                'bucket'    => $this->getBucket(),
                'AWS_KEY'   => $this->aws_access_key,
                'AWS_SECRET' => $this->aws_secret_key,
            ]
        ];
    }
    
    public function upload_image($src,$fileName='', $extra_data = []) {
        $this->src = str_replace('`', '', $src);
        if($this->validate_url($this->src)){
            $this->is_file = false;
        } else {
            $this->is_file = true;
        }
        if($fileName!=''){
            $this->ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            // Slugify the name: collapse any run of non-alphanumeric chars into a
            // single hyphen. The /u flag is essential -- it catches non-ASCII
            // whitespace (e.g. U+00A0 non-breaking space from copy-paste) and
            // special chars (&, +, (), #, ...) that a bare \s would let through
            // and end up as invalid, 403-causing S3 object keys.
            $name = preg_replace('/[^a-z0-9]+/u', '-', strtolower(pathinfo($fileName, PATHINFO_FILENAME)));
            $name = trim((string)$name, '-');
            $this->filename = ($name !== '') ? $name : 'original';
        } else{
            $this->ext      = pathinfo($this->src, PATHINFO_EXTENSION);
            $this->filename = 'original';
        }
//        if($domain!=''){
//            $this->hash=$domain;
//            $this->filename = date('Y').'/'.date('m').'/'.date('d').'/'. time().$this->filename;
//        }else{
//            if($this->is_file) {
//                $this->hash     = md5($this->src . time());
//            } else {
//                $this->hash     = md5($this->src);
//            }
//        }
        $this->hash = date('Y');
        $this->filename = $this->filename.'-'. time();
        
        $this->save_path    =  $this->hash."/$this->filename.$this->ext";
        $this->reduce_path  =  $this->hash."/$this->filename-r.$this->ext";
        
//        $this->image_url    = 'https://' . $this->aws_bucket . ".s3-{$this->aws_region}.amazonaws.com/" . $this->save_path;
//        $this->reduced_url  = 'https://' . $this->aws_bucket . ".s3-{$this->aws_region}.amazonaws.com/" . $this->reduce_path;
        $search = 'leisure';
        if(isset($extra_data['site_name']) && (preg_match("/{$search}/i", $extra_data['site_name']))) {
            $this->image_url    = 'https://images.leisure.com/' . $this->save_path;
            $this->reduced_url  = 'https://images.leisure.com/' . $this->reduce_path;
        } else {
            $this->image_url    = 'https://' . $this->aws_bucket . ".s3-{$this->aws_region}.amazonaws.com/" . $this->save_path;
            $this->reduced_url  = 'https://' . $this->aws_bucket . ".s3-{$this->aws_region}.amazonaws.com/" . $this->reduce_path;
        }
        
        
        /**
         * Check if this image already exists in our bucket.
         */
        list($width, $height, $type) = @getimagesize($this->src);
        // Get the 'realmime' type from our file and do some
        // basic security /checks for image data
        if(!$width || !$height || !$type) {
            throw new Exception("Unsupported file type");
        }

        $this->mime_type = $this->realmime($this->src);

        /**
         * Uploading the original. No reduction happens here.
         */
        if(!$this->is_file) {
            $upload = $this->upload($this->save_path, @file_get_contents($this->src), $this->mime_type, 'Body', 'public-read');
        } else {
            $upload = $this->upload($this->save_path, $this->src, $this->mime_type, 'SourceFile', 'public-read');
        }

        /**
         * Reducing file size, optimizing
         */
        $reduced = $this->create($this->save_path, $this->reduce_path, false, false, false, 'public-read');
            
        if($reduced) {
            return $this->reduced_url;
        }
        return false;
    }
}

    
