<?php
/**
 * $Horde: forwards/lib/Driver/qmail.php,v 1.7 2003/09/20 20:40:44 chuck Exp $
 *
 * Copyright 2001-2003 Eric Rostetter <eric.rostetter@physics.utexas.edu>
 *
 * See the enclosed file LICENSE for license information (BSD). If you
 * did not receive this file, see http://www.horde.org/licenses/bsdl.php.
 *
 * Forwards_Driver_qmail:: implements the Forwards_Driver API for ftp driven
 * qmail mail servers.  
 *
 * @author  Eric Rostetter <eric.rostetter@physics.utexas.edu>
 * @version $Revision: 1.7 $ 
 * @since   Forwards 2.2
 * @package forwards
 */
class Forwards_Driver_qmail extends Forwards_Driver {

    /** The FTP stream we open via the VFS class */
    var $_vfs;

    /** The error string returned to the user if an error occurs. */
    var $err_str;

    /** Hash containing configuration data. */
    var $params;

    /**
     * Constructs a new ftp qmail Forwards_Driver object.
     *
     * @param array  $params    A hash containing connection parameters.
     */
    function Forwards_Driver_qmail($params = array())
    {
        $this->params = $params;
    }

    /**
     * Check if the realm has a specific configuration.  If not, try to fall
     * back on the default configuration.  If still not a valid configuration
     * then exit with an error.
     *
     * @param string    $realm      The realm of the user, or "default" if none.
     *                              Note: passed by reference so we can change
     *                              its value!
     */
    function check_config(&$realm)
    {
        // If no realm passed in, or no host config for the realm passed in,
        // then we fall back to the default realm

        if (empty($realm) || empty($this->params[$realm]['host'])) {
            $realm = 'default';
        }

        // If still no host/port, then we have a misconfigured module
        if (empty($this->params[$realm]['host']) ||
            empty($this->params[$realm]['port']) ) {
            $this->err_str = _("The module is not properly configured!");
            return false;
        }
        return true;
    }

    /**
     * Begins forwarding of mail for a user.
     *
     * @param string    $user       The username to enable forwarding for.
     * @param string    $realm      The realm of the user, or "default" if none.
     * @param string    $target     The email address that mail should be
     *                              forwarded to.
     * @param optional boolean $keeplocal A flag that, when true, causes a copy of
     *                                    forwarded email to be kept in the local
     *                                    mailbox.
     *
     * @return boolean  Returns true on success, false on error.
     */
    function enableForwarding($user, $realm = 'default', $pass, $where,
                              $metoo = false)
    {
        // Make sure the configuration file is correct
        if (!$this->check_config($realm)) {
            return false;
        }

        // Build the ftp array to pass to VFS
        $_args = array('hostspec' => $this->params[$realm]['host'],
                       'port' => $this->params[$realm]['port'],
                       'username' => $user,
                       'password' => $pass);

        // Create the VFS ftp driver.
        require_once HORDE_LIBS . 'VFS.php';
        $_vfs = &VFS::singleton('ftp', $_args);
        $_vfs->setParams($_args);

        // Try to login with the username/password, no realm. This
        // isn't really needed, but allows for a better error message.
        $status = $_vfs->checkCredentials();
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            $this->err_str .= '  ' .  _("Check your username and password");
            return false;
        }

        // Create the forwarding information.
        $address = '&' . $where;
        if ($metoo == 'on') {
            $address .= "\n./Maildir/";
        }

        // Set the forward
        $status = $_vfs->writeData('', '.qmail', $address);
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            return false;
        }

        // Try to change the permissions, but ignore any errors
        $_vfs->changePermissions('', '.qmail', '0600');

        $_vfs->_disconnect();
        return true;
    }

    /**
     * Stops forwarding of mail for a user.
     *
     * @param string    $user       The username of the user to disable forwarding.
     * @param string    $realm      The realm of the user.
     * @param string    $pass       The password of the user.
     *
     * @return boolean  Returns true on success, false on error.
     */
    function disableForwarding($user, $realm = 'default', $pass)
    {
        if (!$this->check_config($realm)) {
            return false;
        }

        $_args = array('hostspec' => $this->params[$realm]['host'],
                       'port' => $this->params[$realm]['port'],
                       'username' => $user,
                       'password' => $pass);

        require_once HORDE_LIBS . 'VFS.php';
        $_vfs = &VFS::singleton('ftp', $_args);
        $_vfs->setParams($_args);

        // Try to login with the username/password, no realm.
        $status = $_vfs->checkCredentials();
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            $this->err_str .= '  ' .  _("Check your username and password");
            return false;
        }

        $status = $_vfs->deleteFile('', '.qmail');
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            $this->err_str .= '  ' .  _("Maybe you didn't have a forward enabled?");
            return false;
        }
        $_vfs->_disconnect();
        return true;
    }

    /**
     * Retrieves current target of mail redirection
     *
     * @param string    $user       The username of the user to get forward of.
     * @param string    $realm      The realm of the user.
     *
     * @return mixed    A string of current forwarding mail address, or false.
     */
    function currentTarget($user, $realm = 'default', $pass)
    {
        // Make sure the configuration file is correct.
        if (!$this->check_config($realm)) {
            return false;
        }

        // Build the ftp array to pass to VFS.
        $_args = array('hostspec' => $this->params[$realm]['host'],
                       'port' => $this->params[$realm]['port'],
                       'username' => $user,
                       'password' => $pass);

        // Create the VFS ftp driver.
        require_once HORDE_LIBS . 'VFS.php';
        $_vfs = &VFS::singleton('ftp', $_args);
        $_vfs->setParams($_args);

        // Try to login with the username/password, no realm
        $status = $_vfs->checkCredentials();
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            $this->err_str .= '  ' .  _("Check your username and password");
            return false;
        }

        $status = $_vfs->read('', '.qmail');
        if (is_a($status, 'PEAR_Error')) {
            $this->err_str = $status->getMessage();
            return false;
        }
        return $status;
    }

    /**
     * Retrieves current state of mail redirection
     *
     * This function is implemented poorly, and should be rewritten.
     *
     * @param string    $user       The username to check forwarding for.
     * @param string    $realm      The realm of the user.
     * @return boolean  Returns true/false based on if forwarding is enabled.
     */
    function isEnabledForwarding($user, $realm, $password)
    {
        return $this->currentTarget($user, $realm, $password) != false;
    }

}
