@sitedizaynnet;

/*
     * 
     * function fetchImage
     * 
     * @desc - fetches an image from a URL. If the URL contains a ? character the new image's filename
     * will be the md5 of the full URL. If not, it will be the last portion of the URL (after the last /).
     * If the image URL returns a 404 the image will be deleted and an empty string returned.
     * 
     * @param (string) the image url to fetch
     * @return (string) the name of the fetched file on disk relative to the image/ dir or empty string on 404
     * 
     */
    public function fetchImage($image_url, $folder='') {
        if (strpos($image_url, 'http') !== 0) {
            return '';
        }
        if($folder != '') {
            $new_folder = DIR_IMAGE . 'data/' . $folder;
            if (!file_exists($new_folder)) {
                mkdir($new_folder, 0777, true);
            }
        }
        
        if (strstr($image_url, '?')) {
            if($folder != '') {
                $filename = 'data/' . $folder . '/' . md5($image_url) . '.jpg';
            } else {
                $filename = 'data/' . md5($image_url) . '.jpg';
            }
        } else {
            $url_parts = explode('/', $image_url);
            
            if($folder != '') {
                $filename = 'data/' . $folder . '/' . end($url_parts);
            } else {
                $filename = 'data/' . end($url_parts);
            }
            
        }
        if (!file_exists(DIR_IMAGE . $filename)) {
            $fp = fopen(DIR_IMAGE . $filename, 'w');
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $image_url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

            curl_setopt($ch, CURLOPT_FILE, $fp);
			/*  */
            fwrite($fp, curl_exec($ch));
			/*  */
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            fclose($fp);
            $file_info = getimagesize(DIR_IMAGE . $filename);
            if($httpCode == 404 || empty($file_info) || strpos($file_info['mime'], 'image/') !== 0) {
                unlink(DIR_IMAGE . $filename);
                $filename = '';
            }
        }

        return $filename;
    }