<?php   if(!defined('DEDEMEMBER')) exit("dedecms");
/**
 * 密碼函數
 * 
 * @version        $Id: inc_pwd_functions.php 1 15:18 2010年7月9日Z tianya $
 * @package        DedeCMS.Member
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */

/**
 *  驗證碼生成函數
 *
 * @param     int  $length  需要生成的長度
 * @param     int  $numeric  是否為數字
 * @return    string
 */
function random($length, $numeric = 0)
{
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric)
    {
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    }
    else
    {
        $hash = '';
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

/**
 *  郵件發送函數
 *
 * @param     string  $email  E-mail地址
 * @param     string  $mailtitle  E-mail標題
 * @param     string  $mailbody  E-mail內容
 * @param     string  $headers 頭信息
 * @return    void
 */
function sendmail($email, $mailtitle, $mailbody, $headers)
{
    global $cfg_sendmail_bysmtp, $cfg_smtp_server, $cfg_smtp_port, $cfg_smtp_usermail, $cfg_smtp_user, $cfg_smtp_password, $cfg_adminemail;
    if($cfg_sendmail_bysmtp == 'Y')
    {
        $mailtype = 'TXT';
        require_once(DEDEINC.'/mail.class.php');
        $smtp = new smtp($cfg_smtp_server,$cfg_smtp_port,true,$cfg_smtp_usermail,$cfg_smtp_password);
        $smtp->debug = false;
        $smtp->sendmail($email,$cfg_webname,$cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
    } else {
        @mail($email, $mailtitle, $mailbody, $headers);
    }
}

/**
 *  發送郵件；type為INSERT新建驗證碼，UPDATE修改驗證碼；
 *
 * @param     int  $mid  會員ID
 * @param     int  $userid  用戶ID
 * @param     string  $mailto  發送到
 * @param     string  $type  類型
 * @param     string  $send  發送到
 * @return    string
 */
function newmail($mid, $userid, $mailto, $type, $send)
{
    global $db,$cfg_adminemail,$cfg_webname,$cfg_basehost,$cfg_memberurl;
    $mailtime = time();
    $randval = random(8);
    $mailtitle = $cfg_webname.":密碼修改";
    $mailto = $mailto;
    $headers = "From: ".$cfg_adminemail."\r\nReply-To: $cfg_adminemail";
    $mailbody = "親愛的".$userid."：\r\n您好！感謝您使用".$cfg_webname."網。\r\n".$cfg_webname."應您的要求，重新設置密碼：（註：如果您沒有提出申請，請檢查您的信息是否洩漏。）\r\n本次臨時登陸密碼為：".$randval." 請於三天內登陸下面網址確認修改。\r\n".$cfg_basehost.$cfg_memberurl."/resetpassword.php?dopost=getpasswd&id=".$mid;
    if($type == 'INSERT')
    {
        $key = md5($randval);
        $sql = "INSERT INTO `#@__pwd_tmp` (`mid` ,`membername` ,`pwd` ,`mailtime`)VALUES ('$mid', '$userid',  '$key', '$mailtime');";
        if($db->ExecuteNoneQuery($sql))
        {
            if($send == 'Y')
            {
                sendmail($mailto,$mailtitle,$mailbody,$headers);
                return ShowMsg('EMAIL修改驗證碼已經發送到原來的郵箱請查收', 'login.php','','5000');
            } else if ($send == 'N')
            {
                return ShowMsg('稍後跳轉到修改頁', $cfg_basehost.$cfg_memberurl."/resetpassword.php?dopost=getpasswd&amp;id=".$mid."&amp;key=".$randval);
            }
        }
        else
        {
            return ShowMsg('對不起修改失敗，請聯繫管理員', 'login.php');
        }
    }
    elseif($type == 'UPDATE')
    {
        $key = md5($randval);
        $sql = "UPDATE `#@__pwd_tmp` SET `pwd` = '$key',mailtime = '$mailtime'  WHERE `mid` ='$mid';";
        if($db->ExecuteNoneQuery($sql))
        {
            if($send == 'Y')
            {
                sendmail($mailto,$mailtitle,$mailbody,$headers);
                ShowMsg('EMAIL修改驗證碼已經發送到原來的郵箱請查收', 'login.php');
            }
            elseif($send == 'N')
            {
                return ShowMsg('稍後跳轉到修改頁', $cfg_basehost.$cfg_memberurl."/resetpassword.php?dopost=getpasswd&amp;id=".$mid."&amp;key=".$randval);
            }
        }
        else
        {
            ShowMsg('對不起修改失敗，請與管理員聯繫', 'login.php');
        }
    }
}

/**
 *  查詢會員信息mail用戶輸入郵箱地址；userid用戶名
 *
 * @param     string  $mail  郵件
 * @param     string  $userid  用戶ID
 * @return    string
 */
function member($mail, $userid)
{
    global $db;
    $sql = "SELECT mid,email,safequestion FROM #@__member WHERE email='$mail' AND userid = '$userid'";
    $row = $db->GetOne($sql);
    if(!is_array($row)) return ShowMsg("對不起，用戶ID輸入錯誤！","-1");
    else return $row;
}

/**
 *  查詢是否發送過驗證碼
 *
 * @param     string  $mid  會員ID
 * @param     string  $userid  用戶名稱
 * @param     string  $mailto  發送郵件地址
 * @param     string  $send  為Y發送郵件,為N不發送郵件默認為Y
 * @return    string
 */
function sn($mid,$userid,$mailto, $send = 'Y')
{
    global $db;
    $tptim= (60*10);
    $dtime = time();
    $sql = "SELECT * FROM #@__pwd_tmp WHERE mid = '$mid'";
    $row = $db->GetOne($sql);
    if(!is_array($row))
    {
        //發送新郵件；
        newmail($mid,$userid,$mailto,'INSERT',$send);
    }
    //10分鐘後可以再次發送新驗證碼；
    elseif($dtime - $tptim > $row['mailtime'])
    {
        newmail($mid,$userid,$mailto,'UPDATE',$send);
    }
    //重新發送新的驗證碼確認郵件；
    else
    {
        return ShowMsg('對不起，請10分鐘後再重新申請', 'login.php');
    }
}