<?php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2002, Richard Heyes                                     |
// | All rights reserved.                                                  |
// |                                                                       |
// | Redistribution and use in source and binary forms, with or without    |
// | modification, are permitted provided that the following conditions    |
// | are met:                                                              |
// |                                                                       |
// | o Redistributions of source code must retain the above copyright      |
// |   notice, this list of conditions and the following disclaimer.       |
// | o Redistributions in binary form must reproduce the above copyright   |
// |   notice, this list of conditions and the following disclaimer in the |
// |   documentation and/or other materials provided with the distribution.| 
// | o The names of the authors may not be used to endorse or promote      |
// |   products derived from this software without specific prior written  |
// |   permission.                                                         |
// |                                                                       |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
// |                                                                       |
// +-----------------------------------------------------------------------+
// | Author: Richard Heyes <richard@phpguru.org>                           |
// +-----------------------------------------------------------------------+
//
// $Id: Net_POP3_example.php,v 1.2 2002/07/27 13:07:55 richard Exp $
?>
<html>
<body>
<?php

include('Net_POP3.php');
include('Mail/mimeDecode.php');

/*
*  All of the modifyable elements - Charles Severance
*/

// When testmode is set to 1, do not delete the messages
$testmode = 0;

// Do not add a trailing slash to the home directory
$homedir = "/kunden/homepages/17/d88943663/htdocs/images";
$photolog = $homedir . "/../photolog.txt";

// This account must be dedicated to SMS messages - this software
// Deletes every message it finds.  If it is not a correct format
// message - it  gets deleted.

$pophost = "mail.xyz.net";
$poplogin = "xyz";
$poppw = "xyz";

// Only accept messages from this phone number 
$fromstring = "5111234567";

/*
*  End of the modifyable parts
*/

/*
* Create the class
*/
$pop3 =& new Net_POP3();

/*
* Connect to lhost on usual port
* If not given, defaults are localhost:110
*/
$pop3->connect($pophost, 110, 5);

/*
* Login using username/password. APOP will
* be tried first if supported, then basic.
*/
$pop3->login($poplogin, $poppw);

/*
* Get number of messages in maildrop
*/
echo '<h2>getNumMsg</h2>';
echo '<pre>' . $pop3->numMsg() . '</pre>';

/*
 *  Decode the MIME in the message
 */

echo '<h2>mimeDecode()</h2>';
echo '<pre>\r\n';

$imessage = $pop3->numMsg();

for ($i = 1; $i <= $pop3->numMsg(); $i++) { 

  echo "\r\n============  Start Processing ============\r\n";

  $input = $pop3->getMsg($i);

  $params['include_bodies'] = true;
  $params['decode_bodies']  = true;
  $params['decode_headers'] = true;

  $decoder = new Mail_mimeDecode($input);
  $structure = $decoder->decode($params);

  // print_r($structure);
  // print_r("Text part:" . $structure->parts[0]->body);
  // print_r("ctype:" . $structure->parts[1]->ctype_parameters[name]);
  // print_r("body:" . $structure->parts[1]->body); 
  // print_r("from:" . $structure->headers[from]);
  // echo "\r\n";

  // echo "Position = " . strpos($structure->headers[from],$fromstring) . "\r\n";

  if ( strpos($structure->headers[from], $fromstring) === false  ) {
    echo "From address not allowed: " . $structure->headers[from] . "\r\n";
    if ( $testmode == 1 ) {
    	echo "Not deleteing unauthorized message because of testmode\r\n";
    } else {
      echo "Deleting incorect from address message " . $i . "\r\n" ; 
      $pop3->deleteMsg($i);
    }
    continue;
  }

  $meta_data = $structure->parts[0]->body;

  $imagename = $structure->parts[1]->ctype_parameters[name];
  echo "Image Name from c_type = " . $imagename . "\r\n";
  if ( ! $imagename ) {
    $imagename = $structure->parts[1]->d_parameters[filename];
    echo "Image Name from d_parameters = " . $imagename . "\r\n";
  }

  // Compute the check sum and see if this is a duplicate

  $checksum = crc32($structure->parts[1]->body);
  echo "Checksum " . $checksum . "\r\n";
  $checksum_match = false;

  $handle = fopen($photolog, 'r');
  if ( $handle ) while ( ! feof($handle) ) {
  $line_input = fgets($handle,1024);
    // echo "Line:" . $line_input . "\r\n";
    $buffer = split(",",$line_input);
    // echo "Read:" . $buffer[1] . " " . $buffer[3] . "\r\n";
    if ( $buffer[3] == $checksum ) {
    	echo "Found a checksum match!\r\n";
	$imagename = $buffer[1];
        $checksum_match = true;
	break;
    }
  }
  fclose($handle);

  echo "Final Image Name = " . $imagename . "\r\n";

  // Come up with the year, month, and image name depending on the image name

  // Motorola v300:  20-06-04_0827.jpg
  // Treo 600 Variant 1: Picture006_19Jun04.jpg
  // Treo 600 MMS: image000.jpg
  // In the short term, we parse the string and see if it is valid Motoroloa otherwise
  // we fake the valid motorola

  $parts = split("[-_]", $imagename);
  
  echo "Part count:" . count($parts) . "\r\n";
  print_r($parts);
  
  if ( count($parts) == 4 && strlen($parts[0]) == 2 && strlen($parts[1]) ==2 &&
        strlen($parts[2]) == 2 && strlen($parts[3]) >= 8 ) {
    echo "Motorola v300 format file:" . $imagename . "\r\n";
    $month = $parts[1];
    $year = "20" . $parts[2];
  } else { 
    $month = date("m");
    $year = date("Y");
    $imagename = date("d-m-y_Hi") . sprintf("%03d",$i) . ".jpg";
  }

  echo $imagename . "(" . $year . " " . $month . ")\r\n";
  $dotpos = strrpos($imagename, '.');
  $meta_name = null;

  if ($dotpos) {
    $ext = substr($imagename, $dotpos+1);
    $meta_name = substr($imagename,0,$dotpos);
    echo "Meta file=" . $meta_name . "\r\n";
    if ($ext != 'jpg' ) {
      if ( $testmode == 1 ) {
      	echo "Not deleteing non-jpg message because of testmode\r\n";
      } else {
        echo "Deleting non-jpg message " . $i . "\r\n" ; 
        $pop3->deleteMsg($i);
      }
      continue;
    }
  }

  // Delete the signature and detect for an empty message
  if ( $meta_data ) {
    $sigpos = strpos($meta_data,"---");
    if ( ! $sigpos ) $sigpos = strpos($meta_data,"___");
    if ( $sigpos ) $meta_data = substr($meta_data,0,$sigpos-1);
    echo "Metadata (" . strlen($meta_data) . " bytes): " . $meta_data . "\r\n";
    if ( strlen($meta_data) < 4 ) $meta_data = null;
  }

  if ( $meta_name ) $meta_name = $meta_name . ".txt";
  echo "Meta file=" . $meta_name . "\r\n";

  if ( strlen($month) == 2 && strlen($year) == 4 ) {
    $filename = $homedir . "/" . $year ;
    echo "mkdir " . $filename . "\r\n";
    if ( mkdir($filename,0755) ) {
      echo "cp " . $filename . "/../index.php ". $filename . "/index.php" . "\r\n";
      copy( $filename . "/../index.php", $filename . "/index.php");
    }

    $filename = $filename . "/" . $month ;
    echo "mkdir " . $filename . "\r\n";
    if ( mkdir($filename,0755) ) {
      echo "cp " . $filename . "/../index.php ". $filename . "/index.php" . "\r\n";
      copy( $filename . "/../index.php", $filename . "/index.php");
    }

    if ( $meta_name ) $meta_file = $filename . "/" . $meta_name;
    $filename = $filename . "/" . $imagename;
  } else {
    $meta_file = null;
    $filename = $homedir . "/" . $imagename;
  }
  
  echo "Writing file = " . $filename . "\r\n";
  $handle = fopen($filename, 'w');
  fwrite($handle, $structure->parts[1]->body);
  fclose($handle);

  echo "Meta File = " . $meta_file . "\r\n";
  echo "Meta Data = " . $meta_data . "\r\n";
  if ( $meta_file && $meta_data ) {
    echo "Writing metadata file = " . $meta_file . "\r\n";
    $handle = fopen($meta_file, 'w');
    fwrite($handle, $meta_data);
    fclose($handle);
  }

  // Write the log file

  if ( ! $checksum_match ) {
    $handle = fopen($photolog, 'a');
    $val = date("m/d/Y H:i:s,") . $imagename . "," . $meta_name . "," .$checksum . "," . $filename . "," . $meta_file . "\r\n";
    echo $val ; 
    fwrite($handle,$val);
    fclose($handle);
  }

  // Slide into the home directory

  $filename = $homedir . "/../lastblog.jpg";
  echo "Writing file = " . $filename . "\r\n";
  $handle = fopen($filename, 'w');
  fwrite($handle, $structure->parts[1]->body);
  fclose($handle);

/*
 *  Delete the message
 */

if ( $testmode == 1 ) {
  echo "Test-mode Not deleting message " . $i . "\r\n" ; 
} else {
  echo "Deleting message " . $i . "\r\n" ; 
  $pop3->deleteMsg($i);
}

 if ( $i > 10 ) break;
}

echo '</pre>';

/*
* Disconnect
*/
$pop3->disconnect();
?>
