<?php
/* ******************************************************************
** THUMBNAIL GENERATION SCRIPT
** NOTE THAT SCRIPT REQUIRES WRITABLE 'DATA' SUBDIRECTORY
** SCRIPT COPYRIGHT 2006
** RUSS GILMAN-HUNT, ARGHWEBWORKS
** http://www.arghwebworks.com/
**
** This is primarily a workable 'code sample' for Russell Gilman-Hunt
** Feel free to copy, modify, et cetera
**
****************************************************************** */
// set these defaults here so I don't have to calculate them later.
$uploaddir=dirname(__FILE__) . '/data/';
$maxsize=1024*1024;
$thumbsizes=array(
    
'small'=>72,
    
'medium'=>128,
    
'large'=>144,
);


// have we submitted this form?
if ( count($_POST) >){
    
// cleanup the data directory.
    // using it here rather than in a cron for ease-of-coding.

    
cleanup();
    
$thumbsize=$_POST['tsize'];
    
$tsquare=$_POST['tsquare'];
    
$uploadfile $uploaddir basename($_FILES['userfile']['name']);
    
// make sure we were able to move the file.
    
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))  {
        
$filename=$_FILES['userfile']['name'];
        
$filetype=$_FILES['userfile']['type'];
        
$filesize=$_FILES['userfile']['size'];
        
// another place to check for filesize being too large.
        
if ( $filesize $maxsize ) die ("file was too big. Upload attack?");

    }
    else {
        die (
'some problem moving the uploaded file. Sorry it didn\'t work out.');
    }
    
// largest side of the image is based on this value;
    
$largestside=$thumbsizes[$thumbsize];
    
// are we dealing with a square or a rectangular image?
  
if ( $tsquare == 'yes' ) {
      
$thumb=cutSquare($uploadfile$largestside);
  }
  else {
      
$thumb=resizeImage($uploadfile$largestside);
  }
  
// need to create the thumbnail file:
  
$thumbfilename=mktime()."_t.jpg";
  
imagejpeg$thumb$uploaddir.$thumbfilename );
  
imagedestroy$thumb );
  
$content=<<<EOF
<div class='note'>
<P>Save this image to your own computer; we remove files older than 1 hour. </p>
<P>To do this, right click on the image and select "save as..." and enter a name for your file.
<p>Or if you only have one mouse button, hold down the control key and click, and select the same from the contextual menu.</p>
<p>Thank you.</p>
</div>
<img src='data/$thumbfilename' />
EOF;

}
else {
$content=<<<EOF
<div class='note'>
    You are restricted to files of one megabyte or smaller. Please
    ensure that your file isn't any larger than that.
    <br />
    Thank you.
</div>

<form enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?=$maxsize?>" />
My Original:<input name="userfile" type="file" />
<fieldset>
<legend>Options</legend>
  <table class='edittable'>
      <tr>
          <th valign=top rowspan=3>Thumbnail Size</th>
          <td><input type='radio' name='tsize' value='small' />Small ( THUMBSMALL px )</td>
      </tr>
      <tr>
          <td><input type='radio' name='tsize' value='medium' checked />Medium ( THUMBMEDIUM px )</td>
      </tr>
      <tr>
          <td><input type='radio' name='tsize' value='large' />Large ( THUMBLARGE px )</td>
      </tr>
      <tr>
          <th>Square Thumbnail?</th>
          <td><input type='checkbox' name='tsquare' value='yes' /> <em>If this box is checked, we will cut a thumbnail out of the center of your image rather than resizing the image to fit the thumbnail size</em></td>
      </tr>
     </table>
</fieldset>
<input type="submit" value="Send File" />
    </form>
EOF;

$content str_replace(array("THUMBSMALL","THUMBMEDIUM","THUMBLARGE"), array_values($thumbsizes), $content );

}
// content is created and now we just have to display it.
?>
<html>
<head>
<title>ArghWebWorks Thumbnail Service</title>
<style>
    body {
        font-family:verdana,helvetica,arial,sans-serif;
        font-size:10pt;

        }
    .note {
    border:1px solid #800;
    float:right;
    width:20%;
    font-size:0.8em;
    padding:5px 10px 5px 10px;

    }
    .mainfield {
        width:70%;
        padding:5px;
        margin:5px 25px 0 25px;
        }
    .mainlegend  {
        font-size:150%;
        border:1px solid #800;
        background-color:#800;
        color:white;

        }
    fieldset {
        border:3px solid #800;
        }
    legend {
        font-size:110%;
        border-right:2px solid #800;
        border-bottom:2px solid #800;
        }
    table.edittable tr th {
        text-align:right;
        font-weight:normal;
        background-color:#088;
        color:white;
        }
    em {
        font-size:0.75em;
        }
</style>
</head>
<body>
<fieldset class='mainfield'>
<legend class='mainlegend'>Automatic Thumbnail Generator</legend>
<?=$content?>
<P>
    <a href='autothumb.phps'>Want the Source?</a>
</p>
</fieldset>
</body></html>
<?
/* functions */


/*cutSquare( filename, sidelength );
creates the thumbnail and returns the filename.
takes the name of the file and creates a thumbnail based on the center of the image.*/
function cutSquare$filename$sidelength ) {
    
// need the sizes of the
    
list($width$height$type$attr) = getimagesize($filename);
    
// locate the top left corner of the square.
    // is that correct?
    
$left=round ( ($width /)-($sidelength/2) ) ;
    
$top=round( ( $height /) - ( $sidelength ) );
    
// create the image resource from which we will copy the image.
    
$srcimg=imagecreatefromjpeg$filename );
  
$dstimg=createImg$sidelength$sidelength );
  
// copy the image over.
  
$success=imagecopy$dstimg$srcimg00$top$left$sidelength$sidelength );
  
imagedestroy$srcimg );
  if ( !
$success )  die("some error in __FUNCTION__ ");
  return 
$dstimg;
}
/* resizeImage( $filename, $longestside ) {
calculates the size of the short side, creates thumbnail and returns filename.
*/
function resizeImage$filename$sidelength ){
    list(
$width$height$type$attr) = getimagesize($filename);
    
$newwidth=$newheight=0;

    
// is this a portrait or a landscape (or a square) photo?
    
if ( $width $height ) {
        
// landscape
        
$newwidth=$sidelength;
        
$newheight=round( ( $height $width ) * $sidelength );
    }
    elseif ( 
$width == $height ) {
        
// square
        
$newwidth=$newheight=$sidelength;
    }
    else {
        
// portrait
        
$newheight=$sidelength;
        
$newwidth=round(( $width/$height) * $sidelength );
    }
    
// get the sourceimg
    
$srcimg=imagecreatefromjpeg$filename);
    
// create the dstimg
    
$dstimg=createImg$newwidth$newheight );

    
// copy over, resizing the image.
    // return the image resource.
    
$success=imagecopyresized($dstimg$srcimg0000$newwidth$newheight$width$height);
    
imagedestroy$srcimg );
    if ( !
$success ) die ( "error copying image in __FUNCTION__");
    return 
$dstimg;
}

// this is just to create the image handle we desire.
// use it to create an image.
// we're using this in case the imagecreatetruecolor doesn't work for us
// (ie, it may die with an error string, not creating an image )
function createImg$width=0$height=) {
    if ( ( 
$width == ) || ( $height == ) ) die ('invalid height/width  specified in  __FUNCTION__' );
    
$returnval=@imagecreatetruecolor($width$height);
    if ( !
$returnval ) {
        
$tmpfile='/tmp/' mktime() . ".jpg";
        
$thumb=imagecreate$width$height );
        
imageJPEG$thumb$tmpfile );
        
imagedestroy$thumb );
        
$returnval=@imagecreatefromjpeg$tmpfile );
        
unlink$tmpfile );
    }
    return 
$returnval;


}

// cleans out all files in the upload directory that are older than one hour
// in order to keep disk usage down (and deter linking to our thumbnails).
//
function cleanup() {
    global 
$uploaddir;

    
// we _know_ it's a directory, but let's be sure.
    
if (is_dir($uploaddir)) {
   if (
$dh opendir($uploaddir)) {
       while ((
$file readdir($dh)) !== false) {
               
$wholefile=$uploaddir $file ;
               if ( !
is_file$wholefile ) ) continue;
               
$filem=filemtime$wholefile );
          if ( 
mktime()-$filem 3600 unlink ($wholefile );
        }
        
closedir($dh);
      }
    }
    return 
true;
}
?>