ImageMagick encerrando a través de un script PHP en Windows OS

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Febrero 25th, 2013, 2:55 pm

¿Alguien tiene alguna experiencia con ImageMagick y sistema operativo Windows. Estoy usando popen en php para ejecutar el comando y esto tiene trabajo con ningún problema pero recientemente parece ser encerrar y es la única forma de desbloquearlo para reiniciar apache.

:banghead:
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Febrero 25th, 2013, 2:55 pm

  • Zealous
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: Abr 15, 2011
  • Mensajes: 1202
  • Loc: Sydney
  • Status: Online

Nota Febrero 25th, 2013, 7:54 pm

¿Hay algún error en los registros de operaciones?

Lo que está sucediendo cuando encerrar, podría ser un misconfig en alguna parte.
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Febrero 26th, 2013, 8:01 am

ImageMagick informa que nada y he trataron de leer para cualquier salida y nada. No he cambiado nada en el código sólo comenzó actuando para arriba.

Lo que pasa es que va a trabajar completamente bien y de repente se detiene ejecutando los comandos. Yo esto una vez hace un tiempo había replicado enviando multitud de solicitudes a la vez en él. Im no está seguro de esto es lo que está ocurriendo o no. Puedo tomar el comando y escritorio remoto en el servidor y usar el mismo imagemagick y funciona bien.

Cuando esto hace bloqueo si usted es el usuario que lo encierra todo el sitio y usted entonces necesita cerrar el navegador y abrir una nueva ventana para ver el sitio otra vez, básicamente sesiones base de bloqueo en el sitio pero imagemagick detiene todo el proceso para todos cuando esto sucede. la única forma de resolver el problema del bloqueo de imagemagick es reiniciar apache y en algunos casos el propio servidor.


Aquí es el comando que se envía a imagemagick
Código: [ 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"


Esta es la clase que se construye y ejecuta este comando. (despojado de sólo las funciones necesarias para procesar las imágenes)
PHP Código: [ 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.  


Creo que la cuestión podría ser donde es ejecutado el comando
PHP Código: [ 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
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Febrero 26th, 2013, 10:11 am

Im no está seguro si es realmente Imagemagick ese es el tema porque Ive tuvo un problema similar con ffmpeg en este mismo servidor. Creo que tiene algo que ver con cómo Im llamándola
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Febrero 26th, 2013, 11:23 am

¿Es posible que tenga Xdebug o Zend depurar disponibles para que usted puede caminar a través de su programa cuando existe este problema? Para ello debe saber precisamente qué línea está causando el script colgar. Sería útil ya que hay toneladas de código.

¿Si no podría poner un montón de comandos echo a lo largo de su código y averiguar exactamente donde el eco dejar salir para que sepa exactamente qué línea está causando que cuelgue?

Sería útil para conseguirlo limitado para que podamos enfocar en la línea de la causa del problema.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Febrero 26th, 2013, 11:51 am

No tengo uno de esos pero creo he reducido hacia abajo a la image_exec función hacer el registrador tiró ayer para tratar de resolver esto. Cuando la secuencia de comandos se ejecuta correctamente los registros leer
Código: [ 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


Cuando esto ocurre leen los registros. (3 triesby me cuando bloqueado)
Código: [ 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 Código: [ 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.  


Así que creo que he reducido abajo a si ($ h = popen ("start \"bla\"$cmd", "r")) { no devolver false para que no produce la no podía ejecutar comando. en el registro pero también se detiene en ese momento y dosis no entran el if declaración llevándome a creer que es algo que ver con el popen. Me encontré con esto, pero no sabe exactamente cómo instalarlo y hacer que el factor que quieren instalar el compositor software que mientras que en el trabajo es bloqueado por el cortafuegos. https://github.com/symfony/Process . hay algo extraño sin embargo.
PHP Código: [ 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.  

Si cualquier cosa agrego a esto mientras que enlacen cerraduras, si yo comente la variable de salida de $ encierra, si me quito el tiempo declaración encierra. Esta prueba se subió porque me encontré con estohttps://bugs.php.net/bug.php?id=51800

¿Alguna idea?
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Febrero 27th, 2013, 9:46 am

Tengo curiosidad Si utilizas proc_open en vez de popen si su opinión de su escritura es diferente.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Febrero 27th, 2013, 9:48 am

También en ese último eslabón que le dio para proc_open mira el primer comentario en la parte inferior, no sabe si podría ayudar también:

Quote:
Me llevó mucho tiempo (y tres proyectos consecutivos) para resolver esto. Porque popen() y proc_open () devuelven válidos procesos incluso cuando el comando falló su torpe determinar cuando realmente ha fracasado si se está abriendo un proceso no interactivo como "sendmail -t".

Previamente había supongo que leyendo de STDERR inmediatamente después de comenzar el proceso funcionaría, y lo hace...pero cuando el comando es acertado PHP cuelga porque STDERR es vacío y su espera para datos se escriban a él.

La solución es un simple stream_set_blocking (tubos de $[2], 0) inmediatamente después de llamar a proc_open ().

PHP Código: [ 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. ?>


Si el proceso se abre con éxito tubos $[2] estará vacías, pero si falla el error bash/sh estará en él.

Finalmente, yo puedo soltar todo mi "solución" comprobación de errores.

Me doy cuenta de esta solución es obvia y Im no está seguro de cómo me tomó 18 meses para descifrarlo, pero esperemos que esto le ayudará a alguien.

Nota: Asegúrese de que su descriptorSpec ha (2 = &gt; array ("pipa", "w")) para que funcione.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Febrero 27th, 2013, 10:48 am

Parece prometedor Desafortunadamente a menos que algo sucede en el trabajo que necesita atención inmediata Im apagado hasta el lunes. Así que hasta entonces lo único que puedo hacer realmente es investigación y especular.
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Marzo 4th, 2013, 11:04 am

Tan lamentablemente Im consiguiendo las mismas cuestiones con proc_open :( y la línea stream_set_blocking (tubos de $[2], 0); Parece tener problemas cuando se ejecutan en equipos con windows.
https://bugs.php.net/bug.php?id=47918
https://bugs.php.net/bug.php?id=34972
https://bugs.php.net/bug.php?id=51800

El último eslabón fue un error, encontré con cuando miraba en https://github.com/symfony/Process y aparece notly tienen un trabajo alrededor así que voy a intentar copiar ahí solucionar y ve si puedo proc_open para trabajar.

Aquí es un factor importante de la cárcel que he confirmado.

en este programa hay una página que su único propósito es reconstruir las imágenes en miniatura y puesto que es Ajax basado en esta página no devuelve mucho y puede ser funcionó por ir a la página - http://[archive].[my_site].com/aia/new_site/managers_layout/process_thumbnail_refresh.php?id=427 (necesito para enmascarar la URL real pero eso él no es importante).

ahora si corro esta url en el navegador funciona y construir las miniaturas muy bien. entonces puedo ejecutar esto otra vez tan pronto como termina, también podemos ejecutar este script al mismo tiempo con otro navegador (creo sesión diferente funcionaría así) y funciona bien. una forma de asegurar y repetir constantemente el bloqueo es ejecutar esta url en el navegador y antes de que finalice el script ejecutarlo otra vez. y esto se trabe apache cada vez, causando la necesidad de reiniciar apache.

Este proyecto funciona a través de un servidor proxy, así que cuando se produce esta cerradura para arriba usted conseguirá un 502 o proxy error después de una cantidad fija de tiempo (su unos 5 minutos) ir directamente al servidor y causando el bloqueo provoca lo que aparenta ser un bucle infinito (funcionó durante más de 15 minutos antes de que me reinicia apache) en cuanto al reinicio de apache nota esto así en el monitor de apache, simplemente haga clic en reiniciar no arreglarlo tengo hacer clic en espera de la parada para que deje de funcionar y haga clic en iniciar para desatascarlo.

¿Como estoy tratando de trabajar en esta posible solución existe de todos modos para seleccionar todas las manijas proc_open desde una sesión dada que entonces pueden ser cerradas? O las manijas se pueden almacenar en el $_SESSION (parece una mala idea en mi cabeza)
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Marzo 4th, 2013, 4:29 pm

Esperemos que esa solución funciona que Symfony ha encontrado.

¿En cuanto a una forma de seleccionar todos los mangos de una sesión, allí no es completamente seguro, pero si fuese yo probablemente empezaría con proc_get_status y entonces tal vez de alguna manera con el PID para acoplar contra? No estoy seguro, pero también pueden ser útiles los comentarios a continuación.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Marzo 5th, 2013, 12:53 pm

Frustrante . Empecé tratando de rastrear dónde se encierra en el archivo y encontré que es parece encerrar en session_start (); al intentar recargar la página mientras todavía está cargando la magia de la imagen
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Marzo 5th, 2013, 12:55 pm

También encontré este artículo
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 280
  • Status: Offline

Nota Marzo 5th, 2013, 1:46 pm

:hmm:Así que aquí está mi arreglo poco tonta que parece estar trabajando ahora

PHP Código: [ 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
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Marzo 6th, 2013, 12:30 pm

Consigues una solución Scott, no importa lo fea es alegre.

¿Así que parece que el problema tenía que ver con las sesiones?
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Marzo 6th, 2013, 12:30 pm

Publicar Información

  • Total de mensajes en este tema: 18 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 152 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC