#!/usr/local/bin/php

<?php

/* MAIL HANDLING/PARSING
* If the mail has gotten as far as this
* script, then Procmail has forwarded it here
* so now we need to parse it and post it
*/

// read from stdin
$fd fopen("php://stdin""r");
$email "";
while (!
feof($fd)) {
    
$email .= fread($fd1024);
}
fclose($fd);

// handle email
$lines explode("\n"$email);

// empty vars
$from "";
$subject "";
$headers "";
$message "";
$splittingheaders true;

for (
$i=0$i<count($lines); $i++) {
    if (
$splittingheaders) {
        
// this is a header
        
$headers .= $lines[$i]."\n";

        
// look out for special headers
        
if (preg_match("/^Subject: (.*)/"$lines[$i], $matches)) {
            
$subject $matches[1];
        }
        if (
preg_match("/^From: (.*)/"$lines[$i], $matches)) {
            
$from $matches[1];
        }
    } else {
        
// not a header, but message
        //$message .= $lines[$i]."\n";
    
$message .= $lines[$i]." ";
    }

    if (
trim($lines[$i])=="") {
        
// empty line, header section has ended
        
$splittingheaders false;
    }
}

// parse the subject line to get the secretword
$token explode(" "$subject);
$secretword $token[1];

// open db connection
$connection mysql_connect("localhost""user""pass");
mysql_select_db("main"$connection);

// get username based on secretword (to use in posting query below)
$query_s "SELECT username FROM secretwords WHERE secretword='$secretword'";
$result_s mysql_query($query_s$connection) or die ("query failed on secretword");
while (
$row mysql_fetch_array($result_s)) {
    
$username $row[0];
}

// this query is a straight ripoff from the standard posting script
// with minor modifications
// don't forget to get timezone offset too!
$query "SELECT user_id, tz_offset FROM users WHERE username = '$username'";
$result mysql_query($query$connection) or die("query failed");
while (
$row = @ mysql_fetch_array($result)) {
$user_id $row["user_id"];
$tz_offset $row["tz_offset"];
}

// before content is inserted into database, quotes and
// apostrophes must be escaped - otherwise, the javascript
// import function breaks later and nothing works

$message mysql_escape_string($message);

// processing of message string so javascript display doesn't choke on it
//$message = str_replace("\n", " ", $message);
$message rtrim($message);

// post form content to db
$query2 "INSERT INTO posts VALUES
    (NULL, '" 
$user_id "', date_add(now(), interval '" $tz_offset "' hour), '" $title "', '" $message "', 0)";
$result2 mysql_query($query2) or die("Query failed 2" mysql_error());

// update the activity monitor in the users table (lastpost column)
$now date("Y-m-d");

$query3 "UPDATE users
         SET lastpost = '" 
$now "'
         WHERE user_id = $user_id"
;
$result mysql_query($query3) or die("Query failed 3" mysql_error());

?>