Imports System.Web
Imports BaseFunction.PublicMethod
Imports ICSharpCode.SharpZipLib
Imports System.Drawing
Imports System.Text
Imports System.Text.RegularExpressions

Public Class clsFile
    Public Function SaveUpload() As String
        Dim file As HttpPostedFile = HttpContext.Current.Request.Files("Filedata")
        If file IsNot Nothing Then
            Dim uploadPath As String = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request("folder"))
            Dim strFileEx As String = HttpContext.Current.Request("ex")
            Dim FileEx() As String = Nothing
            If strFileEx IsNot Nothing AndAlso strFileEx.Length > 0 Then
                FileEx = strFileEx.Replace("*", "").Split(";")
            Else
                FileEx = BaseFunction.PublicMethod.GetApplication("UpType").Replace("*", "").Split(";")
            End If

            Dim isReName As String = HttpContext.Current.Request("Rename")
            Dim UpFileEx As String = IO.Path.GetExtension(file.FileName)
            Dim mFileName As String = ""

            If FileEx.Contains(UpFileEx) Then
                If Not IsNothing(file) Then
                    If isReName = "1" Then
                        mFileName = Now.ToString("yyyyMMddhhmmss") & UpFileEx
                    Else
                        mFileName = file.FileName
                    End If
                    uploadPath = HttpContext.Current.Server.MapPath(uploadPath)
                    If Not uploadPath.EndsWith("\") Then
                        uploadPath = uploadPath & "\"
                    End If
                    If IO.Directory.Exists(uploadPath) Then
                        file.SaveAs(uploadPath & mFileName)
                        Return mFileName
                    Else
                        Return "0"
                    End If
                Else
                    Return "0"
                End If
            Else
                Return "0"
            End If
        Else
            Return "0"
        End If
    End Function
    Public Function GetFolders() As String
        Dim FolderName As String
        Dim VirFolderPath As String
        Dim mFolder() As String
        Dim resultStr As String = String.Empty
        Dim Path As String = HttpContext.Current.Request("Path")

        If Not IsNothing(Path) AndAlso Path.Length > 0 Then
            Path = HttpContext.Current.Server.MapPath(HttpUtility.UrlDecode(Path))
            mFolder = (From f In IO.Directory.GetDirectories(Path) _
                       Select f).ToArray
        Else
            mFolder = (From f In IO.Directory.GetDirectories(HttpContext.Current.Request.PhysicalApplicationPath) _
                       Select f).ToArray
        End If
        If mFolder.Count > 0 Then
            resultStr = "<ul>"
            For Each f In mFolder
                VirFolderPath = f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/")
                If f.EndsWith("\") Then
                    FolderName = Microsoft.VisualBasic.Left(f, f.Length - 1).Split("\").Last
                Else
                    FolderName = f.Split("\").Last
                End If
                resultStr += "<li id=""" & FolderName & """><span id=""" & VirFolderPath & """>" & FolderName & "</span>"
                If IO.Directory.GetDirectories(f).Count > 0 Then
                    resultStr += "<ul class='ajax'><li>{url:/GetFolders.gdr?Path=" & HttpUtility.UrlEncode(VirFolderPath) & "}</li></ul>"
                Else
                    resultStr += "<ul class='folder-close-last'></ul>"
                End If
                resultStr += "</li>"
            Next
            resultStr += "</ul>"
        End If
        Return resultStr
    End Function
    Public Function GetFiles() As String
        Dim mModel As Integer = 0
        Dim mShowCheck As Integer = 0
        Integer.TryParse(HttpContext.Current.Request("ShowCheck"), mShowCheck)
        Integer.TryParse(HttpContext.Current.Request("ShowM"), mModel)
        Dim PlugPath As String = HttpUtility.UrlDecode(HttpContext.Current.Request("Plug"))
        Dim FolderPath As String = HttpContext.Current.Request("Path")
        Dim strEX As String = HttpContext.Current.Request("Ex")
        Dim FileEx() As String = Nothing
        Dim resultStr As String = ""
        Dim mFileName As String
        Dim exPicName As String
        If strEX IsNot Nothing AndAlso strEX.Length > 0 Then
            FileEx = strEX.Split(",")
        End If
        If PlugPath Is Nothing OrElse PlugPath.Length = 0 Then
            PlugPath = "/App_Themes/ManagerTheme/Images/Explorer/"
        End If
        If FolderPath Is Nothing OrElse FolderPath.Length = 0 Then
            FolderPath = "/"
        End If
        If Not IsNothing(FolderPath) AndAlso FolderPath.Length > 0 Then
            FolderPath = HttpContext.Current.Server.MapPath(HttpUtility.UrlDecode(FolderPath))
            Dim Files() As String
            If FileEx IsNot Nothing Then
                Files = (From f In IO.Directory.GetFiles(FolderPath) _
                         Where FileEx.Contains(IO.Path.GetExtension(f)) _
                         Select f).ToArray
            Else
                Files = (From f In IO.Directory.GetFiles(FolderPath) _
                         Select f).ToArray
            End If
            Dim mFileFullName As String
            For Each f In Files
                mFileName = IO.Path.GetFileName(f)
                mFileFullName = mFileName
                If mFileName.Length > 21 Then
                    mFileName = CutString(IO.Path.GetFileName(f), 18)
                End If
                exPicName = IO.Path.GetExtension(f).Replace(".", "") & ".gif"
                If IO.File.Exists(HttpContext.Current.Request.PhysicalApplicationPath & PlugPath & "file\" & exPicName) Then
                    If mModel > 0 Then
                        resultStr += "<li id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "'><img src='" & PlugPath & "file/" & exPicName & "' style='cursor:pointer' /><span>" & mFileName & "</span></li>"
                    Else
                        If mShowCheck > 0 Then
                            resultStr += "<li id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "'><img src='" & PlugPath & "file/" & exPicName & "' style='cursor:pointer' /><span>" & mFileName & "</span><input type=""checkbox"" name=""chkfile"" id=""" & mFileFullName & """ /></li>"
                        Else
                            resultStr += "<li><img src='" & PlugPath & "file/" & exPicName & "' id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "' style='cursor:pointer' /><span>" & mFileName & "</span></li>"
                        End If
                    End If
                Else
                    If mModel > 0 Then
                        resultStr += "<li id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "'><img src='" & PlugPath & "file/other.gif' style='cursor:pointer' /><span>" & mFileName & "</span></li>"
                    Else
                        If mShowCheck > 0 Then
                            resultStr += "<li id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "'><img src='" & PlugPath & "file/other.gif' style='cursor:pointer' /><span>" & mFileName & "</span><input type=""checkbox"" name=""chkfile"" id=""" & mFileFullName & """ /></li>"
                        Else
                            resultStr += "<li><img src='" & PlugPath & "file/other.gif' id='" & f.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/").Replace("\", "/") & "' style='cursor:pointer' /><span>" & mFileName & "</span></li>"
                        End If
                    End If

                End If
            Next
        End If
        Return resultStr
    End Function
    Public Function GetHTMLFile() As String
        Dim mFilePath As String = HttpContext.Current.Request("FilePath")
        If mFilePath IsNot Nothing AndAlso mFilePath.Length > 0 Then
            mFilePath = HttpContext.Current.Server.MapPath(mFilePath)
            If IO.File.Exists(mFilePath) Then
                Dim strIMG As String = IO.Path.GetDirectoryName(mFilePath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "/")).Replace("\", "/")
                Dim mHTML As String = IO.File.ReadAllText(mFilePath)
                Dim RegImg As RegularExpressions.Regex = New Regex("<IMG.*?src=""(.*?.*?)"".*?>", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
                Dim mImgs() As String = (From m As System.Text.RegularExpressions.Match In RegImg.Matches(mHTML) _
                                         Select m.Groups(1).Value).Distinct.ToArray
                For Each m In mImgs
                    mHTML = mHTML.Replace(m, strIMG & "/" & m)
                Next
                Return mHTML
            Else
                Return ""
            End If
        Else
            Return ""
        End If
    End Function
    Public Sub DownLoad()
        Dim MIME As String = ""
        Dim FileName As String = HttpContext.Current.Server.MapPath(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request("FileName")))
        If IO.File.Exists(FileName) Then
            Select Case IO.Path.GetExtension(FileName)
                Case ".gif", ".jpg", ".bmp", ".jpeg"
                    MIME = "image/" & Replace(IO.Path.GetExtension(FileName), ".", "")
                Case ".css", ".js"
                    MIME = "text/plain"
                Case Else
                    MIME = "application/octet-stream"
            End Select
            HttpContext.Current.Response.AddHeader("Content-Type", MIME)
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" & IO.Path.GetFileName(FileName))
            HttpContext.Current.Response.WriteFile(FileName)
            HttpContext.Current.Response.End()
        End If
    End Sub
    Public Function ExZip() As String
        Dim mFilePath As String = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request("FilePath"))
        Dim virFolder As String = IO.Path.GetDirectoryName(mFilePath)
        If ExToZip(HttpContext.Current.Server.MapPath(mFilePath)) Then
            Return virFolder
        Else
            Return "0"
        End If
    End Function
    Public Function AddFolder() As String
        Dim ParentFolder As String = HttpContext.Current.Request("ParentFolder")
        Dim NewFolderName As String = HttpContext.Current.Request("NewFolderName")
        If Not IsNothing(ParentFolder) AndAlso ParentFolder.Length > 0 AndAlso Not IsNothing(NewFolderName) AndAlso NewFolderName.Length > 0 Then
            Dim pPath As String = HttpContext.Current.Server.MapPath(ParentFolder)
            If Not IO.Directory.Exists(pPath & "\" & NewFolderName) Then
                Try
                    IO.Directory.CreateDirectory(pPath & "\" & NewFolderName)
                    Return "1"
                Catch ex As Exception
                    Return "0"
                End Try

            Else
                Return "0"
            End If
        Else
            Return "0"
        End If
    End Function
    Public Function DelFolder() As String
        Dim DelPath As String = HttpContext.Current.Request("FolderPath")
        If Not IsNothing(DelPath) AndAlso DelPath.Length > 0 Then
            Dim pPath As String = HttpContext.Current.Server.MapPath(DelPath)
            Try
                IO.Directory.Delete(pPath, True)
                Return "1"
            Catch ex As Exception
                Return "0"
            End Try
        Else
            Return "0"
        End If
    End Function
    Public Function DelFile() As String
        Dim FilePath As String = HttpContext.Current.Request("FilePath")
        If Not IsNothing(FilePath) AndAlso FilePath.Length > 0 Then
            Dim mFolderName As String = IO.Path.GetDirectoryName(FilePath)
            FilePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Server.UrlDecode(FilePath))
            If IO.File.Exists(FilePath) Then
                Try
                    IO.File.Delete(FilePath)
                    Return mFolderName
                Catch ex As Exception
                    Return "0"
                End Try
            End If
        End If
        Return "1"
    End Function
    Public Sub ResponseRndImage()
        Dim mCodeLen As Integer
        If Integer.TryParse(HttpContext.Current.Request("RndCodeLen"), mCodeLen) Then
            If mCodeLen > 32 Then mCodeLen = 32
            If mCodeLen < 1 Then mCodeLen = 4
        Else
            mCodeLen = 4
        End If
        Dim strCookieName As String = HttpContext.Current.Request("CodeCookie")
        If strCookieName Is Nothing OrElse strCookieName.Length = 0 Then strCookieName = "CodeCookie"
        Dim strCoding As String = System.Guid.NewGuid.ToString.Replace("-", "")
        Dim mCode As String = Left(strCoding, mCodeLen)
        Dim img As System.Drawing.Bitmap
        Dim g As Graphics
        Dim r As Random = New Random
        Dim gWidth As Integer = Int(mCodeLen * 15) ''gWidth为图片宽度,根据字符长度自动更改图片宽度 
        Dim x As Single = gWidth / (mCodeLen + 1)
        HttpContext.Current.Response.Cookies(strCookieName).Value = mCode
        img = New Bitmap(gWidth, 22)
        g = Graphics.FromImage(img)
        For i As Integer = 0 To 10 '画图片的背景噪音线 'For i As Integer = 0 To 25 
            Dim x1 As Integer
            x1 = r.Next(img.Width)
            Dim x2 As Integer = r.Next(img.Width)
            Dim y1 As Integer = r.Next(img.Height)
            Dim y2 As Integer = r.Next(img.Height)
            g.DrawLine(New Pen(getRandColor(160, 200)), x1, y1, x2, y2)
        Next i
        Dim font As Font
        font = New System.Drawing.Font("Arial", 14, FontStyle.Bold)
        Dim red As Integer = 0, green As Integer = 0, blue As Integer = 0, rdn As New Random
        Dim brush As System.Drawing.Drawing2D.LinearGradientBrush
        For i As Integer = 0 To mCodeLen - 1 '产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
            red = rdn.Next(255)
            green = rdn.Next(255)
            blue = rdn.Next(255)
            brush = New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(0, 0, img.Width, img.Height), Color.FromArgb(red, green, blue), Color.FromArgb(red, green, blue), 1.2F, True) '字体颜色 
            g.DrawString(mCode(i), font, brush, i * x + 4, 1)
        Next
        g.DrawRectangle(New Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1) '画图片的边框线 
        Dim ms1 As System.IO.MemoryStream '在矩形内绘制字串（字串，字体，画笔颜色，左上x.左上y）  
        ms1 = New System.IO.MemoryStream
        img.Save(ms1, System.Drawing.Imaging.ImageFormat.Png)
        HttpContext.Current.Response.ClearContent() '需要输出图象信息 要修改HTTP头  
        HttpContext.Current.Response.ContentType = "image/Png"
        HttpContext.Current.Response.BinaryWrite(ms1.ToArray())
        g.Dispose()
        img.Dispose()
        HttpContext.Current.Response.End()
    End Sub
    Private Function getRandColor(ByVal fc As Integer, ByVal bc As Integer) As Color
        Dim rdn As New Random()
        If fc > 255 Then fc = 255
        If bc > 255 Then bc = 255
        Dim r As Integer = fc + rdn.Next(bc - fc)
        Dim g As Integer = fc + rdn.Next(bc - fc)
        Dim b As Integer = fc + rdn.Next(bc - fc)
        Return Color.FromArgb(r, g, b)
    End Function


    Private Function ExToZip(ByVal ZipFile As String) As Boolean
        If IO.File.Exists(ZipFile) Then
            Dim FileList() As String = Nothing
            Dim ZipPath As String = IO.Path.GetDirectoryName(ZipFile)
            If Not ZipPath.EndsWith("\") Then
                ZipPath += "\"
            End If
            Using s As New Zip.ZipInputStream(IO.File.OpenRead(ZipFile))
                Dim ZipStream As IO.FileStream
                Dim ZipTry As Zip.ZipEntry
                Dim i As Integer = 0
                Try

                    Dim FileSize As Long = FileLen(ZipFile)
                    Dim ZipSizeSum As Long = 0

                    ZipTry = s.GetNextEntry
                    Do While Not IsNothing(ZipTry)
                        Dim ZipSize As Integer = 2048
                        Dim Buffer() As Byte
                        ReDim Buffer(2048)
                        If IO.Path.HasExtension(ZipTry.Name) Then
                            ZipStream = IO.File.Create(ZipPath & ZipTry.Name)
                        Else
                            IO.Directory.CreateDirectory(ZipPath & ZipTry.Name)
                            ZipTry = s.GetNextEntry
                            Continue Do
                        End If
                        ZipSizeSum = ZipSizeSum + ZipTry.CompressedSize
                        ReDim Preserve FileList(i)
                        FileList(i) = ZipTry.Name
                        Do While ZipSize > 0
                            ZipSize = s.Read(Buffer, 0, Buffer.Length)
                            If ZipSize > 0 Then
                                ZipStream.Write(Buffer, 0, ZipSize)
                            Else
                                Exit Do
                            End If
                        Loop

                        ZipStream.Flush()
                        ZipStream.Close()
                        ZipTry = s.GetNextEntry
                        If Not IsNothing(ZipTry) Then i = i + 1
                    Loop
                Catch e As Exception
                    Return Nothing
                End Try
            End Using
            Return True
        Else
            Return False
        End If
    End Function
End Class
