Location: PHPKode > projects > phlyMail Lite > phlymail/frontend/mod.auth.php
<?php
/**
 * mod.auth.php -> phlyMail 3.7.0+ authentication module
 * @package phlyMail Nahariya 4.0+ Default Branch
 * @copyright 2002-2010 phlyLabs, Berlin (http://phlylabs.de)
 * @version 4.2.0mod1 2010-11-08
 */
// Only valid within phlyMail
if (!defined('_IN_PHM_')) die();

// Which PHP version do we use?
if (!version_compare(phpversion(), '5.2.0', '>=')) {
    header('Content-Type: text/plain; charset=utf-8');
    die('phlyMail requires PHP 5.2.0 or higher, you are running '.phpversion().'.'.LF.'Please upgrade your PHP');
}

// Init vars
$WPloggedin = 0;
$still_blocked = 0;
// Is the system offline?
$maintained = (!isset($_PM_['core']['online_status']) || !$_PM_['core']['online_status']) ? 1 : 0;
$unusable = 0;
$special = isset($_REQUEST['special']) ? $_REQUEST['special'] : false;
$countonfail = (isset($_PM_['auth']['countonfail']) && $_PM_['auth']['countonfail']) ? $_PM_['auth']['countonfail'] : false;
$waitonfail = (isset($_PM_['auth']['waitonfail']) && $_PM_['auth']['waitonfail']) ? $_PM_['auth']['waitonfail'] : 5;
$lockonfail = (isset($_PM_['auth']['lockonfail']) && $_PM_['auth']['lockonfail']) ? $_PM_['auth']['lockonfail'] : 10;
// Support on demand OTP
if (isset($_REQUEST['give_otp'])) {
    header('Content-Type: application/json; charset=utf-8');
    if (1 == $maintained) {
        echo '{"error":"'.addcslashes($WP_msg['currentlyoffline'], '"').'"}';
        exit;
    }
    $_SESSION['otp'] = md5($_SERVER['REMOTE_ADDR']).time().getmypid();
    echo '{"otp":"'.$_SESSION['otp'].'"}';
    exit;
}

if (isset($_REQUEST['user']) && isset($_REQUEST['pass'])) {
    list ($uid, $realpass) = $DB->authenticate($_REQUEST['user']);

    if ($DB->get_usercount() > 1) $uid = false;
    $failure = $DB->get_usrfail($uid);
    // Automatisches Verblassen von Fehleingaben
    if ($failure['fail_count'] < $countonfail) {
        if ($failure['fail_time'] < (date('U') - 600)) $DB->reset_usrfail($uid);
    } else {
        if ($failure['fail_time'] < (date('U') - ($lockonfail * 60))) $DB->reset_usrfail($uid);
        else $still_blocked = 1;
    }
    if (isset($_REQUEST['secure']) && $_REQUEST['secure']) {
        $soll = md5($realpass.$_SESSION['otp']);
        if ($soll != $_REQUEST['secure']) {
            if ($still_blocked != 1) $DB->set_usrfail($uid);
            $uid = false;
        }
        unset($_SESSION['otp']);
    } elseif ($_REQUEST['pass']) {
        if (md5($_REQUEST['pass']) != $realpass) {
            if ($still_blocked != 1) $DB->set_usrfail($uid);
            $uid = false;
        }
    } else {
        $uid = false;
    }

    // --- Custom Logging of logins and login attempts
    if (isset($_PM_['logging']['log_sysauth']) && $_PM_['logging']['log_sysauth']) {
        $logpath = $GLOBALS['_PM_']['path']['logging'].'/sysauth/'.preg_replace('!\%(\w)!e', 'date("\1")', $GLOBALS['_PM_']['logging']['basename']);
        if (basics::create_dirtree(dirname($logpath))) {
            $logstring = date('Y-m-d H:i:s').' ';
            if ($maintained == 1) $logstring .= '9 '.$_REQUEST['user'];
            elseif ($unusable == 1) $logstring .= '2 '.$_REQUEST['user'];
            elseif ($still_blocked == 1) $logstring .= '3 '.$_REQUEST['user'];
            elseif ($uid != false) $logstring .= '1 '.$_REQUEST['user'];
            else $logstring .= '0 "'.$_REQUEST['user'].'" '.getenv('REMOTE_ADDR');
            file_put_contents($logpath, $logstring.LF, FILE_APPEND);
        }
    }
    // ---
    if (1 == $maintained) $error = $WP_msg['currentlyoffline'];
    elseif (1 == $unusable) $error = $WP_msg['stilldisabled'];
    elseif ($still_blocked == 1) $error = $WP_msg['stillblocked'];
    elseif ($uid != false) {
        $_SESSION['phM_uid'] = $uid;
        $_SESSION['phM_username'] = $_REQUEST['user'];
        // Has groups managemnt, so read in assigend groups
        if (isset($DB->features['groups']) && $DB->features['groups']) {
            $_SESSION['phM_groups'] = $DB->get_usergrouplist($uid);
        } else {
            $_SESSION['phM_groups'] = array(0);
        }
        $_SESSION['phM_privs']['all'] = true;
        $WPloggedin = 1;
        $DB->set_logintime($_SESSION['phM_uid']);
        $urladd = '';
        if (isset($_REQUEST['orig_url'])) {
            $urladd = parse_url(urldecode($_REQUEST['orig_url']));
            $urladd = (isset($urladd['query'])) ? $urladd['query'].'&' : '';
        }
        // Session cookie
        if (!isset($_PM_['auth']['session_cookie']) || $_PM_['auth']['session_cookie']) {
            $_SESSION['phM_cookie'] = md5(uniqid());
            setcookie('phlyMail_Session', $_SESSION['phM_cookie']);
        }
        header('Location: '.PHP_SELF.'?'.$urladd.give_passthrough(1));
        exit();
    } else {
        if (!isset($error) || !$error) $error = $WP_msg['wrongauth'];
        sleep($waitonfail);
    }
}

if ($WPloggedin != 1) {
    $action = 'auth';
    $_PM_['temp']['load_tpl_auth'] = 'do.it!';
    if ('lost_pw' == $special) {
        if (isset($_REQUEST['user']) && $_REQUEST['user']) {
            list ($uid, $realpass, $email) = $DB->authenticate($_REQUEST['user']);
            if ($DB->get_usercount() > 1) $uid = false;
            if (!$uid) {
                $error = $WP_msg['notknown'];
            } else {
                $usrdata = $DB->get_usrdata($uid);
                if (!$usrdata['email'] || !strstr($usrdata['email'], '@')) {
                    $uid = false;
                    $error = $WP_msg['AuthLostNoEmail'];
                }
            }
            if (isset($uid) && $uid) {
                $newpass = mk_secure_password();
                $DB->upd_user(array('uid' => $uid, 'email' => $usrdata['email'], 'username' => $_REQUEST['user'], 'password' => $newpass));
                $DB->reset_usrfail($uid);
                auth_mail_password(array('subject' => $WP_msg['AuthLostMailSubj'], 'body' => $WP_msg['AuthLostMailBody'], 'password' => $newpass, 'email' => $email));
                $tpl = new fxl_cached_template($_PM_['path']['frontend'].'/templates/auth.forgotten.tpl', $_PM_['path']['tplcache'].'auth.forgotten.tpl');
                $tpl->fill_block('okay', array
                        ('msg_okay' => $WP_msg['AuthPWSent']
                        ,'msg_back' => $WP_msg['backLI']
                        ,'login' => htmlspecialchars(PHP_SELF.'?'.give_passthrough())
                        ));
                return;
            }
        }
        $tpl = new fxl_cached_template($_PM_['path']['frontend'].'/templates/auth.forgotten.tpl', $_PM_['path']['tplcache'].'auth.forgotten.tpl');
        $t_q = $tpl->get_block('query');
        $t_q->assign(array
                ('PHP_SELF' => htmlspecialchars(PHP_SELF.'?whattodo=check&special=lost_pw&'.give_passthrough())
                ,'msg_popuser' => $WP_msg['popuser']
                ,'msg_lost_pw' => $WP_msg['AuthLostPW']
                ,'msg_enter' => $WP_msg['AuthLostEnterName']
                ,'msg_send' => $WP_msg['AuthLostSend']
                ,'user' => isset($_REQUEST['user']) ? phm_entities($_REQUEST['user']) : ''
                ));
        if (isset($error) && $error) $t_q->fill_block('error', 'error', $error);
        $tpl->assign('query', $t_q);
        return;
    }
    if (!$special) {
        //
        // Admin has defined a failed login URI
        //
        if (isset($_PM_['core']['failed_redir_uri']) && $_PM_['core']['failed_redir_uri']
                && isset($error) && $error) {
            $url = preg_replace('!\r|\n|\t!', '', $_PM_['core']['failed_redir_uri']);
            if (!preg_match('!^http(s)?\://!', $url)) $url = 'http://'.$url;
            $url .= (false !== strstr($url, '?') ? '&' : '?').'error='.urlencode($error);
            header('Location: '.$url);
            exit;
        }

        $tpl = new fxl_cached_template($_PM_['path']['frontend'].'/templates/auth.login.tpl', $_PM_['path']['tplcache'].'auth.login.tpl');
        $tpl->assign(array
            ('PHP_SELF' => htmlspecialchars(PHP_SELF.'?'.give_passthrough())
            ,'msg_authenticate' => $WP_msg['authenticate']
            ,'msg_popuser' => $WP_msg['popuser']
            ,'msg_poppass' => $WP_msg['poppass']
            ,'msg_login' => $WP_msg['login']
            ,'msg_lost_pw' => $WP_msg['AuthLostPW']
            ,'user' => isset($_REQUEST['user']) ? phm_entities($_REQUEST['user']) : ''
            ));
        if (isset($error) && $error) $tpl->fill_block('error', 'error', $error);
    }
}

function mk_secure_password()
{
    $charmap = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!_.+,:;$';
    $maxchar = strlen($charmap)-1;
    $pwd = '';
    for ($i = 0; $i < 8; ++$i) $pwd .= $charmap{(rand(0, $maxchar))};
    return $pwd;
}

function auth_mail_password($input)
{
    global $_PM_; // Since we need it virtuallay everywhere in this function
    require_once($_PM_['path']['lib'].'/pop3.inc.php');
    require_once($_PM_['path']['lib'].'/phm_streaming_smtp.php');
    require_once($_PM_['path']['lib'].'/phm_streaming_sendmail.php');
    require_once($_PM_['path']['lib'].'/phm_streaming_mailparser.php');
    require_once($_PM_['path']['lib'].'/message.encode.php');
    require_once($_PM_['path']['lib'].'/idna_convert.class.php');

    $providername = (isset($_PM_['core']['provider_name']) && $_PM_['core']['provider_name'] != '') ? $_PM_['core']['provider_name'] : 'phlyMail';
    $body = str_replace('$2', $input['password'], str_replace('$1', $providername, phm_stripslashes($input['body'])));
    $from = isset($_PM_['core']['systememail']) && $_PM_['core']['systememail'] ? $_PM_['core']['systememail'] : $input['email'];
    $to = $input['email'];
    $subject = str_replace('$1', $providername, phm_stripslashes($input['subject']));

    if (preg_match('![\x80-\xff]!', $body)) {
        $bodylines = explode(LF, $body);
        $body = '';
        foreach ($bodylines as $value) $body .= phm_quoted_printable_encode($value.CRLF);
        $body_qp = 'true';
    }
    $header = create_messageheader(array('from' => $from, 'to' => $to, 'subject' => $subject));
    $to = mailparser::parse_email_address($to);
    if ($_PM_['core']['send_method'] == 'sendmail') {
        $header = str_replace(CRLF, LF, $header);
        $body = str_replace(CRLF, LF, $body);
        $LE = LF;
        $sendmail = preg_replace('!\ \-t!', '', $_PM_['core']['sendmail']).' -t';
        $sm = new phm_streaming_sendmail($sendmail);
        if ($moep = $sm->get_last_error() && $moep) return;
    }
    if ($_PM_['core']['send_method'] == 'smtp') {
        if (!isset($_PM_['core']['fix_smtp_host']) || !$_PM_['core']['fix_smtp_host']) return;
        $LE = CRLF;
        $from = mailparser::parse_email_address($from);
        $smtp_host = $_PM_['core']['fix_smtp_host'];
        $smtp_port = ($_PM_['core']['fix_smtp_port']) ? $_PM_['core']['fix_smtp_port'] : 25;
        $smtp_user = (isset($_PM_['core']['fix_smtp_user'])) ? $_PM_['core']['fix_smtp_user'] : false;
        $smtp_pass = (isset($_PM_['core']['fix_smtp_pass'])) ? $_PM_['core']['fix_smtp_pass'] : false;
        $sm = new phm_streaming_smtp($smtp_host, $smtp_port, $smtp_user, $smtp_pass);
        $sm->open_server($from[0], $to[0]);
    }
    if ($sm) {
        $sm->put_data_to_stream($header);
        if (isset($body_qp) && 'true' == $body_qp) {
            $sm->put_data_to_stream('MIME-Version: 1.0'.$LE);
            $sm->put_data_to_stream('Content-Type: text/plain; charset=utf-8'.$LE);
            $sm->put_data_to_stream('Content-Transfer-Encoding: quoted-printable'.$LE);
        }
        $sm->put_data_to_stream($LE);
        $sm->put_data_to_stream($body);
        $sm->finish_transfer();
        $sm->close();
    }
}
?>
Return current item: phlyMail Lite