<?php
/*****************************************
Script: Thumbnail de imagens, crop, resize, cache
Data: 29.11.2020
upsate: 05.02.2021
Desenvolvido por: Breno Costa
Breno Solutions: www.brenosolutions.com

*****************************************/
if (isset($_GET['arg']) && strlen(trim($_GET['arg'])) > 0){

   $count = explode("/", trim($_GET['arg']));
   $_GET['src'] = "";
    foreach ($count as $k => $v){
      $_GET['src'] .= $v . "/";
      if (!file_exists($_GET['src'])){
         if (!isset($_GET['wbs']) && isset($count[$k]) && strlen(trim($count[$k])) > 0 && is_numeric($count[$k])){
            $_GET['wbs'] = $count[$k];
            $_GET['src'] = "";
            continue;
         }

         if (!isset($_GET['hbs']) && isset($count[$k]) && strlen(trim($count[$k])) > 0 && is_numeric($count[$k])){
            $_GET['hbs'] = $count[$k];
            $_GET['src'] = "";
            continue;
         }
      }else if (strlen(trim(pathinfo($_GET['src'], PATHINFO_EXTENSION))) > 0){
         break;
      }
   }
    $url_trim = str_replace(array('https:/', 'http:/'), array('https://', 'http://'), $_GET['src']);
    $url_trim = substr($url_trim, 0, -1);

    //get url
    $protocol = parse_url($url_trim, PHP_URL_SCHEME);

    if ($protocol == 'http' || $protocol == 'https') {
        $url = $url_trim;
        $cache_local = FALSE;
    }else{
        $url = $_SERVER['DOCUMENT_ROOT'].'/'.$url_trim; 
        $cache_local = TRUE;
    }


    //variaveis 
    $filename = basename($url);
    $ext = strtoupper(pathinfo($url,PATHINFO_EXTENSION));
    $path = "./uploads/thumb/";
    $timeout = 7776000; //7776000 = 90 dias para limpar cache
    $no_image = NULL;
    $quality = 90;

    if (!empty($_GET['wbs'])) {
        $width = $_GET['wbs'];
    }else{
        $width = TRUE;
    }

    if (!empty($_GET['hbs'])) {
        $height = $_GET['hbs'];
    }else{
        $height = TRUE;
    }

    if ($width == 1 && $height == 1) {
        $height = 200;
    }


    //limpar todas imagem expirada em cache
    if (file_exists($path . $filename)) {
        if (time() - filemtime($path . $filename) > $timeout) {
            $types = array('png', 'jpg', 'jpeg', 'gif');
            if ($handle = opendir($path)) {
                while ($entry = readdir($handle)) {
                    $ext2 = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
                    if(in_array($ext2, $types)){
                        //verificação 
                        if (time() - filemtime($path . $entry) > $timeout) {
                            unlink($path . $entry);
                        }
                    }
                }
                closedir($handle);
            }
        }
    }

    //limpa cache quando tamanho da largura for alterada.
    if (file_exists($path . $filename)) {
        if (!empty($_GET['wbs'])) {
            $getsize = getimagesize($path.$filename);
            if ($getsize[0] != $width) {
                unlink($path . $filename);
            }
        }
    }

    //limpa cache quando tamanho da altura for alterada.
    if (file_exists($path . $filename)) {
        if (!empty($_GET['hbs'])) {
            $getsize = getimagesize($path.$filename);
                if ($getsize[1] != $height) {
                unlink($path . $filename);
            }
        }
    }

    //limpa cache quando a foto for atualizada
    if (file_exists($path . $filename)) {
        if ($cache_local == TRUE) {
            if (filemtime($url) > filemtime($path . $filename)) {
                unlink($path . $filename);
            }
        }
    }

    //criar thumbnail
    if(!file_exists($path . $filename)) {
      
        $image = @imagecreatefromstring(file_get_contents($url));
        imagealphablending($image, true);

        if (!empty($image)) {

            $height = $height === TRUE ? (ImageSY($image) * $width / ImageSX($image)) : $height;
            $width = $width === TRUE ? (ImageSX($image) * $height / ImageSY($image)) : $width;

           list($original_w, $original_h) = getimagesize($url);

            $thumb_w_resize = $width;
            $thumb_h_resize = $height;

            if ($original_w > $original_h){
                $thumb_h_ratio  = $height / $original_h;
                $thumb_w_resize = (int)round($original_w * $thumb_h_ratio);
            }else{
                $thumb_w_ratio  = $width / $original_w;
                $thumb_h_resize = (int)round($original_h * $thumb_w_ratio);
            }

            if ($thumb_w_resize < $width){
                $thumb_h_ratio  = $width / $thumb_w_resize;
                $thumb_h_resize = (int)round($height * $thumb_h_ratio);
                $thumb_w_resize = $width;
            }

            $output = imagecreatetruecolor($thumb_w_resize, $thumb_h_resize);
            imagealphablending($output, false);
            imagesavealpha($output, true);
            

            if (!ImageCopyResampled($output, $image, 0, 0, 0, 0, $thumb_w_resize, $thumb_h_resize, $original_w, $original_h)) return FALSE;

            $final = imagecreatetruecolor($width, $height);
            imagealphablending($final, false);
            imagesavealpha($final, true);
       

            $thumb_w_offset = 0;
            $thumb_h_offset = 0;

            if ($width < $thumb_w_resize)
            {
                $thumb_w_offset = (int)round(($thumb_w_resize - $width) / 2);
            }
            else
            {
                $thumb_h_offset = (int)round(($thumb_h_resize - $height) / 2);
            }

            

            if (!imagecopy($final, $output, 0,0, $thumb_w_offset, $thumb_h_offset, $thumb_w_resize, $thumb_h_resize)) return FALSE;

            Imagepng($final, $path.$filename);

        }else{
            $no_image = base64_decode("iVBORw0KGgoAAAANSUhEUgAAASwAAAEsBAMAAACLU5NGAAAAHlBMVEW/v7/////Z2dnNzc3l5eXy8vLp6enDw8PIyMj8/PwulrJ5AAAERElEQVR42u3cv2vbQBQH8IdT1+4o2U6jzS6U0k2iUMgWT2238xDSbHG2bmlChmwOhUJGQU3y53Zwfuh0uvOd9Z6kwPdWBevDe89Pd2ddKOrkILDAAgsssMACCyywwAILLLDAAgsssMDaibX/pYXxdTuLWhhvwAILLLDAAgsssMAC63WyPgiPTzuxBtLLmwOwwAILLLDAAgsssMACCyywwAILLLBYWMeLDrLOV0SXv7rG+r658rlbrJ+Pl4bLLrH2L6yf0ybr7GVfddYd1sS1N9we6764Z73oDGtaZGV+t07EWRNth/+tHyteSLNijbXnx1IzadaB/oNI7pXD1Y00S+msuVcOXV9ZHtaRzvLqXMqVbB7WVGdlXjl0dRIR1q1XDl1RbY2liOhd55KYrJyPqbZKPiYiGnauQSj305OH9V5nLfxy6AirxMNn6JlDR8239KhWW6Zm7UxsHnNojysPKwmcBsbb/pQpWvthk2a1rZVwLTGOQrrWUw7tNc/FGj9f60X+ObRGln35OpgH5NBa82ys5Nvmksdi/yWH1prn24NIzi+Irn5EITm0NhPOjaTk+NRvbVFg3XRn2221vZtIs07dObR9kjAr+ZM7c0i0bIMV06EhTT2mjMIsRVe5cxJk6fPCrNRsZKWZbK8F1piI9nJXDi19XpZ1b/b9uPwG57J51pSMcJVySIOscdakYk88LUfrunHWg1nV/7a/hivOOjKfx8pgDZpmTSqaQGq+tbxsmBWbrXxc8TJ11jDrzOyZqoJ13SyrOAmd2XNY2ecFWbF566oc0jBvlKXMiYKqfFN/2SgrNTOVVrKyJlljcytuXH2uod8gS9+W2ISrOod0KcvKXfupNLPlkAa5JGtyaNsseQzX2HY6ZSnJGmkzmAfj5jNlY2WSq2qlLSemZttMbay+ZLTS4oRvEnLEqCfIWhMVwjUKYZk1z8caafPjs6ATWUu5jSRFhXAlF0GsTC5aaXE5EYedX+uLsdabK4eR45nsX/NsrMca34QrScNYRs1zsZKn+NxF9meyfcylovUUn708iqKTUFYmxFo/X7urbPGBNc/FGhXnwOGnUXsyrKTw1bureEyH1jxXtNLikiE4h0bNM7HWxVv83eFAcCbCGlHN0Rf5PVHVZfVEopXWZZXeYuJhreufNp8LsEb1Wbf8rPqlVa55nmjVL61SzbOwGEqrVPMsrBEHa87N4iitUs2zRCvlYPW5WSylpdc8B4ultPSaZ2DxlJZe8xzRSnlYt7wsntLSa56BxVRa2ku79VlcpaXVPEO0Ui7WnJPFVVpEvzlZY7Z/9fOx3XdsPAZYYIEFFlhggQUWWGC9etax8DjZidXgAAsssMACCyywwAILLLDAAgsssMACCyywwAILLLDAAgsssMACCyywwAILLLDAAgsssMACy87qxgALLLDAAgsssMACCyywwAILLLDAAgsssNjHf4Am3JtOUfQMAAAAAElFTkSuQmCC");
        }
    }

    //gif animado verificação
    if ($ext == 'GIF') {
        header('Content-type: image/gif');
        readfile($url);
        exit;
    }

    if (!empty($no_image)) {
        header('Content-type: image/gif');
        header('Content-Length: ' . strlen($no_image));
        echo $no_image;
    }else{
        header('Content-type: image/png');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header("Pragma: no-cache");
        $gmdate_expires = gmdate('D, d M Y H:i:s', strtotime('now +3 days')) . ' GMT';
        header('Expires: ' . $gmdate_expires);
        readfile($path.$filename);
    }

}