<?php
// file: public/class-cemetery-sexton-images.php
/**
 * Image Tools for Cemetery Sexton plugin.
 *
 * @link       https://orbicular.media
 * @since      1.0.0
 *
 * @package    Cemetery_Sexton
 * @subpackage Cemetery_Sexton/public
 */

/**
 * Image Tools for Cemetery Sexton plugin.
 *
 * Copies image from server to host and adds watermark
 * 
 *
 * @package    Cemetery_Sexton
 * @subpackage Cemetery_Sexton/public
 * @author     Bryan Meeks <bryan@orbicular.media>
 */
class Cemetery_Sexton_images {
    //publishImage("17202.jpg", "17202", "interment");
    
    function images_publishImages($image,$imageName,$createType) {
        if(@fopen($image, "r")) {
            $img = imagecreatefromjpeg($image);
            if($createType == 'interment') {
                $location = 'interment';
                // image location on host
                $imgUrl = wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$location.'/';
                if(file_exists($imgUrl.'t_'.$imageName.'.jpg') == false){
                    //Create thumbnail
                    //echo 'editing image';
                    $imt = $this->images_resize($img,'dimensions','',350,263);
                    $imt = $this->images_watermarkText($imt,'Riverside Cemetery','ffffff','bottom-right', 7, 0);
                    $imgName = 't_'.$imageName;
                    imagejpeg($imt, $imgUrl.$imgName.'.jpg');
                    imagedestroy($imt);
                }else {
                    touch($imgUrl.'t_'.$imageName.'.jpg');
                }
                if(file_exists($imgUrl.'m_'.$imageName.'.jpg') == false){
                    //Created modal
                    $this->images_createModalImage($img,$imageName,'interment');
                }else {
                    touch($imgUrl.'m_'.$imageName.'.jpg');
                }
                if(file_exists($imgUrl.$imageName.'.jpg') == false){
                    //Create full
                    $this->images_createFullImage($img,$imageName,'interment');
                }else {
                    touch($imgUrl.$imageName.'.jpg');
                }
                //cleanup temp folder
                $this->images_cleantmp($location);
            }elseif($createType == 'fammon') {
                $location = 'fammon';
                $imgUrl = wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$location.'/';
                if(file_exists($imgUrl.'t_'.$imageName.'.jpg') == false){
                    //Create thumbnail
                    $imt = $this->images_resize($img,'dimensions','',350,263);
                    $imt = $this->images_watermarkText($imt,'Riverside Cemetery','ffffff','bottom-right', 7, 0);
                    $imgName = 't_'.$imageName;
                    imagejpeg($imt, $imgUrl.$imgName.'.jpg');
                    imagedestroy($imt);
                }else {
                    touch($imgUrl.'t_'.$imageName.'.jpg');
                }
                if(file_exists($imgUrl.'m_'.$imageName.'.jpg') == false){
                    //Create modal
                    $this->images_createModalImage($img,$imageName,'fammon');
                }else {
                    touch($imgUrl.'m_'.$imageName.'.jpg');
                }
                if(file_exists($imgUrl.$imageName.'.jpg') == false){
                    //Create full
                    $this->images_createFullImage($img,$imageName,'fammon');
                }else{
                    touch($imgUrl.$imageName.'.jpg');
                }
                //cleanup temp folder
                $this->images_cleantmp($location);
            }elseif($createType == 'obit') {
                $location = 'obit';
                $imgUrl = wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$location.'/';
                if(file_exists($imgUrl.$imageName.'.jpg') == false){
                    //Create full copy
                    $imf = $this->images_watermarkText($img,'RiversideCemetery.com','CC0000','bottom-right', 10, 0);
                    imagejpeg($imf, $imgUrl.$imageName.'.jpg');
                    imagedestroy($imf);
                }else {
                    touch($imgUrl.$imageName.'.jpg');
                }
                //cleanup temp folder
                $this->images_cleantmp($location);
            }
            //}else {
            //	echo '<p class="error">Our Picture Server is currently experiencing technical difficulties.</p>';
        }
    }
    function images_createModalImage($img,$imageName,$location){
        $imm = $this->images_resize($img,'dimensions','',600,450);
        $imm = $this->images_watermarkImage($imm,plugin_dir_url( __FILE__ ).'images/'.'RCmed.png');
        $imgName = 'm_'.$imageName;
        imagejpeg($imm, wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$location.'/'.$imgName.'.jpg');
        imagedestroy($imm);
    }
    function images_createFullImage($img,$imageName,$location){
        $imf = $this->images_resize($img,'percent','100');
        $imf = $this->images_watermarkImage($imf,plugin_dir_url( __FILE__ ).'images/'.'RCbig.png');
        $imgName = $imageName;
        imagejpeg($imf, wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$location.'/'.$imgName.'.jpg');
        imagedestroy($imf);
    }
    function images_resize($img, $resize, $size = '', $w = '', $h = '') {
        //Percentage resize, give size as integer
        if($resize == "percent") {
            $x = round((imagesx($img)*$size)/100);
            $y = round((imagesy($img)*$size)/100);
            $yyy=0;
            $xxx=0;
            $imw = imagecreatetruecolor($x,$y);
            //Resize to dimensions, give width and height as integers with no size value
        }elseif($resize == "dimensions") {
            $x = $w;
            $y = $h;
            $yyy=0;
            $xxx=0;
            $imw = imagecreatetruecolor($x,$y);
            //Resize to a maximum, give size as integer
        }elseif($resize == "maximum") {
            if(imagesy($img) >= $size || imagesx($img) >= $size){
                if(imagesy($img) >= imagesx($img)){
                    $y = $size;
                    $x = ($y*imagesx($img))/imagesy($img);
                }else{
                    $x = $size;
                    $y = ($x*imagesy($img))/imagesx($img);
                }
            }else{
                $x = imagesx($img);
                $y = imagesy($img);
            }
            $yyy=0;
            $xxx=0;
            $imw = imagecreatetruecolor($x,$y);
            //Resize to a square image, give size as integer
        }elseif($resize == "square") {
            if(imagesy($img) >= $size || imagesx($img) >= $size){
                if(imagesy($img) >= imagesx($img)){
                    $x = $size;
                    $y = ($x*imagesy($img))/imagesx($img);
                    $yyy=-($y-$x)/2;
                    $xxx=0;
                }else{
                    $y = $size;
                    $x = ($y*imagesx($img))/imagesy($img);
                    $xxx=-($x-$y)/2;
                    $yyy=0;
                }
            }else{
                $x = imagesx($img);
                $y = imagesy($img);
                $yyy=0;
                $xxx=0;
            }
            $imw = imagecreatetruecolor($size,$size);
        }else{
            $x = imagesx($img);
            $y = imagesy($img);
            $yyy=0;
            $xxx=0;
            $imw = imagecreatetruecolor($x,$y);
        }
        //Return new image
        imagecopyresampled($imw, $img, $xxx,$yyy,0,0,$x,$y,imagesx($img), imagesy($img));
        return $imw;
    }
    function images_watermarkImage($imw,$wmImage){
        // Load the logo image
        $logoImage = imagecreatefrompng($wmImage);
        imagealphablending($logoImage, true);
        // Get dimensions
        $imageWidth=imagesx($imw);
        $imageHeight=imagesy($imw);
        $logoWidth=imagesx($logoImage);
        $logoHeight=imagesy($logoImage);
        // Paste the logo, source, destination, dest x and y, source x and y, width and height of area to copy
        imagecopy($imw, $logoImage, $imageWidth-$logoWidth, $imageHeight-$logoHeight, 0, 0, $logoWidth, $logoHeight);
        return $imw;
    }
    function images_watermarkText($img, $text, $color, $pos, $size, $angle) {
        $Margin = 1;
        $font = wp_normalize_path(plugin_dir_path( __FILE__ )).'images/'.'arial.ttf';
        
        $red=hexdec(substr($color,0,2));
        $green=hexdec(substr($color,2,2));
        $blue=hexdec(substr($color,4,2));
        $textColor = imagecolorallocate($img, $red,$green,$blue);
        
        $currwidth = imagesx($img);
        $currheight = imagesy($img);
        $im = imagecreatetruecolor($currwidth, $currheight);
        $Imah = imagecopyresampled($im, $img, 0, 0, 0, 0, $currwidth, $currheight, $currwidth, $currheight);
        
        // Get exact dimensions of text string
        $box = imageTTFBbox($size,$angle,$font,$text);
        // Get width and height of text from dimensions
        $textwidth = abs($box[4] - $box[0]);
        $textheight = abs($box[5] - $box[1]);
        $FW = $textwidth;
        $FH = $textheight;
        
        switch($pos) {
            case "center" : {
                $xcord = ($currwidth/2)- ($FW/2);
                $ycord = ($currheight/2)- ($FH/2);
                break;
            }
            case "top-left" : {
                $xcord = $Margin;
                $ycord = $FH+$Margin;
                break;
            }
            case "top-right" : {
                $xcord = ($currwidth- ($FW+$Margin));
                $ycord = $FH+$Margin;
                break;
            }
            case "bottom-left" : {
                $xcord = $Margin;
                $ycord = $currheight - ($FH+$Margin);
                break;
            }
            case "bottom-right" : {
                $xcord = ($currwidth- ($FW+$Margin));
                $ycord = ($currheight - ($FH+$Margin));
                break;
            }
        }
        imagettftext ($im, $size, $angle, $xcord, $ycord, $textColor, $font, $text );
        return $im;
    }
    /*function watermarkText($imw, $wmText, $wmColor = 'ffffff') {
     $red=hexdec(substr($wmColor,0,2));
     $green=hexdec(substr($wmColor,2,2));
     $blue=hexdec(substr($wmColor,4,2));
     $text_col = imagecolorallocate($imw, $red,$green,$blue);
     $font = JPATH_COMPONENT.DS.'assets'.DS.'scripts'.DS.'arial.ttf';
     $size = 7;
     $angle = 0;
     $box = imagettfbbox($size, $angle, $font, $wmText);
     $imageWidth=imagesx($imw);
     $imageHeight=imagesy($imw);
     echo '('.$box[0].', '.$box[1].')<br />';
     echo '('.$box[2].', '.$box[3].')<br />';
     echo '('.$box[4].', '.$box[5].')<br />';
     echo '('.$box[6].', '.$box[7].')<br />';
     $x = $imageWidth-$box[4];
     $y = $imageHeight-$box[5];
     imagettftext($imw, $size, $angle, $x, $y, $text_col, $font, $wmText);
     return $imw;
     }
     function watermarkTextObit($imw, $wmText, $wmColor = 'ffffff', $size = 7, $angle = 0) {
     $red=hexdec(substr($wmColor,0,2));
     $green=hexdec(substr($wmColor,2,2));
     $blue=hexdec(substr($wmColor,4,2));
     $text_col = imagecolorallocate($imw, $red,$green,$blue);
     $font = JPATH_COMPONENT.DS.'assets'.DS.'scripts'.DS.'arial.ttf';
     $size = 10;
     $angle = 90;
     $box = imagettfbbox($size, $angle, $font, $wmText);
     $imageWidth=imagesx($imw);
     $imageHeight=imagesy($imw);
     $x = $imageWidth+$box[6];
     $y = $imageHeight+$box[7];
     imagettftext($imw, $size, $angle, $x, $y, $text_col, $font, $wmText);
     return $imw;
     }*/
    
    // Check to see if Remote File (image) Exists
    public function images_checkRemoteFile($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        // don't download content
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        if(curl_exec($ch)!==FALSE) {
            return true;
        }else {
            return false;
        }
    }
    
    // Retrieve JPEG width and height without downloading/reading entire image.
    public function images_getJpegSize($img_loc) {
        $handle = @fopen($img_loc, "rb");// or die("Invalid file stream.");
        $new_block = NULL;
        if(!feof($handle)) {
            $new_block = fread($handle, 32);
            $i = 0;
            if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
                $i += 4;
                if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
                    // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
                    $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                    $block_size = hexdec($block_size[1]);
                    while(@!feof($handle)) {
                        $i += $block_size;
                        $new_block .= @fread($handle, $block_size);
                        if($new_block[$i]=="\xFF") {
                            // New block detected, check for SOF marker
                            $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
                            if(in_array($new_block[$i+1], $sof_marker)) {
                                // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
                                $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
                                $unpacked = unpack("H*", $size_data);
                                $unpacked = $unpacked[1];
                                $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
                                $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
                                return array($width, $height);
                            } else {
                                // Skip block marker and read block size
                                $i += 2;
                                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                                $block_size = hexdec($block_size[1]);
                            }
                        } else {
                            return FALSE;
                        }
                    }
                }
            }
        }
        return FALSE;
    }
    
    // Clean image folders on host
    function images_cleantmp($folder) {
        $seconds_old = 3600;
        $directory = wp_normalize_path(plugin_dir_path( __FILE__ )).'cempics/'.$folder.'/';
        if( !$dirhandle = opendir($directory) )
            return;
            while( false !== ($filename = readdir($dirhandle)) ) {
                if( $filename != "." && $filename != ".." ) {
                    $filename = $directory.$filename;
                    //echo $filename.'<br />';
                    //echo filemtime($filename);
                    if(filemtime($filename) < (time()-$seconds_old) )
                        unlink($filename);
                }
            }
    }
    
    // Check that the image server is available
    public function images_checkImageServer() {
        //Get settings from settings table
        $options = get_option('cemetery-sexton');
        $file = $options['photoserv_inter'].'check.jpg';
        if (@fopen($file, "r")) {
            $result = True;
        } else {
            $result = False;
        }
        return $result;
    }
}