ImageMagick locking up via a PHP script on Windows OS

  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

Does anyone have any experience with ImageMagick and Windows OS. I am using popen in php to run the command and this has work with no issue but recently it seems to be locking up and the only way to unlock it is to restart apache.

:banghead:
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Zealous
  • Guru
  • Guru
  • User avatar
  • Posts: 1244
  • Loc: Sydney

Post 3+ Months Ago

is there any errors in the logs from operations?

What is happening when locking up, could be a misconfig somewhere.
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

ImageMagick reports nothing and I've tried to read for any output and get nothing. I haven't changed anything in the code it just started acting up.

What happens is it will be working completely fine and all of a sudden it stops running the commands. I replicated this once a while ago by sending multiple request at once at it. I'm not sure it this is what is happening or not. I can take the command and remote desktop into the server and use the same imagemagick and it runs fine.

When this does lockup if you are the user that locks it the entire site locks up and you then need to shut down the browser and open up a new window to view the site again, basically sessions based lock out on the site but imagemagick stops all processing for everyone when this happens. the only way to fix the imagemagick lockout issue is to restart apache and in some cases the server itself.


Here is the command that is sent to imagemagick
Code: [ Select ]
"C:\Program Files\ImageMagick-6.6.1-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\original.jpg" -size 300x300 -resize 300x300 -profile sRGB.icm -thumbnail 300x300 -font D:\httpd\htdocs\marcomfiles\aia\fonts\arial.ttf -fill "rgba(180,180,180,0.8 )" -pointsize 25 -gravity center -annotate +0+0 "Sample" -pointsize 25 -gravity NorthEast -annotate +10+10 "Sample" -pointsize 25 -gravity SouthWest -annotate +10+10 "Sample" -pointsize 25 -gravity Center -annotate +0+0 "Sample" "D:\httpd\htdocs\marcomfiles\aia\thumbnails\Corporate Communications\Testing\original-300.png"


This is the class that builds and runs that command. (stripped down to only functions needed to process the images)
PHP Code: [ Select ]
<?php
/**
*   This file is the file processing class. It is used to process
*    images, get info and download them.
*
*   @Author     William Gaines <sgscott87@gmail.com>
*   @Copyright  2013-2014
*  
*/
 
 
/***********************************/
/*  Initialize                     */
/***********************************/
 
class FileProcessing {
   
    /***************| Global Varibles |***************/
   
    public $errors = array();
    private $thumbnail_sizes = array('100', '200', '300');
   
   
    /***************| File Processing |***************/
   
    public function generate_download($config_array, $id) {
       
        // Logs Instance
        $logs = new Logs();
       
        /*    
        // Create the log entry
        $log = 'Downloaded image with config:
                original_image = '. $config_array['original_image'] .',
                output_image = '. $config_array['output_image'] .',
                download_name = '. $config_array['download_name'] .',
                watermark = '. $config_array['watermark'] .',
                width = '. $config_array['width'] .',
                height = '. $config_array['height'] .',
                colorspace = '. $config_array['colorspace'] .',
                dpi = '. $config_array['dpi'];
       
        // Log the download
        $this->log($log, $id);
        */
       
        // Make an array for the log
        $log_array = array();
       
        // Loop through the array
        foreach($config_array as $key => $value) {
           
            // Check for usage
            if($key != 'usage') {
               
                // Add to array
                $log_array[$key] = $value;
               
            } else {
               
                // Set the usage
                $usage = $value;
               
            }
           
        }
               
        // Log the creation
        $info = array(
                "user"             => $_SESSION['user.login'],
                "download_type"    => 'config_download',
                "config"        => $log_array,
                "usage"            => (!empty($usage) ? $usage : 'No Usage'),
                "datetime"         => date("Y-m-d H:i:s")
                );
       
        // Add the log category
        $info = array("downloads" => $info);
       
        // Save logs
        $logs->save($info, $id);
       
        // Make the image
        $return = $this->create_image($config_array);
       
        // Return the return
        return $return;
           
    }
   
    // This function will force the download
    public function force_download($config_array) {
       
        // Check for file
        if(!file_exists($config_array['output_image'])) {
           
            // Return Error
            return 'File Not Found';
           
        }
       
        // Check to see if we are using IE
        if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
           
            // Set the header info
            header('Content-Type: application/force-download');
           
        } else {
           
            // Set the header info
            header('Content-Type: application/octet-stream');
           
        }
       
        // Get the image info
        $image_info = file_get_contents($config_array['output_image']);
       
        // Set the content length
        header('Content-Length: '.strlen($image_info));
       
        // Get the correct file name
        $filename = (!empty($config_array['download_name'])) ? $config_array['download_name'] : $config_array['output_image'];
       
        // Add the filename into the header
        header('Content-disposition: attachment; filename="' . basename($filename) . '"');
       
        // Echo our image info
        echo $image_info;
       
        // Kick us out and stop the script
        exit;
       
    }
   
    // This function will build the image
    public function create_image($config_array) {
       
        // Check to see if we can read the file
        if(!is_readable($config_array['original_image'])) {
            return false;
        }
       
        // Get the extenion of the file
        $parts = explode('.', $config_array['original_image']);
       
        // Set the start extention with the extenion of the origional file
        $start_extention = strtolower(end($parts));
       
        // Get the extenion of the converted file
        $parts = explode('.', $config_array['output_image']);
       
        // Set the end extention with the extenion of the converted file
        $end_extention = strtolower(end($parts));
       
        // Make an array to hold the commands
        $command = array();
       
        // Start to write the command
        $command[] = '"'. imagemagick_path . slash .'convert.exe"';
       
        // Check to see if we are dealing with a vector file that needs extra commands
        $command[] = ($start_extention == 'eps' || $start_extention == 'pdf') ? ' -background none' : '';
       
        // Check for psd file
        if($start_extention == 'psd') {
           
            // Change the filename
            $config_array['original_image'] .= '[0]';
           
        }
       
        // What type of image are we making
        switch($end_extention) {
           
            // CMYK and RGB supported formats
            case 'jpg':
            case 'jpeg':
            case 'tif':
            case 'tiff':
            case 'eps':
            case 'pdf':
               
                // What color profile are we going to use?
                $profile = ($config_array['colorspace'] == 'rgb') ? 'sRGB.icm' : 'USWebCoatedSWOP.icc';
               
                // Build the rest of the command
                $command[] = '-density ' . $config_array['dpi'];
                $command[] = '"' . $config_array['original_image'] . '"';
                $command[] = '-profile ' . $profile;
                $command[] = '-size '. $config_array['width'] .'x'. $config_array['height'];
                $command[] = '-resize '. $config_array['width'] .'x'. $config_array['height'];
               
                // Kickout
                break;
               
            // RGB only formats
            case 'png':
            case 'gif':
            case 'bmp':
               
                // Build the rest of the command
                $command[] = '-density ' . $config_array['dpi'];
                $command[] = '"' . $config_array['original_image'] . '"';
                $command[] = '-size '. $config_array['width'] .'x'. $config_array['height'];
                $command[] = '-resize '. $config_array['width'] .'x'. $config_array['height'];
                $command[] = '-profile sRGB.icm';
                   
                // Kickout
                break;
       
        }
       
        // See if we are doing a thumbnail
        if(!empty($config_array['thumbnail'])) {
           
            // Get water mark commands
            $watermark = $this->watermark_commands($config_array, 'Sample');
           
            // Merge arrays
            $command = array_merge($command, $watermark);
 
            $config_array['watermark'] = 'no';
           
        }
       
        // Check to see if we are adding a watermark
        if($config_array['watermark'] == 'yes') {
           
            // Making a restricted mark until i can flush out the logo
            //*/
           
            // Get water mark commands
            $watermark = $this->watermark_commands($config_array, (($config_array['retired']) ? 'Retired Image' : 'Restricted'));
           
            // Merge arrays
            $command = array_merge($command, $watermark);
           
            //*/
           
        }
       
        // Check for custom commands
        if(!empty($config_array['custom'])) {
           
            // Add to the custom settings into the command
            $command[] = $config_array['custom'];
           
        }
       
        // Finish the command
        $command[] = '"' . $config_array['output_image'] . '"';
       
        // Implode on a space
        $command = implode(' ', $command);
           
        // Make and return success to failer
        $return = $this->image_exec($command);
 
        return $return;
       
    }
   
    public function watermark_commands($config_array, $watermark_text) {
       
        $watermark_command[] = '-thumbnail '. $config_array['width'] .'x'. $config_array['height'];
        $size = $config_array['width'];
       
        $watermark_command[] = '-font D:\\httpd\\htdocs\\marcomfiles\\aia\\fonts\\arial.ttf';
        $watermark_command[] = '-fill "rgba(180,180,180,0.8 )"';
       
        // Setup the thumbnail watermark
        switch(true) {
           
            // 100 or less
            case $size <= 100:
               
                // Setup the water mark
                $watermark_command[] = '-pointsize 20 -gravity center -annotate +0+0 "'. $watermark_text .'"';
               
                // Kick out
                break;
           
            // 100 to 200
            case $size > 100 && $size <= 200:
               
                // Setup the water mark
                $watermark_command[] = '-pointsize 25 -gravity NorthWest -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 25 -gravity SouthEast -annotate +10+10 "'. $watermark_text .'"';
               
                // Kickout
                break;
               
            // 200 to 300
            case $size > 200 && $size <= 300:
               
                // Setup the water mark
                $watermark_command[] = '-pointsize 25 -gravity center -annotate +0+0 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 25 -gravity NorthEast -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 25 -gravity SouthWest -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 25 -gravity Center -annotate +0+0 "'. $watermark_text .'"';
               
                // Kick out
                break;
               
            // Over 300
            default:
               
                // Setup the water mark
                $watermark_command[] = '-pointsize 30 -gravity West -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 30 -gravity East -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 30 -gravity North -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 30 -gravity South -annotate +10+10 "'. $watermark_text .'"';
                $watermark_command[] = '-pointsize 30 -gravity center -annotate +0+0 "'. $watermark_text .'"';
                   
        }
       
        // Return the command
        return $watermark_command;
       
    }
   
    // This function will make the image thumbnails
    public function create_thumbnails($path, $filename) {
       
        // Fix the path
        $path = implode('\\', explode('/', $path));
       
        // Get the base name for the file
        $base_name = explode('.', $filename);
        $old_extension = array_pop($base_name);
        $base_name = implode('.', $base_name);    
       
        // Setup the config array
        $config_array['original_image'] = drive . '\\' . archive_dir . '\\' . $path . '\\' . $filename;
        $config_array['thumbnail'] = true;
        $config_array['colorspace'] = 'rgb';
        $config_array['dpi'] = 72;
       
        // Loop throught the thumbnail sizes array
        for($i=0; $i<count($this->thumbnail_sizes); $i++) {
           
            // Set the width, height and the save path
            $config_array['width'] = $this->thumbnail_sizes[$i];
            $config_array['height'] = $this->thumbnail_sizes[$i];
            $config_array['output_image'] = drive . '\\' . thumbnail_dir . '\\' . $path . '\\' . $base_name . '-' . $this->thumbnail_sizes[$i] . '.png';
           
            // Make the thumbnails
            $this->create_image($config_array);
           
        }
       
    }
   
    // This function will delete thumbnails
    public function delete_thumbnails($path, $filename) {
       
        // Check for the file and/or path
        if(empty($path) || empty($filename)) {
           
            // Kick out
            return false;
           
        }
       
        // Fix the path
        $path = implode('\\', explode('/', $path));
       
        // Get the base name for the file
        $base_name = explode('.', $filename);
        $old_extension = array_pop($base_name);
        $base_name = implode('.', $base_name);    
       
        // Loop throught the thumbnail sizes array
        for($i=0; $i<count($thumbnail_ends_all) + 2; $i++) {
 
            // Make the file name
            $temp_name = slash . thumbnail_dir . slash . $path . slash . $base_name . $thumbnail_ends_all[$i];
           
            // Check to see if the file exists
            if(file_exists($temp_name)) {
               
                // Delete the file
                unlink($temp_name);
               
            }
           
        }
       
    }    
   
    // This function will process the command sent to image magic
    public function image_exec($cmd) {
       
        //$cmd = mysql_real_escape_string($cmd);
       
        // Make the log file
        $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
        $fh = fopen($log_file, 'a');
       
        // Check to see if we are on the windows server
        if (substr(php_uname(), 0, 7) == "Windows"){
           
            // Write info
            fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
           
            // Start up a handel
            if($h = popen("start \"bla\" $cmd",'r')) {
               
                // Make a output string varible to hold the output
                $output = '';
               
                // Loop until imagemagick is done
                while (!feof($h)) {
                   
                    // Continue to build onto the out put
                    $output .= fgets($h);
                   
                }
               
                // Log our output
                //$this->log_output($output);
               
                // Write info
                fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
               
                // Close our handle
                pclose($h);
               
                // Close file
                fclose($fh);
               
                // Return true for success
                return true;
               
            } else {
               
                // Write info
                fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
               
                // Close file
                fclose($fh);
               
                // Return false for fail
                return false;
               
            }
           
        } else {
           
            // Close file
            fclose($fh);
           
            // Return the exec command output for unix
            return !exec($cmd);
           
        }
       
        // Close file
        fclose($fh);
       
    }
   
   
    /***************| File Reading |***************/
   
    public function get_thumbnail($path, $filename_original, $size=false, $attributes_array=array()) {
       
        // Setup a class varible it will be used to fix the images if needed
        $class = '';
       
        // Findout what the base image size will be
        if(!$size && $_SESSION['user.thumbsize'] <= 100) {
           
            // Set the base size
            $base_size = 100;
           
        } else if(!$size && $_SESSION['user.thumbsize'] > 100 && $_SESSION['user.thumbsize'] <= 200) {
           
            // Set the base size
            $base_size = 200;
           
        } else if (!$size && $_SESSION['user.thumbsize'] > 200) {
           
            // Set the base size
            $base_size = 300;
           
        } else {
           
            // Set the base size
            $base_size = $size;
           
        }
       
        // Thumbnail basepath
        $thumbnail = 'http://imagearchive.mysite.com/aia/thumbnails/';
       
        // Fix filename
        $filename = explode('.', $filename_original);
        $old_extension = array_pop($filename);
        $filename = implode('.', $filename);
       
       
        // Check for Zip or PDF
        if(strtolower($old_extension) == 'zip' || strtolower($old_extension) == 'pdf') {
           
            // Add on the thumbnail size and the png extention
            $filename = 'thumb_' . strtolower($old_extension) . '-'. $base_size .'.gif';
           
            // Reset the path
            $path = '';
           
        } else {
       
            // Add on the thumbnail size and the png extention
            $filename .= ($filename == 'folder') ? $base_size .'.png' : '-'. $base_size .'.png';
           
        }
       
        // Fix the path
        $path = (!empty($path)) ? implode('/', explode('\\', $path)) . '/' : '';
       
        // Get the width and height of the image
        $file_info = $this->get_info($thumbnail . $path . $filename);
       
        // Check to see if the wdith and height exists
        if(empty($file_info['width']) && empty($file_info['height'])) {
           
            // Get the width and height of the image
            $file_info = $this->get_info('/httpd/archive/' . $path . $filename_original);
           
        }
       
        //echo $file_info['width'] .'||'. $file_info['height'] . '<br>';
        // Add a fail safe just incase both attempts at getting the width and height failed we are going
        // to default there sizes to $_SESSION['user.thumbsize'] this occurs with some eps files
        if(empty($file_info['width']) || empty($file_info['height'])) {
           
            // Add a class
            $class = 'fiximage';
           
            // Set the size
            $file_info['width'] = $file_info['height'] = $_SESSION['user.thumbsize'];
           
        }
       
        // Set the siz constraints
        $max_width     = (!empty($size)) ? $size : $_SESSION['user.thumbsize'];
        $max_height = (!empty($size)) ? $size : $_SESSION['user.thumbsize'];
       
        // Get the ratios
        $ratio_height = $max_height/$file_info['height'];
        $ratio_width = $max_width/$file_info['width'];
        $ratio = min($ratio_height, $ratio_width);
       
        // New dimensions
        $width = intval($ratio*$file_info['width']);
        $height = intval($ratio*$file_info['height']);
       
        // Make the attributes
        if(!empty($attributes_array)) {
           
            // Make a new $attributes array
            $attributes = array();
           
            // Check for class in the $attributes
            if(array_key_exists('class',$attributes_array)) {
               
                // Add to the class
                $attributes_array['class'] .= ' ' . $class;
               
            } else {
               
                // Add the class
                $attributes_array['class'] = $class;
               
            }
           
            // Loop through the attributes
            foreach($attributes_array as $key => $value) {
               
                // Add to the attributes
                $attributes[] = $key . '="' . $value . '"';
               
            }
           
            // Implode the attributes
            $attributes = implode(' ', $attributes);
       
        }
       
        // Check to see if the width is bigger than the height
        if($width > $height) {
           
            // Make the image and return it
            return '<img src="'. $thumbnail . $path . $filename .'" width="'. $width .'px" border="0" '. $attributes .' />';
       
        } else {
           
            // Make the image and return it
            return '<img src="'. $thumbnail . $path . $filename .'" height="'. $height .'px" border="0" '. $attributes .' />';
       
        }
       
    }
   
    // This function will get the images info    
    public function get_info($filename) {
       
        // Lets get the extention of the file to see how we will be getting its info.
        $ext = end(explode('.', $filename));
       
        // Make an array to return our info on the image
        $image_info = array();
       
        // Run our extension through a switch statement just incase other issues come up with getting file information
        switch(strtolower($ext)) {
            case 'eps':
           
                // Get an array of information for the eps file
                $imginfo = $this->read_eps($filename);
               
                // Setup all of the infomation needed for this function
                $image_info['width'] = $imginfo['width'];
                $image_info['height'] = $imginfo['height'];
                $image_info['resolution'] = $imginfo['dpi'];
                break;
               
            case 'psd':
           
                // Get an array of information for the psd file
                $imginfo = $this->read_psd($filename);
               
                $image_info['info'] = getimagesize($filename);
                $image_info['width'] = $image_info['info'][0];
                $image_info['height'] = $image_info['info'][1];            
                $image_info['resolution'] = $imginfo['dpi'];
                break;
               
            case 'tga':
           
                // Get the image info NOTE NOT SURE HOW TO GET THE DPI FOR TGA'S YET        
                $image_info['info'] = $this->getimagesizetga($filename);
                $image_info['width'] = $image_info['info']['width'];
                $image_info['height'] = $image_info['info']['height'];            
                $image_info['resolution'] = 72;
                break;
           
            default:
               
                // Call the read from IM function to get the dpi
                //$imginfo = $this->read_from_IM($this->getFullPathName());
                // NEED TO WORK ON THIS A BIT MORE
               
                // Run our extension through a switch statement this is to get a good dpi or a default since imagemagik likes to lock up
                switch(strtolower($ext)) {
                    case 'jpg':
                    case 'jpeg':
                    case 'tif':
                    case 'tiff':
                       
                        // If we are in this area of cases we can use php exif function to get the dpi start by getting the exif data
                        $exif_data = @exif_read_data($filename);
                       
                        // Explode on the '/'
                        $parts = explode('/', $exif_data['XResolution']);
                       
                        // Do the math and set the resolution
                        $resolution = (is_int($parts[0]) && is_int($parts[1])) ? $parts['0'] / $parts['1'] : 72;
                        break;
                       
                    default:
                       
                        // Set to 72
                        $resolution = 72;
                        break;
                       
                }
               
                // Just to be safe let check once more to see if we have a number and its bigger than zero
                $resolution = (is_int($resolution) && $resolution > 0) ? $resolution : 72;
               
                $image_info['info'] = getimagesize($filename);
                $image_info['width'] = $image_info['info'][0];
                $image_info['height'] = $image_info['info'][1];            
                $image_info['resolution'] = $resolution;
 
                break;
               
        }
       
        // Return
        return $image_info;
       
    }
   
    // This function will get the images info    
    public function get_type($filename) {
       
        // Lets get the extention of the file to see how we will be getting its info.
        $ext = end(explode('.', $filename));
 
        // Run our extension through a switch statement just incase other issues come up with getting file information
        switch(strtolower($ext)) {
            case 'jpg':
            case 'jpeg':
               
                // Set the image type
                $image_type = 'Jpeg';
                break;
 
            case 'gif':
               
                // Set the image type
                $image_type = 'GIF';
                break;
               
            case 'png':
               
                // Set the image type
                $image_type = 'PNG';
                break;
               
            case 'tif':
            case 'tiff':
               
                // Set the image type
                $image_type = 'TIF';
                break;
               
            case 'bmp':
               
                // Set the image type
                $image_type = 'BMP';
                break;
 
            case 'eps':
               
                // Set the image type
                $image_type = 'EPS (.eps)';
                break;
               
            case 'psd':
           
                // Set the image type
                $image_type = 'Photoshop File (.psd)';
                break;
               
            case 'tga':
               
                // Set the image type
                $image_type = 'Targa (.tga)';
                break;
               
        }
       
        // Return
        return $image_type;
       
    }
   
    // Read TGA file info
    public function getimagesizetga($filename) {
       
        // Open the TGA file
        $f = fopen($filename, 'rb');
       
        // Read just the header info
        $header = fread($f, 18);
       
        // Unpack the info into an array
        $header = @unpack("cimage_id_len/ccolor_map_type/cimage_type/vcolor_map_origin/vcolor_map_len/ccolor_map_entry_size/vx_origin/vy_origin/vwidth/vheight/cpixel_size/cdescriptor", $header);
       
        // Close the file
        fclose($f);
       
        // Make an array of allowed image types this is used to make sure the file is a tga
        $types = array(0,1,2,3,9,10,11,32,33);        
       
        // Check to see if we have a good image type
        if (in_array($header['image_type'], $types)) {
           
            // Check to see if the pixel size is less than 32
            if ($header['pixel_size'] < 32) {
               
                // Return the header info
                return $header;
           
            }
           
        }
       
        // Return false
        return false;
       
    }
   
    // Read EPS data of given filename
    public function read_eps($img){
       
        // Open and read
        $fp=fopen ($img, "rb");
        $buffer = fread($fp, 4096);    
       
        // Lets assume information is in first 4096 bytes If it is not we will try to access a little more of the file
        if (!preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln)) {
                fclose($fp);
                $fp=fopen ($img, "rb");
                $buffer = fread($fp, 100000);
               
                // OK so if we have gotten to this point we still don't have the info we need so will try the whole file
                if (!preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln)) {
                    fclose($fp);
                    $fp=fopen ($img, "rb");
                    $buffer = fread($fp,filesize($img));
                    preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln);
 
                }
        }
       
        // Crop out the bounding box
        $xpos = strpos($buffer, 'BoundingBox:');
        $ypos = strpos($buffer, '%%HiResBoundingBox:');
        $zpos = $ypos - $xpos;
        $buffer = substr($buffer, $xpos, $zpos);
 
        // Get the img data
        $imgdata2 = explode(" ", $buffer);
       
        // Lets try to get our image size shall we
        $imgdata = explode(" ", $imgdataln[0]);
       
        /*
        //echo $buffer . '<br><br><br><br><br><br><br><br>';
        // Let search for our bounding box and get our size out of that as well
        if (preg_match("/(HiResBoundingBox:)(.)+/",$buffer ,$imgdataln2)) {
          $imgdata2 = explode(" ", $imgdataln2[0]);
        }*/
        //print_r($imgdata);
        //print_r($imgdata2);
       
        // Close our file it is no use to us now
        fclose ($fp);
       
        // Check to see if we got our image size. reason for this is esps don't always have their image size info
        // if we don't have that we will just use the numbers we have which would be the bounding box info
        // NOTE that if we do not have the image info the dpi will always be 72
        $imgdata[1] = (empty($imgdata[1])) ? ($imgdata2[3] - $imgdata2[1]) : $imgdata[1];
        $imgdata[2] = (empty($imgdata[2])) ? ($imgdata2[4] - $imgdata2[2]) : $imgdata[2];
 
        // Set the imageinfo variable
        $imginfo = array();
        $imginfo['width'] = $imgdata[1];
        $imginfo['height'] = $imgdata[2];
       
        // Calculate the dpi
        if ($imgdata2[3] > 0) {
            $imginfo['dpi'] = (72/$imgdata2[3])*$imgdata[1];
           
            // Check to see if we have the orignial DPI or if we are defaulting it to be 72.
            // we will only be defaulting it if we do not have the images actual size.
            // this will be most likely used to inform the users that the original DPI is not avaiable
            $imginfo['original_dip'] = (!empty($imgdata[1])) ? 1 : 0;
           
        }
       
        // if the dpi is over 300 set it to 300
        if ((290 < $imginfo['dpi']) && ($imginfo['dpi'] < 310)) {
            $imginfo['dpi'] = 300;
        }
       
        // Return the imginfo array
        return $imginfo;
       
    }
   
    // Read PSD data of given filename
    public function read_psd($img){
   
        // Open the file for reading
        $fp = fopen($img, "r");
       
        // Read the file and save its contents as the variable "data"
        $data = fread($fp, 80000);
       
        // Create an array to hold the image info
        $image_info = array();
       
        // Find the dpi of the image we start by finding the xml type tags for its dpi
        preg_match('/<tiff:XResolution>.*<\/tiff:XResolution>/i', $data, $matches);
       
        // We need to strip off the tags and then explode it at the / this is done cause the info taken from within the tags are as follows
        // 3000000/10000 this is for a 300 dpi image we explode so we can do the math on it.
        $parts = explode('/', strip_tags($matches[0]));
       
        // Check to see if we have the parts for the DPI if we dont use ImageMagick to get them. if we have them do the math on the dpi and store it in out image info array
        $image_info['dpi'] = (empty($parts[0]) || empty($parts[1])) ? $this->read_from_IM($img) : $parts[0] / $parts[1];
               
        // Close the file when you're done reading it
        fclose($fp);
       
        // Return our array
        return $image_info;
   
    }
   
    // Read from IM of given filename and get the dpi. I broke this out into its own function so i can try to not use it that much
    public function read_from_IM($img){
   
        // Wae are having issues with this right now so for the time being just return 72
        $image_info = 72;
        return $image_info;
                   
        // This bit of code causes the WAMP stack
        // to freeze and lock the server so no more requests will be
        // answered until an OS reboot. Sweet!
        // C05290 - March 9, 2009
       
        // Call identify.exe and use the verbose command to get a list of info on the file
        $vident = $this->process_cmd("identify -verbose \"". drive .$this->getFullPathName()."\"");
       
        // Sreach the list of info on the file for resolution
        if(strstr($vident,"Resolution")) {
           
            // Explode on the carrage return
            $l = explode("\n",$vident);
           
            // Make an array to hold the info we want to get
            $lines = array();
           
            // Loop through the l array to get our info
            foreach($l AS $line) {
               
                // Explode on the : to sperate our value from the word (ie Resolution) and trim the white space around it
                $a = explode(":",trim($line));
               
                // Add our list of words into an assoc. array
                $lines[$a[0]] = (isset($a[1])) ? $a[1]:'';
               
            }
           
            // Set our resolution varible
            $resolution = intval($lines['Resolution']);
       
        }
       
        // Return the resolution and check to see if we have a number other wise default it to 72
        return (empty($resolution)) ? 72 : $resolution;
   
    }
   
    // This function will create the log
    public function log($msg, $id) {
       
        // Database Instace
        $db = DBConnection::instance();
       
        // Check to see if we have anything to log
        if(empty($msg)) {
            return;
        }
       
        // Get the user
        $user = (!empty($_SESSION['user.login'])) ? $_SESSION['user.login'] : 'User Not logged In';
       
        // Make the time
        $time = date("Y-m-d H:i:s \G\M\T O");
       
        // Make the log message
        $message = "[$time ($user)] - $msg";
       
        // Add the log into the database
        $query_values = array
            (
            'fileID'        => $db->in_quotes($id),
            'user'            => $db->in_quotes($user),
            'data'            => $db->in_quotes($message)
            );
       
        // Execute
        $db->sql_insert('logs', $query_values);
       
    }
 
}
 
?>
 
  1. <?php
  2. /**
  3. *   This file is the file processing class. It is used to process
  4. *    images, get info and download them.
  5. *
  6. *   @Author     William Gaines <sgscott87@gmail.com>
  7. *   @Copyright  2013-2014
  8. *  
  9. */
  10.  
  11.  
  12. /***********************************/
  13. /*  Initialize                     */
  14. /***********************************/
  15.  
  16. class FileProcessing {
  17.    
  18.     /***************| Global Varibles |***************/
  19.    
  20.     public $errors = array();
  21.     private $thumbnail_sizes = array('100', '200', '300');
  22.    
  23.    
  24.     /***************| File Processing |***************/
  25.    
  26.     public function generate_download($config_array, $id) {
  27.        
  28.         // Logs Instance
  29.         $logs = new Logs();
  30.        
  31.         /*    
  32.         // Create the log entry
  33.         $log = 'Downloaded image with config:
  34.                 original_image = '. $config_array['original_image'] .',
  35.                 output_image = '. $config_array['output_image'] .',
  36.                 download_name = '. $config_array['download_name'] .',
  37.                 watermark = '. $config_array['watermark'] .',
  38.                 width = '. $config_array['width'] .',
  39.                 height = '. $config_array['height'] .',
  40.                 colorspace = '. $config_array['colorspace'] .',
  41.                 dpi = '. $config_array['dpi'];
  42.        
  43.         // Log the download
  44.         $this->log($log, $id);
  45.         */
  46.        
  47.         // Make an array for the log
  48.         $log_array = array();
  49.        
  50.         // Loop through the array
  51.         foreach($config_array as $key => $value) {
  52.            
  53.             // Check for usage
  54.             if($key != 'usage') {
  55.                
  56.                 // Add to array
  57.                 $log_array[$key] = $value;
  58.                
  59.             } else {
  60.                
  61.                 // Set the usage
  62.                 $usage = $value;
  63.                
  64.             }
  65.            
  66.         }
  67.                
  68.         // Log the creation
  69.         $info = array(
  70.                 "user"             => $_SESSION['user.login'],
  71.                 "download_type"    => 'config_download',
  72.                 "config"        => $log_array,
  73.                 "usage"            => (!empty($usage) ? $usage : 'No Usage'),
  74.                 "datetime"         => date("Y-m-d H:i:s")
  75.                 );
  76.        
  77.         // Add the log category
  78.         $info = array("downloads" => $info);
  79.        
  80.         // Save logs
  81.         $logs->save($info, $id);
  82.        
  83.         // Make the image
  84.         $return = $this->create_image($config_array);
  85.        
  86.         // Return the return
  87.         return $return;
  88.            
  89.     }
  90.    
  91.     // This function will force the download
  92.     public function force_download($config_array) {
  93.        
  94.         // Check for file
  95.         if(!file_exists($config_array['output_image'])) {
  96.            
  97.             // Return Error
  98.             return 'File Not Found';
  99.            
  100.         }
  101.        
  102.         // Check to see if we are using IE
  103.         if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
  104.            
  105.             // Set the header info
  106.             header('Content-Type: application/force-download');
  107.            
  108.         } else {
  109.            
  110.             // Set the header info
  111.             header('Content-Type: application/octet-stream');
  112.            
  113.         }
  114.        
  115.         // Get the image info
  116.         $image_info = file_get_contents($config_array['output_image']);
  117.        
  118.         // Set the content length
  119.         header('Content-Length: '.strlen($image_info));
  120.        
  121.         // Get the correct file name
  122.         $filename = (!empty($config_array['download_name'])) ? $config_array['download_name'] : $config_array['output_image'];
  123.        
  124.         // Add the filename into the header
  125.         header('Content-disposition: attachment; filename="' . basename($filename) . '"');
  126.        
  127.         // Echo our image info
  128.         echo $image_info;
  129.        
  130.         // Kick us out and stop the script
  131.         exit;
  132.        
  133.     }
  134.    
  135.     // This function will build the image
  136.     public function create_image($config_array) {
  137.        
  138.         // Check to see if we can read the file
  139.         if(!is_readable($config_array['original_image'])) {
  140.             return false;
  141.         }
  142.        
  143.         // Get the extenion of the file
  144.         $parts = explode('.', $config_array['original_image']);
  145.        
  146.         // Set the start extention with the extenion of the origional file
  147.         $start_extention = strtolower(end($parts));
  148.        
  149.         // Get the extenion of the converted file
  150.         $parts = explode('.', $config_array['output_image']);
  151.        
  152.         // Set the end extention with the extenion of the converted file
  153.         $end_extention = strtolower(end($parts));
  154.        
  155.         // Make an array to hold the commands
  156.         $command = array();
  157.        
  158.         // Start to write the command
  159.         $command[] = '"'. imagemagick_path . slash .'convert.exe"';
  160.        
  161.         // Check to see if we are dealing with a vector file that needs extra commands
  162.         $command[] = ($start_extention == 'eps' || $start_extention == 'pdf') ? ' -background none' : '';
  163.        
  164.         // Check for psd file
  165.         if($start_extention == 'psd') {
  166.            
  167.             // Change the filename
  168.             $config_array['original_image'] .= '[0]';
  169.            
  170.         }
  171.        
  172.         // What type of image are we making
  173.         switch($end_extention) {
  174.            
  175.             // CMYK and RGB supported formats
  176.             case 'jpg':
  177.             case 'jpeg':
  178.             case 'tif':
  179.             case 'tiff':
  180.             case 'eps':
  181.             case 'pdf':
  182.                
  183.                 // What color profile are we going to use?
  184.                 $profile = ($config_array['colorspace'] == 'rgb') ? 'sRGB.icm' : 'USWebCoatedSWOP.icc';
  185.                
  186.                 // Build the rest of the command
  187.                 $command[] = '-density ' . $config_array['dpi'];
  188.                 $command[] = '"' . $config_array['original_image'] . '"';
  189.                 $command[] = '-profile ' . $profile;
  190.                 $command[] = '-size '. $config_array['width'] .'x'. $config_array['height'];
  191.                 $command[] = '-resize '. $config_array['width'] .'x'. $config_array['height'];
  192.                
  193.                 // Kickout
  194.                 break;
  195.                
  196.             // RGB only formats
  197.             case 'png':
  198.             case 'gif':
  199.             case 'bmp':
  200.                
  201.                 // Build the rest of the command
  202.                 $command[] = '-density ' . $config_array['dpi'];
  203.                 $command[] = '"' . $config_array['original_image'] . '"';
  204.                 $command[] = '-size '. $config_array['width'] .'x'. $config_array['height'];
  205.                 $command[] = '-resize '. $config_array['width'] .'x'. $config_array['height'];
  206.                 $command[] = '-profile sRGB.icm';
  207.                    
  208.                 // Kickout
  209.                 break;
  210.        
  211.         }
  212.        
  213.         // See if we are doing a thumbnail
  214.         if(!empty($config_array['thumbnail'])) {
  215.            
  216.             // Get water mark commands
  217.             $watermark = $this->watermark_commands($config_array, 'Sample');
  218.            
  219.             // Merge arrays
  220.             $command = array_merge($command, $watermark);
  221.  
  222.             $config_array['watermark'] = 'no';
  223.            
  224.         }
  225.        
  226.         // Check to see if we are adding a watermark
  227.         if($config_array['watermark'] == 'yes') {
  228.            
  229.             // Making a restricted mark until i can flush out the logo
  230.             //*/
  231.            
  232.             // Get water mark commands
  233.             $watermark = $this->watermark_commands($config_array, (($config_array['retired']) ? 'Retired Image' : 'Restricted'));
  234.            
  235.             // Merge arrays
  236.             $command = array_merge($command, $watermark);
  237.            
  238.             //*/
  239.            
  240.         }
  241.        
  242.         // Check for custom commands
  243.         if(!empty($config_array['custom'])) {
  244.            
  245.             // Add to the custom settings into the command
  246.             $command[] = $config_array['custom'];
  247.            
  248.         }
  249.        
  250.         // Finish the command
  251.         $command[] = '"' . $config_array['output_image'] . '"';
  252.        
  253.         // Implode on a space
  254.         $command = implode(' ', $command);
  255.            
  256.         // Make and return success to failer
  257.         $return = $this->image_exec($command);
  258.  
  259.         return $return;
  260.        
  261.     }
  262.    
  263.     public function watermark_commands($config_array, $watermark_text) {
  264.        
  265.         $watermark_command[] = '-thumbnail '. $config_array['width'] .'x'. $config_array['height'];
  266.         $size = $config_array['width'];
  267.        
  268.         $watermark_command[] = '-font D:\\httpd\\htdocs\\marcomfiles\\aia\\fonts\\arial.ttf';
  269.         $watermark_command[] = '-fill "rgba(180,180,180,0.8 )"';
  270.        
  271.         // Setup the thumbnail watermark
  272.         switch(true) {
  273.            
  274.             // 100 or less
  275.             case $size <= 100:
  276.                
  277.                 // Setup the water mark
  278.                 $watermark_command[] = '-pointsize 20 -gravity center -annotate +0+0 "'. $watermark_text .'"';
  279.                
  280.                 // Kick out
  281.                 break;
  282.            
  283.             // 100 to 200
  284.             case $size > 100 && $size <= 200:
  285.                
  286.                 // Setup the water mark
  287.                 $watermark_command[] = '-pointsize 25 -gravity NorthWest -annotate +10+10 "'. $watermark_text .'"';
  288.                 $watermark_command[] = '-pointsize 25 -gravity SouthEast -annotate +10+10 "'. $watermark_text .'"';
  289.                
  290.                 // Kickout
  291.                 break;
  292.                
  293.             // 200 to 300
  294.             case $size > 200 && $size <= 300:
  295.                
  296.                 // Setup the water mark
  297.                 $watermark_command[] = '-pointsize 25 -gravity center -annotate +0+0 "'. $watermark_text .'"';
  298.                 $watermark_command[] = '-pointsize 25 -gravity NorthEast -annotate +10+10 "'. $watermark_text .'"';
  299.                 $watermark_command[] = '-pointsize 25 -gravity SouthWest -annotate +10+10 "'. $watermark_text .'"';
  300.                 $watermark_command[] = '-pointsize 25 -gravity Center -annotate +0+0 "'. $watermark_text .'"';
  301.                
  302.                 // Kick out
  303.                 break;
  304.                
  305.             // Over 300
  306.             default:
  307.                
  308.                 // Setup the water mark
  309.                 $watermark_command[] = '-pointsize 30 -gravity West -annotate +10+10 "'. $watermark_text .'"';
  310.                 $watermark_command[] = '-pointsize 30 -gravity East -annotate +10+10 "'. $watermark_text .'"';
  311.                 $watermark_command[] = '-pointsize 30 -gravity North -annotate +10+10 "'. $watermark_text .'"';
  312.                 $watermark_command[] = '-pointsize 30 -gravity South -annotate +10+10 "'. $watermark_text .'"';
  313.                 $watermark_command[] = '-pointsize 30 -gravity center -annotate +0+0 "'. $watermark_text .'"';
  314.                    
  315.         }
  316.        
  317.         // Return the command
  318.         return $watermark_command;
  319.        
  320.     }
  321.    
  322.     // This function will make the image thumbnails
  323.     public function create_thumbnails($path, $filename) {
  324.        
  325.         // Fix the path
  326.         $path = implode('\\', explode('/', $path));
  327.        
  328.         // Get the base name for the file
  329.         $base_name = explode('.', $filename);
  330.         $old_extension = array_pop($base_name);
  331.         $base_name = implode('.', $base_name);    
  332.        
  333.         // Setup the config array
  334.         $config_array['original_image'] = drive . '\\' . archive_dir . '\\' . $path . '\\' . $filename;
  335.         $config_array['thumbnail'] = true;
  336.         $config_array['colorspace'] = 'rgb';
  337.         $config_array['dpi'] = 72;
  338.        
  339.         // Loop throught the thumbnail sizes array
  340.         for($i=0; $i<count($this->thumbnail_sizes); $i++) {
  341.            
  342.             // Set the width, height and the save path
  343.             $config_array['width'] = $this->thumbnail_sizes[$i];
  344.             $config_array['height'] = $this->thumbnail_sizes[$i];
  345.             $config_array['output_image'] = drive . '\\' . thumbnail_dir . '\\' . $path . '\\' . $base_name . '-' . $this->thumbnail_sizes[$i] . '.png';
  346.            
  347.             // Make the thumbnails
  348.             $this->create_image($config_array);
  349.            
  350.         }
  351.        
  352.     }
  353.    
  354.     // This function will delete thumbnails
  355.     public function delete_thumbnails($path, $filename) {
  356.        
  357.         // Check for the file and/or path
  358.         if(empty($path) || empty($filename)) {
  359.            
  360.             // Kick out
  361.             return false;
  362.            
  363.         }
  364.        
  365.         // Fix the path
  366.         $path = implode('\\', explode('/', $path));
  367.        
  368.         // Get the base name for the file
  369.         $base_name = explode('.', $filename);
  370.         $old_extension = array_pop($base_name);
  371.         $base_name = implode('.', $base_name);    
  372.        
  373.         // Loop throught the thumbnail sizes array
  374.         for($i=0; $i<count($thumbnail_ends_all) + 2; $i++) {
  375.  
  376.             // Make the file name
  377.             $temp_name = slash . thumbnail_dir . slash . $path . slash . $base_name . $thumbnail_ends_all[$i];
  378.            
  379.             // Check to see if the file exists
  380.             if(file_exists($temp_name)) {
  381.                
  382.                 // Delete the file
  383.                 unlink($temp_name);
  384.                
  385.             }
  386.            
  387.         }
  388.        
  389.     }    
  390.    
  391.     // This function will process the command sent to image magic
  392.     public function image_exec($cmd) {
  393.        
  394.         //$cmd = mysql_real_escape_string($cmd);
  395.        
  396.         // Make the log file
  397.         $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
  398.         $fh = fopen($log_file, 'a');
  399.        
  400.         // Check to see if we are on the windows server
  401.         if (substr(php_uname(), 0, 7) == "Windows"){
  402.            
  403.             // Write info
  404.             fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
  405.            
  406.             // Start up a handel
  407.             if($h = popen("start \"bla\" $cmd",'r')) {
  408.                
  409.                 // Make a output string varible to hold the output
  410.                 $output = '';
  411.                
  412.                 // Loop until imagemagick is done
  413.                 while (!feof($h)) {
  414.                    
  415.                     // Continue to build onto the out put
  416.                     $output .= fgets($h);
  417.                    
  418.                 }
  419.                
  420.                 // Log our output
  421.                 //$this->log_output($output);
  422.                
  423.                 // Write info
  424.                 fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
  425.                
  426.                 // Close our handle
  427.                 pclose($h);
  428.                
  429.                 // Close file
  430.                 fclose($fh);
  431.                
  432.                 // Return true for success
  433.                 return true;
  434.                
  435.             } else {
  436.                
  437.                 // Write info
  438.                 fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
  439.                
  440.                 // Close file
  441.                 fclose($fh);
  442.                
  443.                 // Return false for fail
  444.                 return false;
  445.                
  446.             }
  447.            
  448.         } else {
  449.            
  450.             // Close file
  451.             fclose($fh);
  452.            
  453.             // Return the exec command output for unix
  454.             return !exec($cmd);
  455.            
  456.         }
  457.        
  458.         // Close file
  459.         fclose($fh);
  460.        
  461.     }
  462.    
  463.    
  464.     /***************| File Reading |***************/
  465.    
  466.     public function get_thumbnail($path, $filename_original, $size=false, $attributes_array=array()) {
  467.        
  468.         // Setup a class varible it will be used to fix the images if needed
  469.         $class = '';
  470.        
  471.         // Findout what the base image size will be
  472.         if(!$size && $_SESSION['user.thumbsize'] <= 100) {
  473.            
  474.             // Set the base size
  475.             $base_size = 100;
  476.            
  477.         } else if(!$size && $_SESSION['user.thumbsize'] > 100 && $_SESSION['user.thumbsize'] <= 200) {
  478.            
  479.             // Set the base size
  480.             $base_size = 200;
  481.            
  482.         } else if (!$size && $_SESSION['user.thumbsize'] > 200) {
  483.            
  484.             // Set the base size
  485.             $base_size = 300;
  486.            
  487.         } else {
  488.            
  489.             // Set the base size
  490.             $base_size = $size;
  491.            
  492.         }
  493.        
  494.         // Thumbnail basepath
  495.         $thumbnail = 'http://imagearchive.mysite.com/aia/thumbnails/';
  496.        
  497.         // Fix filename
  498.         $filename = explode('.', $filename_original);
  499.         $old_extension = array_pop($filename);
  500.         $filename = implode('.', $filename);
  501.        
  502.        
  503.         // Check for Zip or PDF
  504.         if(strtolower($old_extension) == 'zip' || strtolower($old_extension) == 'pdf') {
  505.            
  506.             // Add on the thumbnail size and the png extention
  507.             $filename = 'thumb_' . strtolower($old_extension) . '-'. $base_size .'.gif';
  508.            
  509.             // Reset the path
  510.             $path = '';
  511.            
  512.         } else {
  513.        
  514.             // Add on the thumbnail size and the png extention
  515.             $filename .= ($filename == 'folder') ? $base_size .'.png' : '-'. $base_size .'.png';
  516.            
  517.         }
  518.        
  519.         // Fix the path
  520.         $path = (!empty($path)) ? implode('/', explode('\\', $path)) . '/' : '';
  521.        
  522.         // Get the width and height of the image
  523.         $file_info = $this->get_info($thumbnail . $path . $filename);
  524.        
  525.         // Check to see if the wdith and height exists
  526.         if(empty($file_info['width']) && empty($file_info['height'])) {
  527.            
  528.             // Get the width and height of the image
  529.             $file_info = $this->get_info('/httpd/archive/' . $path . $filename_original);
  530.            
  531.         }
  532.        
  533.         //echo $file_info['width'] .'||'. $file_info['height'] . '<br>';
  534.         // Add a fail safe just incase both attempts at getting the width and height failed we are going
  535.         // to default there sizes to $_SESSION['user.thumbsize'] this occurs with some eps files
  536.         if(empty($file_info['width']) || empty($file_info['height'])) {
  537.            
  538.             // Add a class
  539.             $class = 'fiximage';
  540.            
  541.             // Set the size
  542.             $file_info['width'] = $file_info['height'] = $_SESSION['user.thumbsize'];
  543.            
  544.         }
  545.        
  546.         // Set the siz constraints
  547.         $max_width     = (!empty($size)) ? $size : $_SESSION['user.thumbsize'];
  548.         $max_height = (!empty($size)) ? $size : $_SESSION['user.thumbsize'];
  549.        
  550.         // Get the ratios
  551.         $ratio_height = $max_height/$file_info['height'];
  552.         $ratio_width = $max_width/$file_info['width'];
  553.         $ratio = min($ratio_height, $ratio_width);
  554.        
  555.         // New dimensions
  556.         $width = intval($ratio*$file_info['width']);
  557.         $height = intval($ratio*$file_info['height']);
  558.        
  559.         // Make the attributes
  560.         if(!empty($attributes_array)) {
  561.            
  562.             // Make a new $attributes array
  563.             $attributes = array();
  564.            
  565.             // Check for class in the $attributes
  566.             if(array_key_exists('class',$attributes_array)) {
  567.                
  568.                 // Add to the class
  569.                 $attributes_array['class'] .= ' ' . $class;
  570.                
  571.             } else {
  572.                
  573.                 // Add the class
  574.                 $attributes_array['class'] = $class;
  575.                
  576.             }
  577.            
  578.             // Loop through the attributes
  579.             foreach($attributes_array as $key => $value) {
  580.                
  581.                 // Add to the attributes
  582.                 $attributes[] = $key . '="' . $value . '"';
  583.                
  584.             }
  585.            
  586.             // Implode the attributes
  587.             $attributes = implode(' ', $attributes);
  588.        
  589.         }
  590.        
  591.         // Check to see if the width is bigger than the height
  592.         if($width > $height) {
  593.            
  594.             // Make the image and return it
  595.             return '<img src="'. $thumbnail . $path . $filename .'" width="'. $width .'px" border="0" '. $attributes .' />';
  596.        
  597.         } else {
  598.            
  599.             // Make the image and return it
  600.             return '<img src="'. $thumbnail . $path . $filename .'" height="'. $height .'px" border="0" '. $attributes .' />';
  601.        
  602.         }
  603.        
  604.     }
  605.    
  606.     // This function will get the images info    
  607.     public function get_info($filename) {
  608.        
  609.         // Lets get the extention of the file to see how we will be getting its info.
  610.         $ext = end(explode('.', $filename));
  611.        
  612.         // Make an array to return our info on the image
  613.         $image_info = array();
  614.        
  615.         // Run our extension through a switch statement just incase other issues come up with getting file information
  616.         switch(strtolower($ext)) {
  617.             case 'eps':
  618.            
  619.                 // Get an array of information for the eps file
  620.                 $imginfo = $this->read_eps($filename);
  621.                
  622.                 // Setup all of the infomation needed for this function
  623.                 $image_info['width'] = $imginfo['width'];
  624.                 $image_info['height'] = $imginfo['height'];
  625.                 $image_info['resolution'] = $imginfo['dpi'];
  626.                 break;
  627.                
  628.             case 'psd':
  629.            
  630.                 // Get an array of information for the psd file
  631.                 $imginfo = $this->read_psd($filename);
  632.                
  633.                 $image_info['info'] = getimagesize($filename);
  634.                 $image_info['width'] = $image_info['info'][0];
  635.                 $image_info['height'] = $image_info['info'][1];            
  636.                 $image_info['resolution'] = $imginfo['dpi'];
  637.                 break;
  638.                
  639.             case 'tga':
  640.            
  641.                 // Get the image info NOTE NOT SURE HOW TO GET THE DPI FOR TGA'S YET        
  642.                 $image_info['info'] = $this->getimagesizetga($filename);
  643.                 $image_info['width'] = $image_info['info']['width'];
  644.                 $image_info['height'] = $image_info['info']['height'];            
  645.                 $image_info['resolution'] = 72;
  646.                 break;
  647.            
  648.             default:
  649.                
  650.                 // Call the read from IM function to get the dpi
  651.                 //$imginfo = $this->read_from_IM($this->getFullPathName());
  652.                 // NEED TO WORK ON THIS A BIT MORE
  653.                
  654.                 // Run our extension through a switch statement this is to get a good dpi or a default since imagemagik likes to lock up
  655.                 switch(strtolower($ext)) {
  656.                     case 'jpg':
  657.                     case 'jpeg':
  658.                     case 'tif':
  659.                     case 'tiff':
  660.                        
  661.                         // If we are in this area of cases we can use php exif function to get the dpi start by getting the exif data
  662.                         $exif_data = @exif_read_data($filename);
  663.                        
  664.                         // Explode on the '/'
  665.                         $parts = explode('/', $exif_data['XResolution']);
  666.                        
  667.                         // Do the math and set the resolution
  668.                         $resolution = (is_int($parts[0]) && is_int($parts[1])) ? $parts['0'] / $parts['1'] : 72;
  669.                         break;
  670.                        
  671.                     default:
  672.                        
  673.                         // Set to 72
  674.                         $resolution = 72;
  675.                         break;
  676.                        
  677.                 }
  678.                
  679.                 // Just to be safe let check once more to see if we have a number and its bigger than zero
  680.                 $resolution = (is_int($resolution) && $resolution > 0) ? $resolution : 72;
  681.                
  682.                 $image_info['info'] = getimagesize($filename);
  683.                 $image_info['width'] = $image_info['info'][0];
  684.                 $image_info['height'] = $image_info['info'][1];            
  685.                 $image_info['resolution'] = $resolution;
  686.  
  687.                 break;
  688.                
  689.         }
  690.        
  691.         // Return
  692.         return $image_info;
  693.        
  694.     }
  695.    
  696.     // This function will get the images info    
  697.     public function get_type($filename) {
  698.        
  699.         // Lets get the extention of the file to see how we will be getting its info.
  700.         $ext = end(explode('.', $filename));
  701.  
  702.         // Run our extension through a switch statement just incase other issues come up with getting file information
  703.         switch(strtolower($ext)) {
  704.             case 'jpg':
  705.             case 'jpeg':
  706.                
  707.                 // Set the image type
  708.                 $image_type = 'Jpeg';
  709.                 break;
  710.  
  711.             case 'gif':
  712.                
  713.                 // Set the image type
  714.                 $image_type = 'GIF';
  715.                 break;
  716.                
  717.             case 'png':
  718.                
  719.                 // Set the image type
  720.                 $image_type = 'PNG';
  721.                 break;
  722.                
  723.             case 'tif':
  724.             case 'tiff':
  725.                
  726.                 // Set the image type
  727.                 $image_type = 'TIF';
  728.                 break;
  729.                
  730.             case 'bmp':
  731.                
  732.                 // Set the image type
  733.                 $image_type = 'BMP';
  734.                 break;
  735.  
  736.             case 'eps':
  737.                
  738.                 // Set the image type
  739.                 $image_type = 'EPS (.eps)';
  740.                 break;
  741.                
  742.             case 'psd':
  743.            
  744.                 // Set the image type
  745.                 $image_type = 'Photoshop File (.psd)';
  746.                 break;
  747.                
  748.             case 'tga':
  749.                
  750.                 // Set the image type
  751.                 $image_type = 'Targa (.tga)';
  752.                 break;
  753.                
  754.         }
  755.        
  756.         // Return
  757.         return $image_type;
  758.        
  759.     }
  760.    
  761.     // Read TGA file info
  762.     public function getimagesizetga($filename) {
  763.        
  764.         // Open the TGA file
  765.         $f = fopen($filename, 'rb');
  766.        
  767.         // Read just the header info
  768.         $header = fread($f, 18);
  769.        
  770.         // Unpack the info into an array
  771.         $header = @unpack("cimage_id_len/ccolor_map_type/cimage_type/vcolor_map_origin/vcolor_map_len/ccolor_map_entry_size/vx_origin/vy_origin/vwidth/vheight/cpixel_size/cdescriptor", $header);
  772.        
  773.         // Close the file
  774.         fclose($f);
  775.        
  776.         // Make an array of allowed image types this is used to make sure the file is a tga
  777.         $types = array(0,1,2,3,9,10,11,32,33);        
  778.        
  779.         // Check to see if we have a good image type
  780.         if (in_array($header['image_type'], $types)) {
  781.            
  782.             // Check to see if the pixel size is less than 32
  783.             if ($header['pixel_size'] < 32) {
  784.                
  785.                 // Return the header info
  786.                 return $header;
  787.            
  788.             }
  789.            
  790.         }
  791.        
  792.         // Return false
  793.         return false;
  794.        
  795.     }
  796.    
  797.     // Read EPS data of given filename
  798.     public function read_eps($img){
  799.        
  800.         // Open and read
  801.         $fp=fopen ($img, "rb");
  802.         $buffer = fread($fp, 4096);    
  803.        
  804.         // Lets assume information is in first 4096 bytes If it is not we will try to access a little more of the file
  805.         if (!preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln)) {
  806.                 fclose($fp);
  807.                 $fp=fopen ($img, "rb");
  808.                 $buffer = fread($fp, 100000);
  809.                
  810.                 // OK so if we have gotten to this point we still don't have the info we need so will try the whole file
  811.                 if (!preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln)) {
  812.                     fclose($fp);
  813.                     $fp=fopen ($img, "rb");
  814.                     $buffer = fread($fp,filesize($img));
  815.                     preg_match("/ImageData:[^\"]*\"/",$buffer ,$imgdataln);
  816.  
  817.                 }
  818.         }
  819.        
  820.         // Crop out the bounding box
  821.         $xpos = strpos($buffer, 'BoundingBox:');
  822.         $ypos = strpos($buffer, '%%HiResBoundingBox:');
  823.         $zpos = $ypos - $xpos;
  824.         $buffer = substr($buffer, $xpos, $zpos);
  825.  
  826.         // Get the img data
  827.         $imgdata2 = explode(" ", $buffer);
  828.        
  829.         // Lets try to get our image size shall we
  830.         $imgdata = explode(" ", $imgdataln[0]);
  831.        
  832.         /*
  833.         //echo $buffer . '<br><br><br><br><br><br><br><br>';
  834.         // Let search for our bounding box and get our size out of that as well
  835.         if (preg_match("/(HiResBoundingBox:)(.)+/",$buffer ,$imgdataln2)) {
  836.           $imgdata2 = explode(" ", $imgdataln2[0]);
  837.         }*/
  838.         //print_r($imgdata);
  839.         //print_r($imgdata2);
  840.        
  841.         // Close our file it is no use to us now
  842.         fclose ($fp);
  843.        
  844.         // Check to see if we got our image size. reason for this is esps don't always have their image size info
  845.         // if we don't have that we will just use the numbers we have which would be the bounding box info
  846.         // NOTE that if we do not have the image info the dpi will always be 72
  847.         $imgdata[1] = (empty($imgdata[1])) ? ($imgdata2[3] - $imgdata2[1]) : $imgdata[1];
  848.         $imgdata[2] = (empty($imgdata[2])) ? ($imgdata2[4] - $imgdata2[2]) : $imgdata[2];
  849.  
  850.         // Set the imageinfo variable
  851.         $imginfo = array();
  852.         $imginfo['width'] = $imgdata[1];
  853.         $imginfo['height'] = $imgdata[2];
  854.        
  855.         // Calculate the dpi
  856.         if ($imgdata2[3] > 0) {
  857.             $imginfo['dpi'] = (72/$imgdata2[3])*$imgdata[1];
  858.            
  859.             // Check to see if we have the orignial DPI or if we are defaulting it to be 72.
  860.             // we will only be defaulting it if we do not have the images actual size.
  861.             // this will be most likely used to inform the users that the original DPI is not avaiable
  862.             $imginfo['original_dip'] = (!empty($imgdata[1])) ? 1 : 0;
  863.            
  864.         }
  865.        
  866.         // if the dpi is over 300 set it to 300
  867.         if ((290 < $imginfo['dpi']) && ($imginfo['dpi'] < 310)) {
  868.             $imginfo['dpi'] = 300;
  869.         }
  870.        
  871.         // Return the imginfo array
  872.         return $imginfo;
  873.        
  874.     }
  875.    
  876.     // Read PSD data of given filename
  877.     public function read_psd($img){
  878.    
  879.         // Open the file for reading
  880.         $fp = fopen($img, "r");
  881.        
  882.         // Read the file and save its contents as the variable "data"
  883.         $data = fread($fp, 80000);
  884.        
  885.         // Create an array to hold the image info
  886.         $image_info = array();
  887.        
  888.         // Find the dpi of the image we start by finding the xml type tags for its dpi
  889.         preg_match('/<tiff:XResolution>.*<\/tiff:XResolution>/i', $data, $matches);
  890.        
  891.         // We need to strip off the tags and then explode it at the / this is done cause the info taken from within the tags are as follows
  892.         // 3000000/10000 this is for a 300 dpi image we explode so we can do the math on it.
  893.         $parts = explode('/', strip_tags($matches[0]));
  894.        
  895.         // Check to see if we have the parts for the DPI if we dont use ImageMagick to get them. if we have them do the math on the dpi and store it in out image info array
  896.         $image_info['dpi'] = (empty($parts[0]) || empty($parts[1])) ? $this->read_from_IM($img) : $parts[0] / $parts[1];
  897.                
  898.         // Close the file when you're done reading it
  899.         fclose($fp);
  900.        
  901.         // Return our array
  902.         return $image_info;
  903.    
  904.     }
  905.    
  906.     // Read from IM of given filename and get the dpi. I broke this out into its own function so i can try to not use it that much
  907.     public function read_from_IM($img){
  908.    
  909.         // Wae are having issues with this right now so for the time being just return 72
  910.         $image_info = 72;
  911.         return $image_info;
  912.                    
  913.         // This bit of code causes the WAMP stack
  914.         // to freeze and lock the server so no more requests will be
  915.         // answered until an OS reboot. Sweet!
  916.         // C05290 - March 9, 2009
  917.        
  918.         // Call identify.exe and use the verbose command to get a list of info on the file
  919.         $vident = $this->process_cmd("identify -verbose \"". drive .$this->getFullPathName()."\"");
  920.        
  921.         // Sreach the list of info on the file for resolution
  922.         if(strstr($vident,"Resolution")) {
  923.            
  924.             // Explode on the carrage return
  925.             $l = explode("\n",$vident);
  926.            
  927.             // Make an array to hold the info we want to get
  928.             $lines = array();
  929.            
  930.             // Loop through the l array to get our info
  931.             foreach($l AS $line) {
  932.                
  933.                 // Explode on the : to sperate our value from the word (ie Resolution) and trim the white space around it
  934.                 $a = explode(":",trim($line));
  935.                
  936.                 // Add our list of words into an assoc. array
  937.                 $lines[$a[0]] = (isset($a[1])) ? $a[1]:'';
  938.                
  939.             }
  940.            
  941.             // Set our resolution varible
  942.             $resolution = intval($lines['Resolution']);
  943.        
  944.         }
  945.        
  946.         // Return the resolution and check to see if we have a number other wise default it to 72
  947.         return (empty($resolution)) ? 72 : $resolution;
  948.    
  949.     }
  950.    
  951.     // This function will create the log
  952.     public function log($msg, $id) {
  953.        
  954.         // Database Instace
  955.         $db = DBConnection::instance();
  956.        
  957.         // Check to see if we have anything to log
  958.         if(empty($msg)) {
  959.             return;
  960.         }
  961.        
  962.         // Get the user
  963.         $user = (!empty($_SESSION['user.login'])) ? $_SESSION['user.login'] : 'User Not logged In';
  964.        
  965.         // Make the time
  966.         $time = date("Y-m-d H:i:s \G\M\T O");
  967.        
  968.         // Make the log message
  969.         $message = "[$time ($user)] - $msg";
  970.        
  971.         // Add the log into the database
  972.         $query_values = array
  973.             (
  974.             'fileID'        => $db->in_quotes($id),
  975.             'user'            => $db->in_quotes($user),
  976.             'data'            => $db->in_quotes($message)
  977.             );
  978.        
  979.         // Execute
  980.         $db->sql_insert('logs', $query_values);
  981.        
  982.     }
  983.  
  984. }
  985.  
  986. ?>
  987.  


I think the issue might be where the command gets executed
PHP Code: [ Select ]
    // This function will process the command sent to image magic
    public function image_exec($cmd) {
       
        // Check to see if we are on the windows server
        if (substr(php_uname(), 0, 7) == "Windows"){
           
            // Start up a handle
            if($h = popen("start \"bla\" $cmd",'r')) {
               
                // Make a output string variable to hold the output
                $output = '';
               
                // Loop until imagemagick is done
                while (!feof($h)) {
                   
                    // Continue to build onto the out put
                    $output .= fgets($h);
                   
                }
               
               
                // Close our handle
                pclose($h);
               
                // Return true for success
                return true;
               
            } else {
               
                // Close file
                fclose($fh);
               
                // Return false for fail
                return false;
               
            }
           
        } else {
           
            // This doesn't get run
           
            // Return the exec command output for unix
            return !exec($cmd);
           
        }
       
    }
 
  1.     // This function will process the command sent to image magic
  2.     public function image_exec($cmd) {
  3.        
  4.         // Check to see if we are on the windows server
  5.         if (substr(php_uname(), 0, 7) == "Windows"){
  6.            
  7.             // Start up a handle
  8.             if($h = popen("start \"bla\" $cmd",'r')) {
  9.                
  10.                 // Make a output string variable to hold the output
  11.                 $output = '';
  12.                
  13.                 // Loop until imagemagick is done
  14.                 while (!feof($h)) {
  15.                    
  16.                     // Continue to build onto the out put
  17.                     $output .= fgets($h);
  18.                    
  19.                 }
  20.                
  21.                
  22.                 // Close our handle
  23.                 pclose($h);
  24.                
  25.                 // Return true for success
  26.                 return true;
  27.                
  28.             } else {
  29.                
  30.                 // Close file
  31.                 fclose($fh);
  32.                
  33.                 // Return false for fail
  34.                 return false;
  35.                
  36.             }
  37.            
  38.         } else {
  39.            
  40.             // This doesn't get run
  41.            
  42.             // Return the exec command output for unix
  43.             return !exec($cmd);
  44.            
  45.         }
  46.        
  47.     }
  48.  
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

I'm not sure if it is really Imagemagick that is the issue because I've had a similar issue with ffmpeg on this same server. I think it has something to do with how I'm calling it
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Is it possible that you have Xdebug or Zend Debug available so that you can walk through your program when this problem exists? Doing this should let you know precisely what line is causing the script to hang. Would be helpful since you have tons of code there.

If not could you put a bunch of echo commands throughout your code and figure out exactly where the echo stop outputting so you know exactly what line is causing it to hang?

Would be helpful to get it narrowed down so we can focus on the line causing the problem.
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

I do not have either one of those but i do believe i have narrowed it down to the image_exec function do to the logger i threw in yesterday to try to figure this out. When the script runs correctly the logs read
Code: [ Select ]
[2013-02-26 11:31:45] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\tifftest.tif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\tifftest.jpg"
[2013-02-26 11:31:45] No Output
  1. [2013-02-26 11:31:45] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\tifftest.tif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\tifftest.jpg"
  2. [2013-02-26 11:31:45] No Output


When this happens the logs read. (3 triesby me when locked)
Code: [ Select ]
[2013-02-26 11:26:39] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\giftest.gif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\giftest.jpg"
[2013-02-26 11:28:55] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\giftest.gif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\giftest.jpg"
[2013-02-26 11:30:53] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\test_move\download_tab_06.jpg" -profile sRGB.icm -size 698x471 -resize 698x471 "D:\httpd\htdocs\marcomfiles\aia\tmp\download_tab_06.jpg"
  1. [2013-02-26 11:26:39] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\giftest.gif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\giftest.jpg"
  2. [2013-02-26 11:28:55] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\giftest.gif" -profile sRGB.icm -size 1317x1153 -resize 1317x1153 "D:\httpd\htdocs\marcomfiles\aia\tmp\giftest.jpg"
  3. [2013-02-26 11:30:53] On Windows Machine Trying to run. start "bla" "C:\Program Files\ImageMagick-6.8.3-Q16\convert.exe" -density 72 "D:\httpd\archive\Corporate Communications\Testing\test_move\download_tab_06.jpg" -profile sRGB.icm -size 698x471 -resize 698x471 "D:\httpd\htdocs\marcomfiles\aia\tmp\download_tab_06.jpg"


PHP Code: [ Select ]
   // This function will process the command sent to image magic
   public function image_exec($cmd) {
     
      //$cmd = mysql_real_escape_string($cmd);
     
      // Make the log file
      $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
      $fh = fopen($log_file, 'a');
     
      // Check to see if we are on the windows server
      if (substr(php_uname(), 0, 7) == "Windows"){
         
         // Write info
         fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
         
         // Start up a handle
         if($h = popen("start \"bla\" $cmd",'r')) {
           
            // Make a output string variable to hold the output
            $output = '';
           
            // Loop until imagemagick is done
            while (!feof($h)) {
               
               // Continue to build onto the out put
               $output .= fgets($h);
               
            }
           
            // Log our output
            //$this->log_output($output);
           
            // Write info
            fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
           
            // Close our handle
            pclose($h);
           
            // Close file
            fclose($fh);
           
            // Return true for success
            return true;
           
         } else {
           
            // Write info
            fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
           
            // Close file
            fclose($fh);
           
            // Return false for fail
            return false;
           
         }
         
      } else {
         
         // Close file
         fclose($fh);
         
         // Return the exec command output for unix
         return !exec($cmd);
         
      }
     
      // Close file
      fclose($fh);
     
   }
 
  1.    // This function will process the command sent to image magic
  2.    public function image_exec($cmd) {
  3.      
  4.       //$cmd = mysql_real_escape_string($cmd);
  5.      
  6.       // Make the log file
  7.       $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
  8.       $fh = fopen($log_file, 'a');
  9.      
  10.       // Check to see if we are on the windows server
  11.       if (substr(php_uname(), 0, 7) == "Windows"){
  12.          
  13.          // Write info
  14.          fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
  15.          
  16.          // Start up a handle
  17.          if($h = popen("start \"bla\" $cmd",'r')) {
  18.            
  19.             // Make a output string variable to hold the output
  20.             $output = '';
  21.            
  22.             // Loop until imagemagick is done
  23.             while (!feof($h)) {
  24.                
  25.                // Continue to build onto the out put
  26.                $output .= fgets($h);
  27.                
  28.             }
  29.            
  30.             // Log our output
  31.             //$this->log_output($output);
  32.            
  33.             // Write info
  34.             fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
  35.            
  36.             // Close our handle
  37.             pclose($h);
  38.            
  39.             // Close file
  40.             fclose($fh);
  41.            
  42.             // Return true for success
  43.             return true;
  44.            
  45.          } else {
  46.            
  47.             // Write info
  48.             fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
  49.            
  50.             // Close file
  51.             fclose($fh);
  52.            
  53.             // Return false for fail
  54.             return false;
  55.            
  56.          }
  57.          
  58.       } else {
  59.          
  60.          // Close file
  61.          fclose($fh);
  62.          
  63.          // Return the exec command output for unix
  64.          return !exec($cmd);
  65.          
  66.       }
  67.      
  68.       // Close file
  69.       fclose($fh);
  70.      
  71.    }
  72.  


So I think I've narrowed it down to if($h = popen("start \"bla\" $cmd",'r')) { it doesn't return false so it doesn't throw the Could not run Command. into the log but it also stops at that point and dose not enter the if statement leading me to believe that it is something to do with the popen. I came across this but not exactly sure how to install it yet do to the factor that they want you to install the composer software which while at work is blocked by the firewall. https://github.com/symfony/Process. there is something strange however.
PHP Code: [ Select ]
// Loop until imagemagick is done
            while (!feof($h)) {
               
               // Continue to build onto the out put
               $output .= fgets($h);
               
            }
 
  1. // Loop until imagemagick is done
  2.             while (!feof($h)) {
  3.                
  4.                // Continue to build onto the out put
  5.                $output .= fgets($h);
  6.                
  7.             }
  8.  

if i add anything to this while loop it locks up, if i comment out the $output variable it locks up, if i remove the while statement it locks up. this test came up because i found this https://bugs.php.net/bug.php?id=51800

Any Ideas?
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

I am curious if you use proc_open instead of popen if your feedback from your script is any different.
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Also on that last link I gave you for proc_open look at the first comment at the bottom, not sure if this might help too:

Quote:
It took me a long time (and three consecutive projects) to figure this out. Because popen() and proc_open() return valid processes even when the command failed it's awkward to determine when it really has failed if you're opening a non-interactive process like "sendmail -t".

I had previously guess that reading from STDERR immediately after starting the process would work, and it does... but when the command is successful PHP just hangs because STDERR is empty and it's waiting for data to be written to it.

The solution is a simple stream_set_blocking($pipes[2], 0) immediately after calling proc_open().

PHP Code: [ Select ]
<?php
 
    $this->_proc = proc_open($command, $descriptorSpec, $pipes);
    stream_set_blocking($pipes[2], 0);
    if ($err = stream_get_contents($pipes[2]))
    {
      throw new Swift_Transport_TransportException(
        'Process could not be started [' . $err . ']'
        );
    }
 
?>
  1. <?php
  2.  
  3.     $this->_proc = proc_open($command, $descriptorSpec, $pipes);
  4.     stream_set_blocking($pipes[2], 0);
  5.     if ($err = stream_get_contents($pipes[2]))
  6.     {
  7.       throw new Swift_Transport_TransportException(
  8.         'Process could not be started [' . $err . ']'
  9.         );
  10.     }
  11.  
  12. ?>


If the process is opened successfully $pipes[2] will be empty, but if it failed the bash/sh error will be in it.

Finally I can drop all my "workaround" error checking.

I realise this solution is obvious and I'm not sure how it took me 18 months to figure it out, but hopefully this will help someone else.

NOTE: Make sure your descriptorSpec has ( 2 => array('pipe', 'w')) for this to work.
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

Seems promising unfortunately unless something happens at work that needs immediate attention I'm off until Monday. So until then all I can really do is research and speculate.
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

So unfortunately I'm getting the same issues with proc_open :( and the line stream_set_blocking($pipes[2], 0); Seems to have issues when it comes to running on windows machines.
https://bugs.php.net/bug.php?id=47918
https://bugs.php.net/bug.php?id=34972
https://bugs.php.net/bug.php?id=51800

The last link was an error i ran across when i was looking into https://github.com/symfony/Process And they apparently have a work around so I'm going to try to rip out there work around and see if i can't get proc_open to work.

Here is an important factor of the lockup which i have confirmed.

in this program there is a page that its sole purpose is to rebuild the thumbnails and since it is Ajax based this page doesn't return much and can be ran by going to the page - http://[archive].[my_site].com/aia/new_site/managers_layout/process_thumbnail_refresh.php?id=427 (I need to mask the real URL but that it not important.)

now if I run this url in the browser it works and build the thumbnails just fine. i then can run this again as soon as it finishes, I can also run this script at the same time with a different browser (I believe different session would work as well) and it works fine. one way to insure and repeat the lockup consistently is to run this url in the browser and before the script completes run it again. and this will lock up apache every time, causing a need to restart apache.

This project runs through a proxy server so when this lock up occurs you will get a 502 or proxy error after a set amount of time (its about 5 minutes) going directly to the server and causing the lockup causes what seems to be an endless loop (ran for over 15 minutes before I restarted apache) As for the restarting of apache Note this as well within the apache monitor simply clicking restart does not fix it I have to click stop wait for it to stop and then click start in order to unjam it.

As I am trying to work on this possible fix is there anyway to select all the proc_open handles from a given session so that then can be closed? OR can the handles be stored in the $_SESSION (it sounds like a bad idea in my head)
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Hopefully that workaround works that Symfony has found.

As far as a way to select all of the handles from a session, not entirely sure there, but if it were me I would probably start with proc_get_status and then maybe somehow using the PID to match up against? Not sure, but the comments below there might be helpful too.
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

Frustrating .... I started trying to track down where the file locks up at and I found that is seems to lock up at session_start(); when you try to reload the page while image magic is still loading
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

I also found this article http://konrness.com/php5/how-to-prevent ... -requests/
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

:hmm: So here is my dumb little fix that seems to be working now

PHP Code: [ Select ]
// This function will process the command sent to image magic
public function image_exec($cmd) {
   
   // Close the session to avoid a session lock
   session_write_close();
   
   // Make the log file
   $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
   $fh = fopen($log_file, 'a');
   
   // Check to see if we are on the windows server
   if (substr(php_uname(), 0, 7) == "Windows"){
     
      // Write info
      fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
     
      // Start up a handel
      if($h = popen("start \"bla\" $cmd",'r')) {
         
         // Make a output string varible to hold the output
         $output = '';
         
         // Loop until imagemagick is done
         while (!feof($h)) {
           
            // Continue to build onto the out put
            $output .= fgets($h);
           
         }
         
         // Write info
         fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
         
         // Close our handle
         pclose($h);
         
         // Close file
         fclose($fh);
         
         // Restart the session
         @session_start();
         
         // Return true for success
         return true;
         
      } else {
         
         // Write info
         fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
         
         // Close file
         fclose($fh);
         
         // Restart the session
         @session_start();
         
         // Return false for fail
         return false;
         
      }
 
   } else {
     
      // Close file
      fclose($fh);
     
      // Return the exec command output for unix
      return !exec($cmd);
     
   }
   
   // Close file
   fclose($fh);
   
}
 
 
  1. // This function will process the command sent to image magic
  2. public function image_exec($cmd) {
  3.    
  4.    // Close the session to avoid a session lock
  5.    session_write_close();
  6.    
  7.    // Make the log file
  8.    $log_file = drive . 'httpd\logs\IM\imageMagik_log_'. date('Ymd') .'.txt';
  9.    $fh = fopen($log_file, 'a');
  10.    
  11.    // Check to see if we are on the windows server
  12.    if (substr(php_uname(), 0, 7) == "Windows"){
  13.      
  14.       // Write info
  15.       fwrite($fh, '['. date('Y-m-d h:i:s') .'] On Windows Machine Trying to run. '. "start \"bla\" $cmd" . "\r\n");
  16.      
  17.       // Start up a handel
  18.       if($h = popen("start \"bla\" $cmd",'r')) {
  19.          
  20.          // Make a output string varible to hold the output
  21.          $output = '';
  22.          
  23.          // Loop until imagemagick is done
  24.          while (!feof($h)) {
  25.            
  26.             // Continue to build onto the out put
  27.             $output .= fgets($h);
  28.            
  29.          }
  30.          
  31.          // Write info
  32.          fwrite($fh, '['. date('Y-m-d h:i:s') .'] ' . (empty($output) ? 'No Output' : $output) . "\r\n\r\n");
  33.          
  34.          // Close our handle
  35.          pclose($h);
  36.          
  37.          // Close file
  38.          fclose($fh);
  39.          
  40.          // Restart the session
  41.          @session_start();
  42.          
  43.          // Return true for success
  44.          return true;
  45.          
  46.       } else {
  47.          
  48.          // Write info
  49.          fwrite($fh, '['. date('Y-m-d h:i:s') .'] Could not run Command. '. "start \"bla\" $cmd" . "\r\n");
  50.          
  51.          // Close file
  52.          fclose($fh);
  53.          
  54.          // Restart the session
  55.          @session_start();
  56.          
  57.          // Return false for fail
  58.          return false;
  59.          
  60.       }
  61.  
  62.    } else {
  63.      
  64.       // Close file
  65.       fclose($fh);
  66.      
  67.       // Return the exec command output for unix
  68.       return !exec($cmd);
  69.      
  70.    }
  71.    
  72.    // Close file
  73.    fclose($fh);
  74.    
  75. }
  76.  
  77.  
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Glad you found a solution Scott, no matter how ugly it is.

So it looks like the problem had to do with sessions?
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

Yep seems that way I've continued to try to lock it up and so far no success on doing that, which is a good thing. So I'm rethinking my session handling.
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Just ran by this today when I was working on something, check out the big warning at the top:

http://php.net/manual/en/ref.exec.php

Quote:
Open files with lock (especially open sessions) should be closed before executing a program in the background.


Ha! Looks like you did it the way they recommend!
  • ScottG
  • Proficient
  • Proficient
  • ScottG
  • Posts: 476

Post 3+ Months Ago

Sweet!

Post Information

  • Total Posts in this topic: 18 posts
  • Users browsing this forum: No registered users and 74 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.