<?
// this thing is called by procmail when it gets a email that is from
// your address with the right subject.
//
// it decodes the data and writes it to files in data/
// this wont work on win32 I'm afraid.
//


// keep this from being called via apache (for if you are really paranoid)
// personally I just keep this file named .phps since then the web server
// will never execute
if (getenv("REMOTE_ADDR") != "") die("Invalid request\n");


// get current update value
$fp=fopen("data/counter","r+");
flock($fp,LOCK_EX);
$index trim(fgets($fp,1024));
fseek($fp,0,SEEK_SET);
fputs($fp,$index+1);
flock($fp,LOCK_UN);
fclose($fp);


// open stdin
$stdin fopen("php://stdin","r");

// skip headers, look to see if we're demiming.
$ismime=0;
for(;;)
{
  if ((
$t=fgets($stdin,1024)) == "\n") break;
  if (
feof($stdin)) die; //failed finding end of headers
  
if (eregi("^Content-Type:.*multipart/mixed.*",$t)) $ismime=1;
}

// each mime block

$mstart="";

if (
$ismime) for (;;)
{
  
$mstart=fgets($stdin,1024);
  if (
substr($mstart,0,2) == "--") break;
  if (
feof($stdin)) die;
}

do
{
  
// next chunk if mime, only chunk if not mime :)
  
$isjpeg=0;
  if (
$ismime) for (;;)
  {
    
$x=fgets($stdin,1024);
    if (
$x == "\n") break;
    if (
feof($stdin)) die; //failed finding end of mime headers
    
if (eregi("^Content-Type:.*jpeg.*",$x)) $isjpeg=1;
  }

  
// output filename
  
if ($isjpeg$fnt="data/image_$index.jpg";
  else 
$fnt="data/text_$index.txt";
  
$outfp=fopen($fnt,"w");
  
$jpegdata="";

  for(;;)
  {
    
$mend=fgets($stdin,1024);
    if (
$ismime)
    {
      if (
$mend == substr($mstart,0,-1) . "--\n" || $mend == $mstart "--") { $mstart=""; break; }
      if (
$mend == substr($mstart,0,-1) . "\n") break;

      if (
feof($stdin)) die; //"failed finding mimeend
    

    else if (
feof($stdin)) break;

    if (!
$isjpegfputs($outfp,$mend);
    else 
$jpegdata .= $mend;
  }
  if (
$isjpegfwrite($outfp,base64_decode($jpegdata));
  
fclose($outfp);
  
chmod($fnt,0644);
} while (
$mstart != "");

fclose($stdin);

?>