<%@ Language="VBSCRIPT" codepage="936" %>
<%option explicit%>
<!--#include file="../Conn.asp"-->
<!--#include file="../Task/TaskConfig.asp"-->
<!--#include file="../HSK_Cls/HSK.MemberCls.asp"-->
<!--#include file="../HSK_Cls/HSK.EscapeCls.asp"-->
<!--#include file="md5.asp"-->
<%
'============================================
'软件名: 咪咪网络手机短信发送通用接口
'最后更新日期：2012-8-13
'官方网站：http://www.mm2006.com
'============================================
Response.cachecontrol = "no-cache"
Response.Addheader "pragma", "no-cache"
Response.expires = -1
Response.expiresAbsolute = Now - 1
Response.Addheader "Content-Type", "text/html; charset=gb2312"
Response.Charset = "gb2312"

Dim KS: Set KS = New PublicCls
Dim KSUser: Set KSUser = New UserCls
Dim SMS_Sign: SMS_Sign = "【" & KS.Setting(0) & "】"      '短信尾加上平台名称或公司签名，默认调用后台设置的网站名称
Dim Action: Action = KS.S("Action")
Dim SendUserName, AcceptUserName: AcceptUserName = Left(Trim(KS.DelSql(UnEscape(Request("UserName")))), 50)
Dim Mobile: Mobile = Trim(KS.DelSql(KS.S("Mobile")))
Dim Content: Content = Trim(KS.DelSql(UnEscape(Request("Content"))))
Dim SessionFlag: SessionFlag = KS.S("Flag")               '发送来源页面标志
Dim SessionNum: SessionNum = KS.S("N")                    '相同操作允许发送短信次数
Dim SecurityCode: SecurityCode = KS.S("C")                '安全密码
Dim SecurityCodeCheck: SecurityCodeCheck = KS.S("CC")     '安全密码是否判断验证 1时验证
Dim VerifyCode: VerifyCode = KS.S("V")                    '验证码
Dim VerifyCodeCheck: VerifyCodeCheck = KS.S("VC")         '验证码是否判断验证 1时验证
Dim MobileCheck: MobileCheck = KS.S("MC")                 '是否检查手机号已存在，用于会员首次认证 1时判断
Dim IsMoney: IsMoney = KS.S("M")                          '参数值为1时发短信需收费 0或空免费发送
Dim MoneyEnforce: MoneyEnforce = KS.S("ME")               '当发短信需收费时是否强行扣费，即余额为0或低于0时可扣为负数 1时强制扣费
Dim Money: Money = SMS_Price                              '手机短信价格变量
Dim rd: rd = KS.MakeRandom(6)                             '产生6位随机数字验证码
Dim RefererUrl: RefererUrl = LCase(Request.ServerVariables("HTTP_REFERER"))
Dim RefererPage: RefererPage = "GetPassword.asp"          '不需要登录调用发短信来源页面，多个用|号隔开
Dim SplitRefererPage: SplitRefererPage = Split(RefererPage, "|")
Dim i, DoRefererPage: DoRefererPage = False
If KS.IsNul(SessionNum) Then SessionNum = 3               '默认空值时各项功能页面限制最多发送3次，可修改此值增加次数

If SMS_Send_Enabled <> 1 Then
    Die "err|抱歉！发送手机短信功能暂时关闭，具体恢复时间请留意平台最新公告消息。"
End If

If KS.IsNul(RefererUrl) Or KS.CheckOuterUrl() Then
    Die "err|非法提交！"
Else
   RefererUrl = Left(RefererUrl, InStr(RefererUrl, ".asp") + 3)
   For i = 0 To UBound(SplitRefererPage)
       If InStr(RefererUrl, LCase(SplitRefererPage(i))) > 0 Then
           DoRefererPage = True
           Exit For
       End If
   Next
End If
If DoRefererPage Then
    If KS.IsNul(AcceptUserName) Then Die "err|抱歉！用户名不能为空！"
    SendUserName = AcceptUserName
Else
    If CBool(KSUser.UserLoginChecked) = False Then
        Die "err|请登录再操作！"
    Else
        If KS.IsNul(AcceptUserName) Then AcceptUserName = KSUser.UserName
        SendUserName = KSUser.UserName
    End If
End If

If KS.ChkClng(VerifyCodeCheck) = 1 Then
    If KS.IsNul(VerifyCode) Then Die "err|请您先输入验证码！"
End If
If Not KS.IsNul(VerifyCode) Then
    If Trim(VerifyCode) <> Session("Verifycode") Then Die "err|您输入的验证码不对！"
End If

If KS.ChkClng(SecurityCodeCheck) = 1 Then
    If KS.IsNul(SecurityCode) Then Die "err|请您先输入安全密码！"
End If
If Not KS.IsNul(SecurityCode) Then
    If Md5(Trim(SecurityCode), 16) <> KSUser.GetUserInfo("KS_SecurityCode") Then Die "err|您输入的安全密码不对！"
End If

If KS.IsNul(Content) Then Content = SMS_Content
Content = Replace(Content, "{$RndNum}", rd) & SMS_Sign
If KS.IsNul(Application("SMS_ReplaceKeyWords")) Then
    Application("SMS_ReplaceKeyWords") = KS.ReadFromFile("短信关键字替换#.txt")
End If
If Not KS.IsNul(Application("SMS_ReplaceKeyWords")) Then
    Dim SMS_ReplaceKeyWords, SMS_ReplaceKeyWords_Row
    SMS_ReplaceKeyWords = Split(Application("SMS_ReplaceKeyWords"), vbCrLf)
    For i = 0 To UBound(SMS_ReplaceKeyWords)
        If InStr(SMS_ReplaceKeyWords(i), "=") > 0 Then
            SMS_ReplaceKeyWords_Row = Split(SMS_ReplaceKeyWords(i), "=")
            If Not KS.IsNul(SMS_ReplaceKeyWords_Row(0)) And InStr(Content, SMS_ReplaceKeyWords_Row(0)) > 0 Then
                Content = Replace(Content, SMS_ReplaceKeyWords_Row(0), SMS_ReplaceKeyWords_Row(1))
            End If
        End If
    Next
End If
If KS.IsNul(Application("SMS_KeyWords")) Then
    Application("SMS_KeyWords") = KS.ReadFromFile("短信关键字过滤#.txt")
End If
If Not KS.IsNul(Application("SMS_KeyWords")) Then
    Dim SMS_KeyWords: SMS_KeyWords = Split(Application("SMS_KeyWords"), vbCrLf)
    For i = 0 To UBound(SMS_KeyWords)
        If Not KS.IsNul(SMS_KeyWords(i)) And InStr(Content, SMS_KeyWords(i)) > 0 Then
            Content = Replace(Content, SMS_KeyWords(i), "***")
        End If
    Next
End If

If KS.IsNul(Mobile) And Not KS.IsNul(AcceptUserName) Then
    Dim UN: Set UN = Conn.Execute("Select Top 1 Mobile From KS_User Where UserName ='" & AcceptUserName & "'")
    If Not UN.EOF Then
        Mobile = UN("Mobile")
    Else
        Die "err|抱歉！系统不存在该用户！"
    End If
    Set UN = Nothing
End If

If KS.ChkClng(MobileCheck) = 1 Then
    If KS.IsNul(Mobile) Or Len(Mobile) < 11 Then
        Die "err|抱歉！手机号码有误，请核实后再试！"
    ElseIf Not Conn.Execute("Select Top 1 UserID From KS_User Where Mobile='" & Mobile & "' And KS_IDAuthentication=1").EOF Then
        Die "err|抱歉！该手机号已被其他账号认证过了，请您更换一个再试!"
    End If
End If

Select Case Action
    Case "SendSMS"
        If InStr(Mobile, ",") > 0 Then
            Mobile = Replace(Mobile, " ", "")
            Money = Round(Money * (UBound(Split(Mobile, ",")) + 1), 3)
        End If
        If KS.ChkClng(IsMoney) = 1 And KS.IsNul(MoneyEnforce) Then
            Dim UserMoney
            If DoRefererPage Then
                UserMoney = Conn.Execute("Select Top 1 Money From KS_User Where UserName='" & SendUserName & "'")(0)
            Else
                UserMoney = KSUser.GetUserInfo("Money")
            End If
            If Round(UserMoney, 3) < Round(Money, 3) Then Die "err|您账号的余额不足支付本次短信费用，请充值后再试，谢谢！"
        End If
        Call DoSendSMS()
End Select

Call Die("")


Sub DoSendSMS()
    Select Case Sending()
        Case 0
            If KS.reTest(Content, "\d{6}") = True Then
                Conn.Execute ("UPDate KS_User Set CheckNum='" & rd & "' Where UserName='" & SendUserName & "'")
            End If
            If KS.ChkClng(IsMoney) = 1 Then
                Dim RealName
                If DoRefererPage Then
                    RealName = Conn.Execute("Select Top 1 RealName From KS_User Where UserName='" & SendUserName & "'")(0)
                Else
                    RealName = KSUser.GetUserInfo("RealName")
                End If
                Call KS.MoneyInOrOut(SendUserName, RealName, Money, 4, 2, Now, 0, "系统", "发送手机短信", 0, 0, 1)
                Dim RSObj: Set RSObj = Server.CreateObject("Adodb.Recordset")
                Dim Sql: Sql = "Select Top 1 * From Log_SMS"
                RSObj.Open Sql, Conn, 1, 3
                RSObj.AddNew
                RSObj("OrderID") = GetNumString()
                RSObj("UserName") = SendUserName
                RSObj("Mobile") = Mobile
                RSObj("Content") = KS.HTMLEncode(Content)
                RSObj("PayMoney") = Money
                RSObj("SendType") = 0
                RSObj("AddDate") = Now()
                RSObj("Status") = 0
                RSObj("UserIP") = KS.GetIP()
                RSObj.Update
                RSObj.Close
                Set RSObj = Nothing
            End If
            Session("Mobile") = Mobile
            Die "ok|恭喜！手机短信已发送成功！"
        Case -1
            Die "err|手机号码为空或有误，如未通过手机短信认证，请先认证绑定后再来操作！"
        Case -2
            Die "err|发送接口设置有误，请反馈给客服或管理员检查处理，谢谢！"
        Case -3
            Die "err|抱歉！发送失败！-1"
        Case -4
            Die "err|抱歉！发送失败！-2"
        Case -5
            Die "err|抱歉！发送失败！-3"
        Case -6
            If InStr(Content, "验证码") > 0 Then
                Die "err|获取验证码不能超过" & SessionNum & "次，请耐心等多一会，如果长时间没收到短信，请与客服联系，谢谢！"
            Else
                Die "err|抱歉！本项功能限制发送短信" & SessionNum & "次！"
            End If
        Case Else
            Die "err|发送失败，未知原因！"
    End Select
End Sub

'函数名：Sending
'作用：发送手机短信
'返回值：数字代码
Function Sending()
    Dim sUserName    '短信接口的用户名
    Dim sKey         '短信接口的密码(或密钥)
    Dim sMobile      '接收短信的手机号。可以同时向多人发送短信。可使用逗号分隔多个信息
    Dim sContent     '短信内容
    Dim Url          '短信接口API地址
    Dim Http         '访问返回的HTTP对象
    Dim sFlag, sNum  '记录短信发送页面功能标记会话来限制发送次数
    
    sUserName = SMS_UserName
    sKey = SMS_Key
    sMobile = Mobile
    sContent = Content
    sFlag = SessionFlag
    sNum = SessionNum
    If KS.IsNul(sMobile) Or Len(sMobile) < 11 Then
        Sending = -1
        Exit Function
    End If
    If SMS_ServicePro = 1 Then  '吉信通公司 API接口
        Url = "http://service.winic.org:8009/sys_port/gateway/?id=" & sUserName & "&pwd=" & sKey & "&to=" & sMobile & "&content=" & Left(sContent, 70) & "&time="
    ElseIf SMS_ServicePro = 2 Then  '深圳市优信通达科技有限公司 API接口
        Url = "http://service.youxinda.net/user/InterFace_Sand.aspx?UName=" & sUserName & "&Pwd=" & sKey & "&SmsMsg=" & Escape(Left(sContent, 70)) & "&MobileList=" & sMobile
    ElseIf SMS_ServicePro = 3 Then  '广州志晴网络科技有限公司 API接口
        Url = "http://124.172.250.160/WebService.asmx/mt?Sn=" & sUserName & "&Pwd=" & sKey & "&mobile=" & sMobile & "&content=" & Escape(Left(sContent, 70))
    Else
        Sending = -2
        Exit Function
    End If

    If KS.ChkClng(Session("SMS_SendTimes" & sFlag)) < KS.ChkClng(sNum) Then
        On Error Resume Next
        Err.Clear
        Set Http = Server.CreateObject("Msxml2.XMLHTTP")
        With Http
            .Open "GET", Url, False
            .setRequestHeader "Content-type:", "text/xml;charset=GB2312"
            .Send
            If Err.Number <> 0 Then
                Err.Clear
                Sending = -3
                Exit Function
            ElseIf .Readystate = 4 And .Status <> 200 Then
                Sending = -4
                Exit Function
            Else
                If SMS_ServicePro = 1 Then  '处理吉信通返回代码
                    If Left(.ResponseText, 3) <> "000" Then
                        Sending = -5
                        Exit Function
                    Else
                        Sending = 0
                    End If
                ElseIf SMS_ServicePro = 2 Then  '处理优信通达返回代码
                    If Left(.ResponseText, 2) <> "OK" Then
                        Sending = -5
                        Exit Function
                    Else
                        Sending = 0
                    End If
                ElseIf SMS_ServicePro = 3 Then  '处理志晴网络返回代码
                    If InStr(.ResponseText, ">0<") = 0 Then
                        Sending = -5
                        Exit Function
                    Else
                        Sending = 0
                    End If
                End If
            End If
        End With
        Set Http = Nothing
        If KS.IsNul(Session("SMS_SendTimes" & sFlag)) Then
            Session("SMS_SendTimes" & sFlag) = 1
        Else
            Session("SMS_SendTimes" & sFlag) = Session("SMS_SendTimes" & sFlag) + 1
        End If
    Else
        Sending = -6
    End If
    
End Function

'函数名：GetNumString
'返回值：随机无重复的ID数字
'********************************************************
Function GetNumString()
    Dim TableNameStr, ID
    TableNameStr = "Select Top 1 ID From Log_SMS Where OrderID ='"
    Do While True
       ID = "SMS" & Right("0" & Day(Now), 2) & Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & KS.MakeRandom(4)
       If Conn.Execute(TableNameStr & ID & "'").EOF Then Exit Do
    Loop
    GetNumString = ID
End Function

Sub Die(Str)
    On Error Resume Next
    Response.Write Str
    Set KS = Nothing
    Set KSUser = Nothing
    Call CloseConn()
    Response.End
End Sub
%>
