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


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
¿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.


- Anonymous
- Bot


- Registrado: 25 Feb 2008
- Mensajes: ?
- Loc: Ozzuland
- Status: Online
Febrero 25th, 2013, 2:55 pm
- Zealous
- Guru


- Registrado: Abr 15, 2011
- Mensajes: 1202
- Loc: Sydney
- Status: Online
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
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
Esta es la clase que se construye y ejecuta este comando. (despojado de sólo las funciones necesarias para procesar las imágenes)
Creo que la cuestión podrÃa ser donde es ejecutado el comando
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);
}
}
?>
/**
* 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);
}
}
?>
- <?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);
- }
- }
- ?>
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);
}
}
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);
}
}
- // 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);
- }
- }
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
- Bigwebmaster
- Site Admin


- Registrado: Dic 20, 2002
- Mensajes: 8934
- Loc: Seattle, WA & Phoenix, AZ
- Status: Offline
¿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.
¿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


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
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
Cuando esto ocurre leen los registros. (3 triesby me cuando bloqueado)
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.
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?
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
[2013-02-26 11:31:45] No Output
- [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
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"
[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"
- [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"
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);
}
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);
}
- // 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);
- }
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);
}
while (!feof($h)) {
// Continue to build onto the out put
$output .= fgets($h);
}
- // Loop until imagemagick is done
- while (!feof($h)) {
- // Continue to build onto the out put
- $output .= fgets($h);
- }
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


- Registrado: Dic 20, 2002
- Mensajes: 8934
- Loc: Seattle, WA & Phoenix, AZ
- Status: Offline
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


- Registrado: Dic 20, 2002
- Mensajes: 8934
- Loc: Seattle, WA & Phoenix, AZ
- Status: Offline
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 ().
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 = > array ("pipa", "w")) para que funcione.
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 . ']'
);
}
?>
$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 . ']'
);
}
?>
- <?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 . ']'
- );
- }
- ?>
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 = > array ("pipa", "w")) para que funcione.
Ozzu Hosting - Want your website on a fast server like Ozzu?
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
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)
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


- Registrado: Dic 20, 2002
- Mensajes: 8934
- Loc: Seattle, WA & Phoenix, AZ
- Status: Offline
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.
¿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


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
- ScottG
- Proficient


- Registrado: Jul 06, 2010
- Mensajes: 280
- Status: Offline
Asà que aquà está mi arreglo poco tonta que parece estar trabajando ahoraPHP 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);
}
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);
}
- // 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);
- }
- Bigwebmaster
- Site Admin


- Registrado: Dic 20, 2002
- Mensajes: 8934
- Loc: Seattle, WA & Phoenix, AZ
- Status: Offline
Consigues una solución Scott, no importa lo fea es alegre.
¿Asà que parece que el problema tenÃa que ver con las sesiones?
¿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


- Registrado: 25 Feb 2008
- Mensajes: ?
- Loc: Ozzuland
- Status: Online
Marzo 6th, 2013, 12:30 pm
1, 2
Para responder a este tema que necesita para ingresar o registrarse. Es gratis.
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
