#!/usr/bin/php4 -q
<?php

/*

    Created 20020708 by Martin List-Petersen <martin@list-petersen.dk>
    
    This thing creates filters for maildrop from some templates


    This code is provided AS IS and released under the GNU GPL v2 only. 
    The license can be downloaded at http://www.marlow.dk/tech/gpl.txt

    20030810 - fixed some minor bugs, not sorting the rules correctly, added activate field to database
    20030807 - public release

*/

function slashes($data$extended=FALSE)
{
    
$data str_replace(" ""\\ "$data);
    
$data str_replace("-""\\-"$data);
    
$data str_replace("_""\\_"$data);
    
$data str_replace("+""\\+"$data);
    
$data str_replace(":""\\:"$data);
    
$data str_replace("'""\\'"$data);
    
$data str_replace(">""\\>"$data);
    
$data str_replace("/""\\/"$data);
    
$data str_replace(".""\\."$data);
    
$data str_replace("@""\\@"$data);
    
$data str_replace("[""\\["$data);
    
$data str_replace("]""\\]"$data);
    
$data str_replace("<""\\<"$data);
    
    return 
$data;
}

function 
error_msg($err)
{
    
// doooh .. didn't work like it should.

    
$error  "maildrop-gen.php 0.2 (C) Martin List-Petersen <martin@list-petersen.dk>\n";
    
$error .= "This code is provided AS IS and released under the GNU GPL v2 only.\n";
    
$error .= "The license can be found here: http://www.marlow.dk/tech/gpl.txt\n\n";
    
$error .= $err."\n\n";

    return 
$error;
}

// missed some, ehhh ?
if($GLOBALS[argv][1] == "")
    die(
error_msg("SYNTAX:\nmaildrop-gen.php user@domain.top"));

// establish db link
$dblink = @mysql_connect("localhost""dbuser""dbpassword") or die("maildrop-gen.php (C) Martin List-Petersen <martin@list-petersen.dk>\n\nCould not connect. Check database settings.\n\n");
mysql_select_db("ispworks") or die(error_msg("Could not select database."));

// set user-email from arguments
$user[email] = $GLOBALS[argv][1];

// get folder information from database
$query  "SELECT homedir,maildir FROM postfix_users WHERE email='".$user[email]."' ORDER BY id";
$result mysql_query($query) or die(error_msg("Query for userdata failed."));
$row    mysql_fetch_row ($result);

$user[folder] = $row[0]."/".$row[1];

// filterfile header
$filteroutput  "#MFMAILDROP=2\n";
$filteroutput .= "#\n";
$filteroutput .= "# DO NOT EDIT THIS FILE.  This is an automatically generated filter.\n\n";

$filteroutput .= "FROM='".$user[email]."'\n";
$filteroutput .= "import SENDER\n";
$filteroutput .= "if (\$SENDER ne \"\")\n";
$filteroutput .= "{\n";
$filteroutput .= " FROM=\$SENDER\n";
$filteroutput .= "}\n\n";

$query  "SELECT op,m_header,m_value,m_folder,m_from,options,name FROM maildrop_rules WHERE email='".$user[email]."' AND active='y' ORDER BY no";
$result mysql_query($query) or die(error_msg("Query for maildrop data failed."));
while(
$row mysql_fetch_row ($result))
{
    
$rule = array(
                                    
"op"      => $row[0],
                                    
"header"  => $row[1],
                                    
"value"   => $row[2],
                                    
"folder"  => $row[3],
                                    
"from"    => $row[4],
                                    
"options" => "",
                                    
"name"    => $row[6]
                                );
                                
    if (
strlen(trim($row[5])) > 0
        
$rule[options] = explode(" "$row[5]);
    else
        
$rule[options] = array();

    
// defaults for the rules
    
$rule_destination "to";

    
// filter start
    
$filteroutput .= "##Op:".$rule[op]."\n";
    
$filteroutput .= "##Header:".$rule[header]."\n";
    
$filteroutput .= "##Value:".$rule[value]."\n";
    
$filteroutput .= "##Folder:".$rule[folder]."\n";
    
$filteroutput .= "##From:".$rule[from]."\n";

    
// check if any options are set and write them to the filterheader
    // check also for changes in settings
    
$plaintext false;
    if(
count($rule[options] > 0))
    {
        for(
$x=0$x count($rule[options]); $x++)
        {
            
$filteroutput .= "##".$rule[options][$x]."\n";
            switch(
$rule[options][$x])
            {
                case 
"Body":
                                    
$body_search true;
                                    break;
                case 
"Continue":
                                    
$rule_destination "cc";
                                    break;
                case 
"PlainString":
                                    
$plaintext true;
                                    break;
            }
        }
    }

    
$filteroutput .= "##Name:".$rule[name]."\n\n\n";

    if(
$body_search == true)
    {
        switch(
$rule[op])
        {
            case 
"contains":
                                 
$filteroutput .= "if ((/".slashes($rule[value])."/:b))\n";
                                 break;
            case 
"startswith":
                                 
$filteroutput .= "if ((/*".slashes($rule[value])."/:b))\n";
                                 break;
        }
        
$body_search false;
    } else {
        switch(
$rule[op])
        {
            case 
"contains":
                                 
$filteroutput .= "if ((/^".$rule[header].":.*".slashes($rule[value])."/))\n";
                                 break;
            case 
"hasrecipient"
                                 
$filteroutput .= "if ((hasaddr(\"".$rule[value]."\")))\n";
                                 break;
            case 
"islargerthan"
                                 
$filteroutput .= "if ((\$SIZE > ".$rule[value]."))\n";
                                 break;
            case 
"startswith":
                                 
$filteroutput .= "if ((/^".$rule[header].": *".slashes($rule[value])."/))\n";
                                 break;
        }
    }

    
$filteroutput .= "{\n";
    if (
substr($rule[folder],0,1) == "!")
    {
        
$filteroutput .= "   ".$rule_destination." \"| \$SENDMAIL -f \" '\"\$FROM\"' \" ".substr($rule[folder],1)."\"\n";
    } else {
        
$filteroutput .= "   ".$rule_destination." \"".$user[folder].$rule[folder]."/.\"\n";
    }
    
$filteroutput .= "}\n\n";
    
$rule = array();
}

mysql_close($dblink);

// filterfile footer
$filteroutput .= "to \"".$user[folder].".\"\n";

// print filter-rules
print $filteroutput;


?>