Imports System.Data
Imports System.IO
Imports AppAuth
Imports AppCommon
Imports AppVariable
Imports System.Net
Partial Class portal
    Inherits System.Web.UI.MasterPage

    Private DBServerAuthUserId As String = ConfigurationManager.AppSettings("WebDavAuthUserId").ToString()
    Private DBServerAuthUserPass As String = ConfigurationManager.AppSettings("WebDavAuthUserPass").ToString()
#Region "******************** ページイベント ********************"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'ヘッダの左領域を設定
        SetHeaderLeft(lb_user, lb_title)
        'ヘッダの右領域を設定
        SetHeaderRight(lb_loginuser, msp_user_name)
        msp_user_name.Text = Session(S_COM_User_Name)

        '----------------------------------------------------------------
        '認証済の確認
        '----------------------------------------------------------------
        If Session(S_COM_PortalID) Is Nothing Then
            Response.Redirect(Request.ApplicationPath & Logout_FilePath)
        End If

        '----------------------------------------------------------------
        'コンテンツへのアクセス認証
        '----------------------------------------------------------------
        If IsPostBack = False Then
            If Auth_Content(Session(S_COM_PortalID), Replace(Request.FilePath.ToString, Request.ApplicationPath, ""), Session(S_MSP_Selected_UC1_Path)) = False Then
                Response.Redirect(Request.ApplicationPath & Logout_FilePath)
            End If
        End If

        '---------------------------------------------------------------
        'HTMLタグを追加
        '---------------------------------------------------------------
        Dim ctl As Control = Page.Master.FindControl("msp_header")
        '2024/02/23 M.Okabe DEL Start
        ''JS
        'SetTagJs(ctl, "jquery-1.8.3.min.js")
        'SetTagJs(ctl, "jquery.cookie.js")
        'SetTagJs(ctl, "master.js")
        'SetTagJs(ctl, "info.js")
        'SetTagJs(ctl, "common.js")
        'SetTagJs(ctl, "jquery-ui.js")  '2018.09.07 ADD /Liu
        '2024/02/23 M.Okabe DEL End
        'ファビコン
        SetTagFavicon(ctl)

        '-----------------------------------------------------------------
        'Safari, ChromeでMENUコントロールの動作がおかしくなるための対策
        '-----------------------------------------------------------------
        If (Request.UserAgent.ToLower().IndexOf("applewebkit") >= 0) Then
            Request.Browser.Adapters.Clear()
        End If

        '-----------------------------------------------------------------
        'メニューをセット
        '-----------------------------------------------------------------
        SetMenuBar()
        SetMenu()

        '-----------------------------------------------------------------
        'ユーザコントロールをセット
        '-----------------------------------------------------------------
        Try '※外すと落ちる
            Dim uc As UserControl

            If Not Session(S_MSP_Selected_UC1_Path) Is Nothing Then
                uc = LoadControl(Request.ApplicationPath & Session(S_MSP_Selected_UC1_Path))
            Else
                msp_asp_usercon1.Visible = False
                uc = LoadControl("")
            End If

            msp_asp_usercon1.Controls.Add(uc)

            If Not Session(S_MSP_Selected_UC1_Path) Is Nothing Then
                msp_uc1_name.Text = HttpUtility.UrlDecode(Session(S_MSP_Selected_UC1_Title))
            Else
                msp_uc1_name.Text = ""
            End If
        Catch ex As Exception
        End Try

        '---------------------------------------------------------------
        'クリックしたメニューバーアイテムを選択状態にする
        '---------------------------------------------------------------
        If Not Session(S_MSP_Selected_Menubar_Parent_Index) Is Nothing Then
            If msp_asp_menubar.Items.Count > 0 Then
                msp_asp_menubar.Items(Session(S_MSP_Selected_Menubar_Parent_Index)).Selected = True
            End If
        End If

        '---------------------------------------------------------------
        'クリックしたメニューアイテムを選択状態にする
        '---------------------------------------------------------------
        Try '※外すと落ちる
            If Not Session(S_MSP_Selected_Menu_Parent_Index) Is Nothing _
                     And Not Session(S_MSP_Selected_Menu_Children_Index) Is Nothing Then
                If msp_asp_menu.Items.Count > 0 Then
                    msp_asp_menu.Items(Session(S_MSP_Selected_Menu_Parent_Index)).ChildItems(Session(S_MSP_Selected_Menu_Children_Index)).Selected = True
                End If
            End If
        Catch ex As Exception
        End Try

        '---------------------------------------------------------------
        'クリックしたメニューアイテムのタイトルを挿入する
        '---------------------------------------------------------------
        If Not Session(S_MSP_Selected_Title) Is Nothing Then
            uc_TitleBar_big.Text = HttpUtility.UrlDecode(Session(S_MSP_Selected_Title))
        End If
    End Sub

#End Region

#Region "***************** コントロールイベント *****************"

    Protected Sub msp_asp_menubar_MenuItemClick(ByVal sender As Object, ByVal e As MenuEventArgs) Handles msp_asp_menubar.MenuItemClick
        '-------------------------------------------------------------------------------------
        'セレクト情報を保存
        '-------------------------------------------------------------------------------------
        '親選択時
        If e.Item.Depth = 0 Then
            Session(S_MSP_Selected_Menubar_Parent_Index) = msp_asp_menubar.Items.IndexOf(e.Item)

            '-------------------------------------------------------------------------------------
            'メニューのセレクト情報を初期化
            '-------------------------------------------------------------------------------------
            Session(S_MSP_Selected_Menu_Parent_Index) = ""
            Session(S_MSP_Selected_Menu_Children_Index) = ""

            '-------------------------------------------------------------------------------------
            'セッションクリア
            '-------------------------------------------------------------------------------------
            SessionClear()

            '-------------------------------------------------------------------------------------
            'コンテンツ呼び出し
            '-------------------------------------------------------------------------------------
            Response.Redirect(Com_Get_Content_M(str_ParamGet(e.Item.Value, "menu")))
        End If
    End Sub

    Protected Sub msp_asp_menu_MenuItemClick(ByVal sender As Object, ByVal e As MenuEventArgs) Handles msp_asp_menu.MenuItemClick
        If e.Item.Depth = 1 Then
            '-------------------------------------------------------------------------------------
            'Sessionにセレクト情報を保存
            '-------------------------------------------------------------------------------------
            Session(S_MSP_Selected_Menu_Parent_Index) = msp_asp_menu.Items.IndexOf(e.Item.Parent)
            Session(S_MSP_Selected_Menu_Children_Index) = msp_asp_menu.Items(msp_asp_menu.Items.IndexOf(e.Item.Parent)).ChildItems.IndexOf(e.Item)

            '-------------------------------------------------------------------------------------
            'セッションクリア
            '-------------------------------------------------------------------------------------
            SessionClear()

            '-------------------------------------------------------------------------------------
            'コンテンツ呼び出し
            '-------------------------------------------------------------------------------------
            Response.Redirect(Com_Get_Content(str_ParamGet(e.Item.Value, "function")))
        End If
    End Sub

    '操作説明マニュアルダウンロード
    Private Sub LinkManual_Click(sender As Object, e As EventArgs) Handles lnk_Manual.Click
        Dim filePath As String = Com_Get_変数("PT_MANUAL_PATH")

        Select Case Session(S_COM_PortalKbn)
            Case "学生"
                filePath = Com_Get_変数("PT_MANUAL_TRAINEE_PATH")
            Case "職員"
                filePath = Com_Get_変数("PT_MANUAL_GOV_CONTACT_PATH")
            Case "教員"
                filePath = Com_Get_変数("PT_MANUAL_TEACHER_PATH")
            Case Else
                filePath = filePath
        End Select

        DownloadFile(filePath)
    End Sub

    '2024/12/08 M.Okabe ADD Start
    'トップ(解像度低の場合のみ)
    Protected Sub btnTop_Click(ByVal sender As Object, ByVal e As EventArgs)
        'ページ遷移
        Response.Redirect(Com_Get_Content(FunctionCd.Top))
    End Sub
    '2024/12/08 M.Okabe ADD End
#End Region

#Region "******************* Sub及びFunction ********************"

    '-------------------------------------------------------------
    '取得したデータをメニューコントロールへセットする。
    '-------------------------------------------------------------
    Private Sub SetMenuBar()
        Dim ds As DataSet = GetMenubarData()

        If Not ds.Tables(0) Is Nothing Then
            For Each masterRow As DataRow In ds.Tables(0).Rows
                Dim masterItem As New MenuItem(masterRow("MENU名").ToString(), "?" & _
                                                "menu=" & masterRow("MENUCD").ToString() & "&")
                msp_asp_menubar.Items.Add(masterItem)
            Next
        End If
    End Sub

    '-------------------------------------------------------------
    '取得したデータをメニューコントロールへセットする。
    '-------------------------------------------------------------
    Private Sub SetMenu()
        Dim ds As DataSet = GetMenuData()
        Dim childItem '2020.10.9 S.Maki
        
        Try
            If Not ds.Tables("CATEGORY") Is Nothing Then
                For Each masterRow As DataRow In ds.Tables("CATEGORY").Rows
                    Dim masterItem As New MenuItem(masterRow("機能分類名").ToString(), "?" & _
                                                            "category=" & masterRow("機能分類CD").ToString() & "&")
                    msp_asp_menu.Items.Add(masterItem)

                    If Not masterRow.GetChildRows("CHILDREN") Is Nothing Then
                        For Each childRow As DataRow In masterRow.GetChildRows("CHILDREN")
                            
                            '2020.10.9 S.Maki
                            If childRow("CONTENT_PATH").StartsWith("http") Then
                                childItem = New MenuItem()
                                childItem.NavigateUrl = childRow("CONTENT_PATH")
                                childItem.Text = childRow("機能名").ToString()
                                childItem.Target = "_blank"
                            Else
                                childItem = New MenuItem(childRow("機能名").ToString(), "?function=" & childRow("機能CD").ToString() & "&")
                            End If
                            'Dim childItem As New MenuItem(childRow("機能名").ToString(), "?" & "function=" & childRow("機能CD").ToString() & "&")
                            '2020.10.9 End
                            
                            masterItem.ChildItems.Add(childItem)
                        Next
                    End If
                Next
            End If
        Catch ex As Exception
        End Try
    End Sub

    '-------------------------------------------------------------
    'データベースからMENUおよびMENUSUBデータを取得し返す。
    '-------------------------------------------------------------
    Private Function GetMenubarData() As DataSet
        Using spm As New StoredProcedureManager("PT_MENU_SELECT")
            spm.AddPrmIn("@PORTALID", Data.SqlDbType.VarChar, Session(S_COM_PortalID))
            spm.Fill()

            Return spm.ds
        End Using
    End Function

    '-------------------------------------------------------------
    'データベースから機能分類およびMENUSUBデータを取得し返す。
    '-------------------------------------------------------------
    Private Function GetMenuData() As DataSet
        '   機能分類データ取得
        Using spm As New StoredProcedureManager("PT_機能分類_SEL")
            spm.AddPrmIn("@MENUCD", Data.SqlDbType.VarChar, Session(S_MSP_Selected_MenuCD))
            spm.AddPrmIn("@PORTALID", Data.SqlDbType.VarChar, Session(S_COM_PortalID))
            spm.Fill("CATEGORY")

            '機能データ取得
            spm.Reset("PT_機能_SEL")
            spm.AddPrmIn("@MENUCD", Data.SqlDbType.VarChar, Session(S_MSP_Selected_MenuCD))
            spm.AddPrmIn("@PORTALID", Data.SqlDbType.VarChar, Session(S_COM_PortalID))
            spm.Fill("FUNCTION")

            spm.ds.Relations.Add( _
                  "CHILDREN" _
                , spm.ds.Tables("CATEGORY").Columns("機能分類CD") _
                , spm.ds.Tables("FUNCTION").Columns("機能分類CD") _
            )

            Return spm.ds
        End Using
    End Function

    Private Function str_ParamGet(ByVal str_Search As String, ByVal str_Param As String) As String
        Dim str As String
        Dim strCnt As Integer

        Try
            str = str_Search
            '---------------------------------------
            '「?」以降の文字列を取得
            '---------------------------------------
            strCnt = str.IndexOf("?")
            str = Mid(str, strCnt + 1, Len(str))

            '---------------------------------------
            'パラメータ以降の文字列を取得
            '---------------------------------------
            strCnt = str.IndexOf(str_Param & "=")
            str = Mid(str, strCnt + 1, Len(str))

            '---------------------------------------
            'パラメータから「&」までの文字列を取得
            '---------------------------------------
            strCnt = str.IndexOf("&")

            '「&」がなければすべての文字列を取得
            If strCnt < 0 Then
                str = Left(str, Len(str))
            Else
                str = Left(str, strCnt)
            End If

            '---------------------------------------
            'パラメータ値を取得
            '---------------------------------------
            str = Replace(str, str_Param & "=", "")
            str = Replace(str, "&", "")
        Catch ex As Exception
            Return "Err_SVN:str_ParamGet()関数で予期せぬエラーが発生しました。"
        End Try

        Return str
    End Function

    Private Sub SessionClear()
        '※メンテナンスしきれないので未使用

        '2020/6/19 ADD START バグ修正
        '例、個人お知らせから連絡事項に切り替える際は、
        '1)前回クリックした個人お知らせの対象がユーザコントロールに残っている
        '2)Gridviewが前回選択された状態になっている
        Session.Remove(S_Info_Selected_No)
        Session.Remove("InfoPersonal_SelectedIndex")
        Session.Remove("InfoPublic_SelectedIndex")
        Session.Remove("InfoClass_SelectedIndex")
        '2020/6/19 ADD END バグ修正
    End Sub

    Private Sub DownloadFile(filePath As String)
        '基幹のWebDavの絶対パス
        Dim coreWebDavPath As String = Com_Get_変数("COMMON_DIRECTORY")

        '基幹の絶対パスの場合、直接参照できないので、URLパスに変換
        If filePath.StartsWith(coreWebDavPath) Then
            Dim urlWebDavPath As String = Com_Get_変数("PT_COMMON_DIRECTORY")
            filePath = filePath.Replace(coreWebDavPath, urlWebDavPath)
        End If
        ' URLの場合
        If filePath.StartsWith("http://") OrElse filePath.StartsWith("https://") Then
            DownloadFromUrl(filePath)
        Else
            DownloadLocalFile(filePath)
        End If
    End Sub

    Private Sub DownloadLocalFile(filePath As String)
        Dim fileName As String = Path.GetFileName(filePath)
        If File.Exists(filePath) Then
            Response.ContentType = "application/octet-stream"
            Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=""{0}""", fileName))
            Response.TransmitFile(filePath)
            Response.End()
        Else
            Response.Write("<script>alert('指定されたファイルが存在しません。');</script>")
        End If
    End Sub

    Private Sub DownloadFromUrl(url As String)
        Try
            ' ファイルをダウンロード
            Dim fileName As String = Path.GetFileName(url)
            ' レスポンスヘッダーを設定
            Response.Clear()
            Response.Buffer = False
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; filename=""" & fileName & """")

            Using client As New WebClient()
                ' 認証情報を設定
                Dim username As String = DBServerAuthUserId
                Dim password As String = DBServerAuthUserPass
                Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username & ":" & password))
                client.Headers("Authorization") = "Basic " & credentials
                Dim fileData As Byte() = client.DownloadData(url)

                Response.AddHeader("Content-Length", fileData.Length.ToString())
                Response.OutputStream.Write(fileData, 0, fileData.Length)

                Response.Flush()
                Response.Close()
            End Using
        Catch ex As WebException

            Dim errorResponse As HttpWebResponse = TryCast(ex.Response, HttpWebResponse)
            If errorResponse IsNot Nothing Then
                Select Case errorResponse.StatusCode
                    Case HttpStatusCode.Unauthorized
                        Response.Write("<script>alert('認証に失敗しました。ユーザーIDとパスワードを確認してください。');</script>")
                    Case HttpStatusCode.NotFound
                        Response.Write("<script>alert('指定されたファイルが見つかりません。');</script>")
                    Case Else
                        Response.Write(String.Format("<script>alert('ファイルのダウンロードに失敗しました: {0}');</script>", ex.Message))
                End Select
            Else
                Response.Write(String.Format("<script>alert('ネットワークエラーが発生しました: {0}');</script>", ex.Message))
            End If
        Catch ex As Exception
            ' その他の例外処理
            Response.Write(String.Format("<script>alert('エラーが発生しました: {0}');</script>", ex.Message))
        End Try
    End Sub

#End Region

End Class

