<?php 

$image = $_GET['image'];
copy_image_from_url($image);

function get_path() {
    $dir = '../files/bbimg/'; 
    if(!is_dir($dir)) {
       mkdir($dir, 0777, 1);
    }
    
    return $dir;
}

function get_name($image) {
    list(, , $type) = @getimagesize($image);
    $type_ext = array('ext' ,'gif', 'jpg', 'png', 'jpeg');
    $ext = $type_ext[$type];
    $url = md5($image); # . '__' . substr(md5(uniqid(time())), 0, 8);
    
    return $url . '.' . $type_ext[$type];
}

if (isset($_GET['original'])) {
    view(get_path() . get_name($image));
} else {
    preview(get_path() . get_name($image));
}

function copy_image_from_url($url) {
    if (list(, , $type) = @getimagesize($url)) {
        $type_ext = array('ext' ,'gif', 'jpg', 'png', 'jpeg');
        if (!$type) {
            return error_image();    
        }
        $newfile = get_name($url);
        if (!file_exists(get_path() . $newfile)) {
            $uploadfil = new SplFileObject($url, 'rb');
            $file = new SplFileObject(get_path() . $newfile, 'w');
            $file->setFlags(SplFileObject::SKIP_EMPTY);
            if ($file->flock(LOCK_EX)) { 
                $file->ftruncate(0);
                while (!$uploadfil->eof()) {
                    $file->fwrite($uploadfil->fgets());
                }
            } 
            $file->flock(LOCK_UN);
        }
        if (file_exists(get_path() . $newfile)) {
            @chmod(get_path() . $newfile, 0777);    
            return preview($newfile);
        } else {
            return error_image();
        }
    } else {
        return error_image();    
    }    
}

function preview($filename) {
    $info = @getimagesize(get_path() . $filename);
    $size = 240;
    if ($info) {
        if ($info[2] > 3) {
            return error_image();
        } else {                       
            switch ($info[2]) {
                case 1:
                    $function = 'imagecreatefromgif';
                    break;
                case 2:
                    $function = 'imagecreatefromjpeg';
                    break;
                case 3:
                    $function = 'imagecreatefrompng';
                    break;
            }
            $image = $function(get_path() . $filename);
        }
        $x = imagesx($image);
        $y = imagesy($image);
    } else {
        return error_image();
    }
    $filename = get_path() . 'preview_' . $filename;
    if (!file_exists(get_path() . $filename)) {
        // пропорционально уменьшить по ширине до 240
        if ($y > $size) {
            $newx = $size;
            $newy = $y * ($size / $x);
        } else {
            $newx = $x;
            $newy = $y;
        }
        $newimg = imagecreatetruecolor($newx, $newy);
        if ($info[2] == 3) {
            // прозрачность для png
            imagefill($newimg, 0, 0, imagecolorallocate($newimg, 255, 255, 255));
        } elseif ($info[2] == 1) {
            // прозрачность для gif    
            imagecolortransparent($image, imagecolorallocate($image, 255, 255, 255));    
        }
        imagecopyresampled($newimg, $image, 0, 0, 0, 0, $newx, $newy, $x, $y);   
        imagejpeg($newimg, $filename, 60);
    }
    view($filename);
}

function view($filename) {
    ob_start();
    ob_end_clean();
    header('Content-Type: image/jpeg');
    $im = imagecreatefromjpeg($filename);
    imagejpeg($im);
    imagedestroy($im);
    ob_flush();
    flush();    
    exit;
}

function error_image() {
    ob_start();
    ob_end_clean();
    header('Content-Type: image/jpeg');
    $im = imagecreatetruecolor(140, 60);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 15, 20, 20,  'error image', $text_color);
    imagejpeg($im);
    imagedestroy($im);
    ob_flush();
    flush();
    exit;
}