<%
'#################################################################################
'## Copyright (C) 2000  Michael Anderson and Pierre Gorissen
'## 
'## This program is free software; you can redistribute it and/or
'## modify it under the terms of the GNU General Public License
'## as published by the Free Software Foundation; either version 2
'## of the License, or any later version.
'##
'## All copyright notices regarding Snitz Forums 2000
'## must remain intact in the scripts and in the outputted HTML
'## The "powered by" text/logo with a link back to 
'## http://forum.snitz.com in the footer of the pages MUST
'## remain visible when the pages are viewed on the internet or intranet.
'## 
'## This program is distributed in the hope that it will be useful,
'## but WITHOUT ANY WARRANTY; without even the implied warranty of
'## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'## GNU General Public License for more details.
'## 
'## You should have received a copy of the GNU General Public License
'## along with this program; if not, write to the Free Software
'## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
'## 
'## Support can be obtained from support forums at:
'## http://forum.snitz.com 
'##
'## Correspondence and Marketing Questions can be sent to:
'## reinhold@bigfoot.com
'## 
'## or
'## 
'## Snitz Communications 
'## C/O: Michael Anderson
'## PO Box 200
'## Harpswell, ME 04079
'#################################################################################
'# File Attachment Mod by Huw Reddick
'#################################################################################
%>
<!--#include file="config.asp"-->
<!--#include file="inc_functions.asp"-->
<!-- #include file="include/clsUpload.inc" -->

<%
   '--- Object to parse the input ---
   Dim objUpload
   Dim strRoot
   Dim strFolder
   Dim MaxFileSize
   Dim boolAllowedType
   Dim strAllowedExtensions
   Dim strResult
   Dim faname 
   Dim boolSuccess
   Dim intFileLen
   Dim ImageFile
   Dim ServerTimeout
   Dim strUploadPath
   
   ServerTimeout = 10000
   
  
	set my_Conn= Server.CreateObject("ADODB.Connection")
	my_Conn.Open strConnString
	
	Set objDict = Server.CreateObject("Scripting.Dictionary")
	set objRec = my_Conn.execute("SELECT * FROM " & strTablePrefix & "MODS WHERE M_NAME = 'Attachment' OR M_CODE = 'Attachment'")

	while not objRec.EOF 
	objDict.Add objRec.Fields.Item("m_code").Value, objRec.Fields.Item("m_value").Value
	objRec.moveNext
	wend 
	
	MaxFileSize = cLng(objDict.Item("faMaxSize"))*512
	strAllowedExtensions = objDict.Item("faExtensions")
	boolAllowUploads = cint(objDict.Item("Attachment"))

	objRec.Close
	set objDict = nothing



   strResult = "Finished..."

   If Request.TotalBytes > 0 Then
     Set objUpload = new clsUpload
     objUpload.ParseRequest
     If (objUpload.Files.Count = 1) Then
        	referrer		= objUpload.Form.Item("referrer")
			set objPath = my_conn.execute("SELECT M_VALUE FROM " & strTablePrefix & "MODS WHERE M_CODE = '" & referrer & "'" )
			if not objPath.eof then
				strUploadPath = objPath("M_VALUE")
			else
				strUploadPath = ""
			end if
		if referrer = "attach" then
			strFolder 		= strUploadPath & getslash & objUpload.Form.Item("Folder")
			strSubFolder	= objUpload.Form.Item("Folder")
			TopicID			= objUpload.Form.Item("TOPIC_ID")
			ReplyID 		= objUpload.Form.Item("REPLY_ID")
			MemberID 		= objUpload.Form.Item("MEMBER_ID")
			ServerTimeout 	= objUpload.Form.Item("TimeOut")
			isLinkImage		= objUpload.Form.Item("isLinkImage")
			if ReplyId = "" then 
			ReplyID = -1
			end if
			if TopicID = "" then
		 		TopicID = -1
			end if
		elseif referrer = "filelibrary" then
			strFolder 		= strUploadPath
			fAuthor 		= objUpload.Form.Item("fAuthor")
			fSubmitted 		= objUpload.Form.Item("fSubmitted")
			fTitle 			= objUpload.Form.Item("fTitle")
			fCategory 		= objUpload.Form.Item("fCategory")
			fForumLink 		= objUpload.Form.Item("fForumLink")
			fSummary 		= objUpload.Form.Item("fSummary")
			fVersion 		= objUpload.Form.Item("fVersion")
			fCompat 		= objUpload.Form.Item("fCompat")
			fInstallation 	= objUpload.Form.Item("fInstallation")
			fNotes 			= objUpload.Form.Item("fNotes")
			fDescription 	= objUpload.Form.Item("fDescription")
			fValid			= objUpload.Form.Item("fvalid")
			faname 			= objUpload.Files.Item(0).FileName
			fDate 			= dateToStr(strForumTimeAdjust)
		elseif referrer = "updatelibrary" then
			strFolder 		= strUploadPath
			fdate 			= dateToStr(strForumTimeAdjust)
			fFileID			= objUpload.Form.Item("fFileID")
		elseif referrer = "my_upload" then
			strFolder		=  strUploadPath & getslash & objUpload.Form.Item("Folder")
			MemberID = objUpload.Form.Item("MEMBER_ID")
			CategoryID = objUpload.Form.Item("category")
			fileDescription = objUpload.Form.Item("description")
		elseif referrer = "admin_upload" then
			strFolder		=  objUpload.Form.Item("Folder")
		elseif referrer = "dbsfiles" then
			strFolder		=  objUpload.Form.Item("Folder")
		end if
		faname 			= objUpload.Files.Item(0).FileName
		intFileLen 		= len(objUpload.Files.Item(0).Blob)
		
        boolAllowedType = Instr(strAllowedExtensions, Right(faname,4)) > 0
		ImageFile = Instr(".jpg,.gif", Right(faname,4)) > 0
		if referrer = "dbsfiles" then
			boolAllowedType = Instr(".asp", Right(faname,4)) > 0
		end if
		if intFileLen > MaxFileSize then
			strResult = "File is too Large to upload"
		else
	        if boolAllowedType then
				Response.write "Uploading.... Please wait"
				boolSuccess = saveDoc()
				If boolSuccess = "True" Then
		          	if referrer = "attach" then
						intoAttachDB()
	  	          		strResult = "The File " & faname & " was uploaded to the Server"
					elseif referrer = "filelibrary" then
						intoLibraryDB()
					elseif referrer = "updatelibrary" then
						updateLibraryDB()
					elseif referrer = "my_upload" then
						intoMyFilesDB()
					end if
				else
					strResult = "Save Failed"
				End If
			else
				strResult = "File Type Not Allowed"
			end if
		end if
     Else
       strResult = "No file to upload."
     End If
   End If
	set my_Conn = nothing

   '---------------------------------------------------------------------------
   '- Function    : intoAttachDB
   '- Description : inserts the document information in the database
   '---------------------------------------------------------------------------
   Private Function intoAttachDB()
   	Dim strSQL
   	set my_Conn= Server.CreateObject("ADODB.Connection")

	my_Conn.Open strConnString
	set rs= Server.CreateObject("ADODB.Recordset")
     strSQL = "INSERT INTO " & strMemberTablePrefix & "USERFILES (MEMBER_ID,F_FILENAME,F_FILESIZE,F_TOPIC_ID,F_REPLY_ID) VALUES("
     strSQL = strSQL  & MemberID & ", "
     strSQL = strSQL & "'" & objUpload.Files.Item(0).FileName 
	 strSQL = strSQL &  "'," & intFileLen & ", "
     strSQL = strSQL  & TopicID & ", "
     strSQL = strSQL & ReplyID & ")"
     my_Conn.execute( strSQL )
	 strSQL = "SELECT F_FILEID FROM " & strMemberTablePrefix & "USERFILES WHERE MEMBER_ID=" & MemberID
	 strSQL = strSQL & " AND F_TOPIC_ID=" & TopicID & " AND F_REPLY_ID=" & ReplyID & " AND F_FILENAME ='" & objUpload.Files.Item(0).FileName & "'"
	 if not ImageFile then
		set rs = Server.CreateObject("ADODB.Recordset")
		rs.open  strSql,  my_Conn, 3
		faname = rs("F_FILEID")
		rs.close
	 end if
	 my_conn.close
   End Function
   '---------------------------------------------------------------------------
   '- Function    : intoLibraryDB
   '- Description : inserts the document information in the database
   '---------------------------------------------------------------------------
   Private Function intoLibraryDB()
   	Dim strSQL
		   	set my_Conn= Server.CreateObject("ADODB.Connection")
			my_Conn.Open strConnString

			sSQL = " INSERT INTO " & strTablePrefix & "FILEMANAGER (" 
			sSQL = sSQL & "F_TITLE,F_AUTHOR,F_AUTHORID,F_CAT,F_DATE,F_FILELINK,F_FORUMLINK,F_SNIPPET,F_VERSION,F_COMPAT,F_INSTALLATION,F_NOTES,F_DESCRIPTION,F_VALID ) VALUES("
			sSQL = sSQL & "'" & chkString(fTitle,"SQLstring") & "', '"
			sSQL = sSQL & chkString(fAuthor,"SQLstring") & "', "
			sSQL = sSQL & fSubmitted & ", "
			sSQL = sSQL & fCategory & ", '"
			sSQL = sSQL & fDate & "', '"
			sSQL = sSQL & faname & "', '"
			sSQL = sSQL & fForumLink & "', '"
			sSQL = sSQL & chkString(fSummary,"SQLstring") & "', '"
			sSQL = sSQL & fVersion & "', '"
			sSQL = sSQL & fCompat & "', '"
			sSQL = sSQL & chkString(fInstallation,"SQLstring") & "', '"
			sSQL = sSQL & chkString(fNotes,"SQLstring") & "', '"
			sSQL = sSQL & chkString(fDescription,"SQLstring") & "'," & fValid & ") "

			my_conn.execute(sSQL)
			my_conn.close
			Response.write "<meta http-equiv='Refresh' content='2; URL=file_library.asp'>"
			response.end
   End Function
   '---------------------------------------------------------------------------
   '- Function    : intoMyFilesDB()
   '- Description : inserts the document information in the database
   '---------------------------------------------------------------------------
   Private Function intoMyFilesDB()
   	Dim strSQL
   	set my_Conn= Server.CreateObject("ADODB.Connection")
	my_Conn.Open strConnString
	set rs= Server.CreateObject("ADODB.Recordset")

			strSQL = "SELECT * from " & strTablePrefix & "MYFILES WHERE file_name='" & faname & "'"
			'response.write strSQL
			set rs = my_conn.execute (strSQL)
			if not rs.EOF then
				strSQL = "UPDATE " & strTablePrefix & "MYFILES SET file_size,file_cat,file_description,file_date)"
			else
				strSQL = "INSERT INTO " & strTablePrefix & "MYFILES (file_name,file_size,file_cat,file_status,file_description,MEMBER_ID,file_date) VALUES ("
				strSQL = strSQL & "'" & faname & "', "
				strSQL = strSQL & intFileLen & ", "
				strSQL = strSQL & CategoryID & ", "
				strSQL = strSQL & 1 & ", "
				strSQL = strSQL & "'" & filedescription & "', "
				strSQL = strSQL & MemberID & ", "
				strSQL = strSQL & "'" & DateToStr(strForumTimeAdjust) & "') "
				response.write strSQL
				my_conn.execute (strSQL)
			end if
			my_conn.close
			Response.write "<meta http-equiv='Refresh' content='2; URL=myfiles.asp'>"
			response.end
   End Function
   '---------------------------------------------------------------------------
   '- Function    : updateLibraryDB
   '- Description : inserts the document information in the database
   '---------------------------------------------------------------------------
   Private Function updateLibraryDB()
   	Dim strSQL
		   	set my_Conn= Server.CreateObject("ADODB.Connection")
			my_Conn.Open strConnString

			sSQL = " UPDATE " & strTablePrefix & "FILEMANAGER SET " 
			sSQL = sSQL & "F_DATE = '" & fDate & "', "
			sSQL = sSQL & "F_FILELINK = '" & faname & "' "
			sSQL = sSQL & " WHERE ID = " & fFileID
			my_conn.execute(sSQL)
			my_conn.close
			
   End Function
   '---------------------------------------------------------------------------
   '- Function    : saveDoc
   '---------------------------------------------------------------------------
   private function saveDoc()

   Dim strFile
   Dim fso
	 server.scriptTimeout = cLng(ServerTimeout)
	 response.write "<br>" & strCookieURL & strFolder
	 strRoot = Server.MapPath(strCookieURL & strFolder)
	 
	 strFile = Server.MapPath(strCookieURL & strFolder & "/" & faname)
	 if referrer <> "attach" and referrer <> "dbsfiles" then
		strFile2 = Server.MapPath(strCookieURL & strFolder & "/"& fdate & "_" & faname)
	elseif referrer = "dbsfiles" then
		strRoot = Server.MapPath("/" & strFolder)
		strFile = Server.MapPath("/" & strFolder & "/" & faname)
	end if

     Set fso = Server.CreateObject("Scripting.FileSystemObject")
	 If not fso.FolderExists(strRoot) then
	 	fso.createFolder(strRoot)
	 end if
       objUpload.Files.Item(0).Save strRoot

	   if referrer <> "attach" and referrer <> "dbsfiles" then
	   	fso.MoveFile strFile,strFile2
		saveDoc = (fso.FileExists(strFile2))
		else
		saveDoc = (fso.FileExists(strFile))
		end if	
	   
   End Function
   
Function GetSlash      
strAspOs = UCase(Request.ServerVariables("ASP_OS"))
    If InStr(strAspOs,"WINDOWS") Then
	         GetSlash = "\"
	Else           
			GetSlash = "/"      
	End If
end function

%>
<html>

<head>
<title><% =strForumTitle %></title>
<meta name="copyright" content="This code is Copyright (C) 2000  Michael Anderson">
<Style><!--
a:link    {color:<% =strLinkColor %>;text-decoration:<% =strLinkTextDecoration %>}
a:visited {color:<% =strVisitedLinkColor %>;text-decoration:<% =strVisitedTextDecoration %>}
a:hover   {color:<% =strHoverFontColor %>;text-decoration:<% =strHoverTextDecoration %>}
--></style>
</head>

<BODY background="<%= strForumURL %><%= strBGImageUrl %>" text="<% =strDefaultFontColor %>" link="<% =strLinkColor %>" aLink=<% =strActiveLinkColor %> vLink="<% =strActiveLinkColor %>" onLoad="window.focus()">

<table width="100%" height="100%">
  <tr>
    <td align=center valign=center>
    <div align=center><center>
    <font face="<% =strDefaultFontFace %>" size="<% =strDefaultFontSize %>">

<p>	<%=strResult%></p><br><br>

    <p>
<% 	if referrer <> "filelibrary" then
	if imageFile then %>
	<font face="<% =strDefaultFontFace %>" size="<% =strDefaultFontSize %>">
		<% if referrer = "attach" then %>
		<a href="JavaScript:onClick= addimage()">Close Window</A></font>
		<% Else  %>
			<a href="JavaScript:onClick= window.close()">Close Window</A></font>
		<% End If %>
	<% Else  %>
	<font face="<% =strDefaultFontFace %>" size="<% =strDefaultFontSize %>">
	<% if referrer = "attach" then %>
		<a href="JavaScript:onClick= addfile()">Close Window</A>
		<% Else  %>
			<a href="JavaScript:onClick= window.close()">Close Window</A></font>
		<% End If %>
	
	</font>	
	<% End If 
	else
		Response.write "<meta http-equiv='Refresh' content='2; URL=file_library.asp'>"
	end if%>
	</p>
    </font>
    </center></div>
    </td>
  </tr>
</table>
<script language="JavaScript">
<!--
function addfile()
{
	var fname, resultString
	resultString ='<%= boolSuccess %>';
	fname = '<%= faname %>';
	if (resultString)
	window.opener.document.PostTopic.Message.value+= '[url="pop_download.asp?mode=Edit&dir='  + '<%=strSubFolder%>' + '&file=' + fname + '"][img]images\/disk.gif[/img][/url]';
	window.close();
}

//-->
</script>
<script language="JavaScript">
<!--
function addimage()
{
	var fname, resultString, isLinkImage
	resultString ='<%= boolSuccess %>';
	fname = '<%= faname %>';
	isLinkImage = '<%=isLinkImage%>'
	if (resultString)
	{
		if (isLinkImage)
			window.opener.document.PostTopic.ImageURL.value = '<% = strForumURL & strFolder %>' +  "/" + fname
		else
				
			window.opener.document.PostTopic.Message.value+= '[img]' + '<%= strCookieURL & strFolder %>' + "/" + fname + '[/img]' + isLinkImage;
	}
	window.close();
}

//-->
</script>

</BODY>
</HTML>
