<?php
/**
 * The Ingo_Script_procmail:: class represents a Procmail script generator.
 *
 * $Horde: ingo/lib/Script/procmail.php,v 1.46.10.1 2005/01/03 12:25:38 jan Exp $
 *
 * Copyright 2003-2005 Brent J. Nordquist <bjn@horde.org>
 * Copyright 2003-2005 Ben Chavet <ben@chavet.net>
 *
 * See the enclosed file LICENSE for license information. If you
 * did not receive this file, see http://www.horde.org/licenses.
 *
 * @author  Brent J. Nordquist <bjn@horde.org>
 * @author  Ben Chavet <ben@chavet.net>
 * @version $Revision: 1.46.10.1 $
 * @since   Ingo 0.1
 * @package Ingo
 */
class Ingo_Script_procmail extends Ingo_Script {

    /**
     * The list of actions allowed (implemented) for this driver.
     *
     * @var array $_actions
     */
    var $_actions = array(
        INGO_STORAGE_ACTION_KEEP,
        INGO_STORAGE_ACTION_MOVE,
        INGO_STORAGE_ACTION_DISCARD,
        INGO_STORAGE_ACTION_REDIRECT,
        INGO_STORAGE_ACTION_REDIRECTKEEP,
        INGO_STORAGE_ACTION_REJECT
    );

    /**
     * The categories of filtering allowed.
     *
     * @var array $_categories
     */
    var $_categories = array(
        INGO_STORAGE_ACTION_BLACKLIST,
        INGO_STORAGE_ACTION_WHITELIST,
        INGO_STORAGE_ACTION_VACATION,
        INGO_STORAGE_ACTION_FORWARD
    );

    /**
     * The types of tests allowed (implemented) for this driver.
     *
     * @var array $_types
     */
    var $_types = array(
        INGO_STORAGE_TYPE_HEADER,
    );

    /**
     * The list of tests allowed (implemented) for this driver.
     *
     * @var array $_tests
     */
    var $_tests = array(
        'contains',
        'begins with',
        'ends with',
        'regex'
    );

    /**
     * Can tests be case sensitive?
     *
     * @var boolean $_casesensitive
     */
    var $_casesensitive = true;

    /**
     * Does the driver support the stop-script option?
     *
     * @var boolean $_supportStopScript
     */
    var $_supportStopScript = true;

    /**
     * Does the driver require a script file to be generated?
     *
     * @var boolean $_scriptfile
     */
    var $_scriptfile = true;

    /**
     * The recipes that make up the code.
     *
     * @var array $_recipes
     */
    var $_recipes = array();

    /**
     * Returns a script previously generated with generate().
     *
     * @access public
     *
     * @return string  The procmail script.
     */
    function toCode()
    {
        $code = '';
        foreach ($this->_recipes as $item) {
            $code .= $item->generate() . "\n";
        }
        return rtrim($code);
    }

    /**
     * Generates the procmail script to do the filtering specified in
     * the rules.
     *
     * @access public
     *
     * @return string  The procmail script.
     */
    function generate()
    {
        global $ingo_storage;

        $filters = $ingo_storage->retrieve(INGO_STORAGE_ACTION_FILTERS);

        $this->addItem(new Procmail_Comment(_("procmail script generated by Ingo") . ' (' . date('F j, Y, g:i a') . ')'));

        /* Add variable information, if present. */
        if (!empty($this->_params['variables']) &&
            is_array($this->_params['variables'])) {
            foreach ($this->_params['variables'] as $key => $val) {
                $this->addItem(new Procmail_Variable(array('name' => $key, 'value' => $val)));
            }
        }

        foreach ($filters->getFilterlist() as $filter) {
            switch ($filter['action']) {
            case INGO_STORAGE_ACTION_BLACKLIST:
                $this->generateBlacklist(!empty($filter['disable']));
                break;

            case INGO_STORAGE_ACTION_WHITELIST:
                $this->generateWhitelist(!empty($filter['disable']));
                break;

            case INGO_STORAGE_ACTION_VACATION:
                $this->generateVacation(!empty($filter['disable']));
                break;

            case INGO_STORAGE_ACTION_FORWARD:
                $this->generateForward(!empty($filter['disable']));
                break;

            default:
                if (in_array($filter['action'], $this->_actions)) {
                    /* Create filter if using AND. */
                    if ($filter['combine'] == INGO_STORAGE_COMBINE_ALL) {
                        $recipe = &new Procmail_Recipe($filter, $this->_params);
                        if (!$filter['stop']) {
                            $recipe->addFlag('c');
                        }
                        foreach ($filter['conditions'] as $condition) {
                            $recipe->addCondition($condition);
                        }
                        $this->addItem(new Procmail_Comment($filter['name'], !empty($filter['disable']), true));
                        $this->addItem($recipe);
                    } else {
                        /* Create filter if using OR */
                        $this->addItem(new Procmail_Comment($filter['name'], !empty($filter['disable']), true));
                        $loop = 0;
                        foreach ($filter['conditions'] as $condition) {
                            $recipe = &new Procmail_Recipe($filter, $this->_params);
                            if ($loop++) {
                                $recipe->addFlag('E');
                            }
                            if (!$filter['stop']) {
                                $recipe->addFlag('c');
                            }
                            $recipe->addCondition($condition);
                            $this->addItem($recipe);
                        }
                    }
                }
            }
        }

        return $this->toCode();
    }

    /**
     * Generates the procmail script to handle the blacklist specified in
     * the rules.
     *
     * @access public
     *
     * @param optional boolean $disable  Disable the blacklist?
     */
    function generateBlacklist($disable = false)
    {
        global $ingo_storage;

        $blacklist = $ingo_storage->retrieve(INGO_STORAGE_ACTION_BLACKLIST);
        $bl_addr = $blacklist->getBlacklist();
        $bl_folder = $blacklist->getBlacklistFolder();

        $bl_type = (empty($bl_folder)) ? INGO_STORAGE_ACTION_DISCARD : INGO_STORAGE_ACTION_MOVE;

        if (!empty($bl_addr)) {
            $this->addItem(new Procmail_Comment(_("Blacklisted Address"), $disable, true));
            $params = array('action-value' => $bl_folder,
                            'action' => $bl_type,
                            'disable' => $disable);

            foreach ($bl_addr as $address) {
                if (!empty($address)) {
                    $recipe = &new Procmail_Recipe($params, $this->_params);
                    $recipe->addCondition(array('field' => 'From', 'value' => $address));
                    $this->addItem($recipe);
                }
            }
        }
    }

    /**
     * Generates the procmail script to handle the whitelist specified in
     * the rules.
     *
     * @access public
     *
     * @param optional boolean $disable  Disable the whitelist?
     */
    function generateWhitelist($disable = false)
    {
        global $ingo_storage;

        $whitelist = $ingo_storage->retrieve(INGO_STORAGE_ACTION_WHITELIST);
        $wl_addr = $whitelist->getWhitelist();

        if (!empty($wl_addr)) {
            $this->addItem(new Procmail_Comment(_("Whitelisted Addresses"), $disable, true));
            foreach ($wl_addr as $address) {
                if (!empty($address)) {
                    $recipe = &new Procmail_Recipe(array('action' => INGO_STORAGE_ACTION_KEEP, 'disable' => $disable), $this->_params);
                    $recipe->addCondition(array('field' => 'From', 'value' => $address));
                    $this->addItem($recipe);
                }
            }
        }
    }

    /**
     * Generates the procmail script to handle vacation.
     *
     * @access public
     *
     * @param optional boolean $disable  Disable vacation?
     */
    function generateVacation($disable = false) 
    {
        global $ingo_storage;

        $vacation = $ingo_storage->retrieve(INGO_STORAGE_ACTION_VACATION);
        $addresses = $vacation->getVacationAddresses();
        $actionval = array('addresses' => $addresses,
                           'subject' => $vacation->getVacationSubject(), 
                           'days' => $vacation->getVacationDays(), 
                           'reason' => $vacation->getVacationReason(),
                           'ignorelist' => $vacation->getVacationIgnorelist(),
                           'excludes' => $vacation->getVacationExcludes());

        if (!empty($addresses)) {
            $this->addItem(new Procmail_Comment(_("Vacation"), $disable, true));
            $params = array('action' => INGO_STORAGE_ACTION_VACATION,
                            'action-value' => $actionval,
                            'disable' => $disable);
            $recipe = &new Procmail_Recipe($params, $this->_params);
            $this->addItem($recipe);
        }
    }

    /** 
     * Generates the procmail script to handle mail forwards.
     *
     * @access public
     *
     * @param optional boolean $disable  Disable forwarding?
     */
    function generateForward($disable = false)
    {
        global $ingo_storage;

        $forward = $ingo_storage->retrieve(INGO_STORAGE_ACTION_FORWARD);
        $addresses = $forward->getForwardAddresses();

        if (!empty($addresses)) {
            $this->addItem(new Procmail_Comment(_("Forwards"), $disable, true));
            $params = array('action' => INGO_STORAGE_ACTION_FORWARD,
                            'action-value' => $addresses,
                            'disable' => $disable);
            $recipe = &new Procmail_Recipe($params, $this->_params);
            if ($forward->getForwardKeep()) {
                $recipe->addFlag('c');
            }
            $this->addItem($recipe);
        }
    }

    /**
     * Adds an item to the recipe list.
     *
     * @access public
     *
     * @param object $item  The item to add to the recipe list.
     *                      The object should have a generate() function.
     */
    function addItem($item)
    {
        $this->_recipes[] = $item;
    }

}

/**
 * The Procmail_Comment:: class represents a Procmail comment.  This is
 * a pretty simple class, but it makes the code in Ingo_Script_procmail::
 * cleaner as it provides a generate() function and can be added to the
 * recipe list the same way as a recipe can be.
 *
 * @author  Ben Chavet <ben@chavet.net>
 * @since   Ingo 1.0
 * @package Ingo
 */
class Procmail_Comment {

    /**
     * The comment text.
     *
     * @var string $_comment
     */
    var $_comment = '';

    /**
     * Constructs a new procmail comment.
     *
     * @access public
     *
     * @param string $comment            Comment to be generated.
     * @param optional boolean $disable  Output 'DISABLED' comment?
     * @param optional boolean $header   Output a 'header' comment?
     */
    function Procmail_Comment($comment, $disable = false, $header = false)
    {
        if ($disable) {
            $comment = _("DISABLED: ") . $comment;
        }

        if ($header) {
            $this->_comment .= "##### $comment #####";
        } else {
            $this->_comment .= "# $comment";
        }
    }

    /**
     * Returns the comment stored by this object.
     *
     * @access public
     *
     * @return string  The comment stored by this object.
     */
    function generate()
    {
        return $this->_comment;
    }

}

/**
 * The Procmail_Recipe:: class represents a Procmail recipe.
 *
 * @author  Ben Chavet <ben@chavet.net>
 * @since   Ingo 1.0
 * @package Ingo
 */
class Procmail_Recipe {

    var $_action = array();
    var $_conditions = array();
    var $_disable = '';
    var $_flags = '';
    var $_params = array();
    var $_valid = true;

    /**
     * Constructs a new procmail recipe.
     *
     * @access public
     *
     * @param optional array $params        Array of parameters.
     *                                      REQUIRED FIELDS:
     *                                      'action'
     *                                      OPTIONAL FIELDS:
     *                                      'action-value' (only used if the
     *                                      'action' requires it)
     * @param optional array $scriptparams  Array of parameters passed to
     *                                      Ingo_Script_procmail::.
     */
    function Procmail_Recipe($params = array(), $scriptparams = array())
    {
        $this->_disable = !empty($params['disable']);
        $this->_params = $scriptparams;

        switch($params['action']) {
        case INGO_STORAGE_ACTION_KEEP:
            $this->_action[] = '$DEFAULT';
            break;
        
        case INGO_STORAGE_ACTION_MOVE:
            $this->_action[] = $this->procmailPath($params['action-value']);
            break;

        case INGO_STORAGE_ACTION_DISCARD:
            $this->_action[] = '/dev/null';
            break;

        case INGO_STORAGE_ACTION_REDIRECT:
            $this->_action[] = '! ' . $params['action-value'];
            break;

        case INGO_STORAGE_ACTION_REDIRECTKEEP:
            $this->_action[] = '{';
            $this->_action[] = '  :0 c';
            $this->_action[] = '  ! ' . $params['action-value'];
            $this->_action[] = '';
            $this->_action[] = '  :0';
            $this->_action[] = '  $DEFAULT';
            $this->_action[] = '}';
            break;

        case INGO_STORAGE_ACTION_REJECT:
            $this->_action[] = '{';
            $this->_action[] = '  EXITCODE=' . $params['action-value'];
            $this->_action[] = '  HOST="no.address.here"';
            $this->_action[] = '}';
            break;

        case INGO_STORAGE_ACTION_VACATION:
            $days = $params['action-value']['days'];
            $this->_action[] = '{';
            foreach ($params['action-value']['addresses'] as $address) {
                if (!empty($address)) {
                    $this->_action[] = '  FILEDATE=`ls -lcn --time-style=+%s \'vacation.' . $address 
                                       . '\' | awk \'{ print $6 + (' 
                                       . $days * 86400 . ') }\'`';
                    $this->_action[] = '  DATE=`date +%s`';
                    $this->_action[] = '  DUMMY=`test $FILEDATE -le $DATE'
                                       .' && rm \'vacation.' . $address .'\'`';
                    $this->_action[] = '';
                    $this->_action[] = '  :0 Whc: vacation.lock';
                    $this->_action[] = '  * $^To:.*' . $address;
                    $this->_action[] = '  * !^X-Loop: ' . $address;
                    if (count($params['action-value']['excludes']) > 0) {
                        foreach ($params['action-value']['excludes'] 
                                 as $exclude) {
                            if (!empty($exclude)) {
                                $this->_action[] = '  * !^From.*' . $exclude;
                            }
                        }
                    }
                    if ($params['action-value']['ignorelist']) {
                        $this->_action[] = '  * !^FROM_DAEMON';
                    }
                    $reason = $params['action-value']['reason'];
                    $this->_action[] = '  | formail -rD 8192 vacation.' . $address;
                    $this->_action[] = '    :0 ehc';
                    $this->_action[] = '    | (formail -rI"Precedence: junk" \\';
                    $this->_action[] = '       -A"X-Loop: ' . $address . '" \\';
                    $this->_action[] = '       -i"Subject: ' . $params['action-value']['subject'] . '" ; \\';
                    $this->_action[] = '       echo "' . ereg_replace("\r\n","\"; echo \"",$reason) . '" \\';
                    $this->_action[] = '      ) | $SENDMAIL -oi -t';
                    $this->_action[] = '';
                }
            }
            $this->_action[] = '}';
            break;
                    
        case INGO_STORAGE_ACTION_FORWARD:
            $this->_action[] = '{';
            foreach ($params['action-value'] as $address) {
                if (!empty($address)) {
                    $this->_action[] = '  :0 c';
                    $this->_action[] = '  ! ' . $address;
                }
            }
            $this->_action[] = '}';
            break;

        default:
            $this->_valid = false;
            break;
        }
    }

    /**
     * Adds a flag to the recipe.
     *
     * @access public
     *
     * @param string $flag  String of flags to append to the current flags.
     */
    function addFlag($flag)
    {
        $this->_flags .= $flag;
    }

    /**
     * Adds a condition to the recipe.
     *
     * @access public
     *
     * @param optonal array $condition  Array of parameters. Required keys
     *                                  are 'field' and 'value'. 'case' is
     *                                  an optional keys.
     */
    function addCondition($condition = array())
    {
        $flag = (!empty($condition['case'])) ? 'D' : '';
        if (empty($this->_conditions)) {
            $this->addFlag($flag);
        }

        $match = (isset($condition['match'])) ? $condition['match'] : null;
        $string = '* ^' . $condition['field'] . ':';

        switch ($match) {
        case 'regex':
            $string .= ' ' . $condition['value'];
            break;

        case 'begins with':
            $string .= ' ' . quotemeta($condition['value']);
            break;

        case 'ends with':
            $string .= '.*' . quotemeta($condition['value']) . '$';
            break;

        case 'contains':
        default:
            $string .= '.*' . quotemeta($condition['value']);
            break;
        }

        $this->_conditions[] = array('condition' => $string, 'flags' => $flag);
    }

    /**
     * Generates procmail code to represent the recipe.
     *
     * @access public
     *
     * @return string  Procmail code to represent the recipe.
     */
    function generate()
    {
        $nest = 0;
        $prefix = '';
        $text = array();

        if (!$this->_valid) {
            return '';
        }

        $text[] = ':0 ' . $this->_flags;
        foreach ($this->_conditions as $condition) {
            if ($nest > 0) { 
                $text[] = str_repeat('  ', $nest - 1) . '{'; 
                $text[] = str_repeat('  ', $nest) . ':0 ' . $condition['flags'];
                $text[] = str_repeat('  ', $nest) . $condition['condition'];
            } else {
                $text[] = $condition['condition'];
            }
            $nest++;
        }

        if (--$nest > 0) {
            $prefix = str_repeat('  ', $nest);
        }
        foreach ($this->_action as $val) {
            $text[] = $prefix . $val;
        }

        for ($i = $nest; $i > 0; $i--) {
            $text[] = str_repeat('  ', $i - 1) . '}';
        }
        
        if ($this->_disable) {
            $code = '';
            foreach ($text as $val) {
                $comment = new Procmail_Comment($val);
                $code .= $comment->generate() . "\n";
            }
            return $code . "\n";
        } else {
            return implode("\n", $text) . "\n";
        }
    }

    /**
     * Returns a procmail-ready mailbox path, converting IMAP folder
     * pathname conventions as necessary.
     *
     * @access public
     *
     * @param string $folder  The IMAP folder name.
     *
     * @return string  The procmail mailbox path.
     */
    function procmailPath($folder)
    {
        /* NOTE: '$DEFAULT' here is a literal, not a PHP variable. */
        if (isset($this->_params) &&
            ($this->_params['path_style'] == 'maildir')) {
            if (empty($folder) || ($folder == 'INBOX')) {
                return '$DEFAULT';
            }
            if (substr($folder, 0, 6) == 'INBOX.') {
                $folder = substr($folder, 6);
            }
            return '"$DEFAULT/.' . $folder . '/"';
        } else {
            if (empty($folder) || ($folder == 'INBOX')) {
                return '$DEFAULT';
            }
            return str_replace(' ', '\ ', $folder);
        }
    }

}

/**
 * The Procmail_Variable:: class represents a Procmail variable.
 *
 * @author  Michael Slusarz <slusarz@bigworm.colorado.edu>
 * @since   Ingo 1.0
 * @package Ingo
 */
class Procmail_Variable {

    var $_name;
    var $_value;

    /**
     * Constructs a new procmail variable.
     *
     * @access public
     *
     * @param optional array $params  Array of parameters. Expected fields are
     *                                'name' and 'value'.
     */
    function Procmail_Variable($params = array())
    {
        $this->_name = $params['name'];
        $this->_value = $params['value'];
    }

    /**
     * Generates procmail code to represent the variable.
     *
     * @access public
     *
     * @return string  Procmail code to represent the variable.
     */
    function generate()
    {
        return $this->_name . '=' . $this->_value . "\n";
    }

}
