#!/usr/bin/php -q
<?
include('Mail/mimeDecode.php');

/* expects to receive mail from stdin */

$input file_get_contents("php://stdin");

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

$email Mail_mimeDecode::decode($params);

/* check to see if valid email */
if (!isset($email->headers['to'])) {
    die(
"not a valid email!\n");
  }

if (
stripos($email->headers['subject'], "Direct message from") !== FALSE) {
  
dm($email);
 } else if (
stripos($email->headers['subject'], "Re: DM from [") !== FALSE) {
  
dm_reply($email);
 } else {
  
/* ignore this email */
 
}

/* the end */


/*
 * Functions to handle mail
 *
 */


function dm(&$email) {
  
$from $email->headers['x-twittersendername'];
  
$fromsn $email->headers['x-twittersenderscreenname'];
  
$sig "$from / $fromsn";

  foreach (
$email->parts as $part) {

    
/* is this the plain text part of the DM email? */
    
if ($part->ctype_primary=='text' && $part->ctype_secondary == 'plain') {

      
$partbody $part->body;
      
$dmtext trim(substr($partbody0stripos($partbody,$sig)));

    }
  }

  
// send DM text email
  
$to "email@domain.com";
  
$subject "DM from [" $fromsn "]";
  
$body "DM Text from [" $fromsn "]:\n\n$dmtext \n\n ";
  
$headers 'From: bot <bot@domain.com>';
  
mail($to$subject$body$headers);

/* end function dm */

function dm_reply(&$email) {
  
$dm_to substr($email->headers['subject'], stripos($email->headers['subject'], '[') + 1stripos($email->headers['subject'], ']') - stripos($email->headers['subject'], '[') - 1);

  
$dmtext substr($email->body0stripos($email->body"\n\n"));
  
$dmtext trim($dmtext);
  
$dmtext str_replace("\n"" "$dmtext);
  
$dmtext str_replace("\r"" "$dmtext);

  
/* send the DM */
  
$host "https://twitter.com/direct_messages/new.json";
  
$ch curl_init();
  
curl_setopt($chCURLOPT_URL"$host");
  
curl_setopt($chCURLOPT_VERBOSE1);
  
curl_setopt($chCURLOPT_RETURNTRANSFER1);
  
curl_setopt($chCURLOPT_TIMEOUT15);
  
curl_setopt($chCURLOPT_POSTFIELDS"user=" $dm_to "&text=" urlencode($dmtext));
  
curl_setopt($chCURLOPT_USERPWD"user:password");
  
curl_setopt($chCURLOPT_HEADERfalse);
  
curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_0);
  
curl_setopt($chCURLOPT_POST1);
  
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
  
$result curl_exec($ch);
  
curl_close($ch);

  
$json json_decode($result);

  
/* if there's an error, send email about it */
  
if (isset($json->error)) {
    
$to "email@domain.com";
    
$subject "ERROR: DM to $dm_to";
    
$body "Would be DM'ing: $dm_to\n\nDM text: >$dmtext< \n\nresponse was:\n$result";
    
$headers 'From: bot <bot@domain.com>';
    
mail($to$subject$body$headers);
  }

/* end function dm_reply */

?>