
<%
/**
 *	$RCSfile: post.jsp,v $
 *	$Revision: 1.1.1.1 $
 *	$Date: 2002/09/09 13:50:23 $
 */
%>

<%@ page import="java.util.*,
                 com.jivesoftware.forum.*,
                 com.jivesoftware.forum.util.*"
    errorPage="error.jsp"
%>

<%@ include file="include/branding/style.jsp" %>

<%@ include file="include/forumSetup.jsp" %>

<%! // Method to apply filters to a message object (used to preview a message)
    private ForumMessage applyFilters(ForumFactory forumFactory, Forum forum,
            ForumMessage message)
    {
        try {
            FilterManager filterManager = forumFactory.getFilterManager();
            message = filterManager.applyFilters(message);
            filterManager = forum.getFilterManager();
            message = filterManager.applyFilters(message);
        } catch (Exception e) { e.printStackTrace(); }
        return message;
    }
%>

<%  // Get parameters
    long forumID = ParamUtils.getLongParameter(request,"forum",-1L);
	long threadID = ParamUtils.getLongParameter(request,"thread",-1L);
    long messageID = ParamUtils.getLongParameter(request,"message",-1L);
    boolean doPost = ParamUtils.getBooleanParameter(request,"doPost");
    boolean reply = ParamUtils.getBooleanParameter(request,"reply");
    boolean fromPreview = ParamUtils.getBooleanParameter(request,"fromPreview");
    String subject = ParamUtils.getParameter(request,"subject");
    String body = ParamUtils.getParameter(request,"body");
    String postButton = ParamUtils.getParameter(request,"postButton");
    boolean quote = ParamUtils.getBooleanParameter(request,"quote");
    
    boolean preview = doPost && ("Preview".equals(postButton)) && !("Go Back/Edit".equals(postButton));
    boolean edit = doPost && ("Go Back/Edit".equals(postButton));
    
    // Load the forum
    if (forumID == -1L) {
        try {
            long sessionForumID
                = ((Long)session.getAttribute("forumID")).longValue();
            if (sessionForumID != -1L) {
                forumID = sessionForumID;
            }
        }
        catch (Exception e) {}
    }
    else {
        session.setAttribute("forumID", new Long(forumID));
    }
    Forum forum = forumFactory.getForum(forumID);
    
    // Determine if moderation is turned on for this forum
    boolean isThreadModOn = (
        forum.getModerationDefaultThreadValue()
        < forum.getModerationMinThreadValue()
    );
    boolean isMsgModOn = (
        forum.getModerationDefaultMessageValue()
        < forum.getModerationMinMessageValue()
    );
    
    // Thread we're posting in
	ForumThread thread = null;
    // The parent message we're replying to (if this is a reply)
	ForumMessage parentMessage = null;
    // Load these objects only if we're replying
	if (reply) {
     	thread = forum.getThread(threadID);
        // a message ID might not be passed in. If this is the case, we're
        // replying to the root message so get the message ID from the root
        // message of the thread
        if (messageID == -1L) {
            parentMessage = thread.getRootMessage();
            messageID = parentMessage.getID();
        } else {
            parentMessage = thread.getMessage(messageID);
        }
	}
    
    // Security check. Determine if this user can post new messages or reply to
    // threads
    // Check to see if this user can create replies
    boolean login = false;
    if (reply) {
        if (!forum.hasPermission(ForumPermissions.CREATE_MESSAGE)
                && !forumFactory.hasPermission(ForumPermissions.CREATE_MESSAGE))
        {
            if (isGuest) {
                login = true;
            }
            else {
                throw new UnauthorizedException("No permission to post replies in this forum");
            }
        }
    }
    // check to see if this use can create new topics
    else {
        if (!forum.hasPermission(ForumPermissions.CREATE_THREAD)
                && !forumFactory.hasPermission(ForumPermissions.CREATE_THREAD))
        {
            if (isGuest) {
                login = true;
            }
            else {
                throw new UnauthorizedException("No permission to post new topics in this forum");
            }
        }
    }
    if (login) {
        // If we need to login, send the referrer along as a link to this page
        StringBuffer postLink = new StringBuffer("post.jsp?forum=").append(forumID);
        if (threadID != -1L) {
            postLink.append("&thread=").append(threadID);
        }
        if (messageID != -1L) {
            postLink.append("&message=").append(messageID);
        }
        if (reply) {
            postLink.append("&reply=").append(reply);
        }
        response.sendRedirect("login.jsp?referrer=" +
            java.net.URLEncoder.encode(postLink.toString()));
        return;
    }
    
    // A user manager lets us get and set user information
    UserManager userManager = forumFactory.getUserManager();
    
    // The new message we're creating
    ForumMessage newMessage = null;
    
    // Errors on the page
	boolean errors = false;
    
    // The error message to show to the user
	String errorMessage = "";
    
    // Grab the subject & body from the session if we're coming from
    // a message preview (these values can't be passed as parameters) and
    // I don't want to POST to every page
	if (doPost && fromPreview && subject==null && body==null) {
 	    subject = (String)session.getValue("jive.message.subject");
        body = (String)session.getValue("jive.message.body");
	}
    
	// Error checks
    
    // Check to see the subject & body are not blank
	if (doPost && (subject == null)) {
 	    errors = true;
		errorMessage = "Please enter a subject";
    }
	else if (doPost && (body == null)) {
 	    errors = true;
        errorMessage = "Sorry, you can't post a blank message. Type a message and try again.";
	}
    
     // Do a message preview. For this, we populate a blank ForumMessage 
    // object. We don't add it to the db
	if (doPost && preview) {
		if (!errors) {
            if (isGuest) {
			    newMessage = forumFactory.createMessage();
            }
            else {
			    newMessage = forumFactory.createMessage(pageUser);
            }
			newMessage.setSubject(subject);
			newMessage.setBody(body);
			session.putValue("jive.message.subject",subject);
			session.putValue("jive.message.body",body);
            newMessage = applyFilters(forumFactory, forum, newMessage);
		}
	}
    // Otherwise, do a real post
	else {
		// Create a new message/thread
		if (doPost && !edit && !errors) {
			// Create a new message object
            if (isGuest) {
			    newMessage = forumFactory.createMessage();
            } else {
			    newMessage = forumFactory.createMessage(pageUser);
            }
			newMessage.setSubject(subject);
			newMessage.setBody(body);
			// if this is a reply, add it to the thread
			if (reply) {
				thread.addMessage(parentMessage,newMessage);
			}
			else {
				// it is a new posting
				forum.addThread(forumFactory.createThread(newMessage));
                thread = newMessage.getForumThread();
			}
            // remove the forumID from the session
            session.removeAttribute("forumID");
   			// Figure out where we need to redirect to.
            String redirect = "thread.jsp?forum="+forumID+"&thread="+thread.getID();
            // Do a standard redirect back to the new thread page if we're
            // not replying to a message
            if (!reply) {
                // However, if thread moderation is turned on, we shoud just
                // redirect back to the forum's thread listing:
                if (isThreadModOn) {
                    response.sendRedirect("forum.jsp?forum="+forumID);
                    return;
                }
                else {
                    // Standard redirect back to the new thread page
                    response.sendRedirect(redirect);
                    return;
                }
            }
            // Otherwise, we need to redirect back to the new posted reply.
            // Compute the correct thread page to go to.
            else {
                // However, if message moderation is turned on, we should just
                // redirect back to the top of the thread listing
                if (isMsgModOn) {
                    response.sendRedirect("thread.jsp?forum=" + forumID
                        + "&thread=" + threadID);
                    return;
                }
                else {
                    // the ID of the newly created message
                    long newMessageID = newMessage.getID();
                    // the number of threads a user wants to display on a topic page
                    int threadRange = myEnv.du.getThreadRange(request, response, pageUser);
                    // the number of messages in this thread
                    int messageCount = thread.getMessageCount();
                    // number of pages in the topic listing (we'll want to be at
                    // the end of that since new messages end up at the end of the
                    // thread list)
                    int numPages = (int)Math.ceil((double)messageCount/(double)threadRange);
                    // starting point:
                    int start = (numPages-1) * threadRange;
                    // do the redirect:
        			response.sendRedirect(
                        "thread.jsp?forum=" + forumID + "&thread=" + thread.getID()
                        + "&start=" + start + "&msRange=" + threadRange + "#" + newMessageID
                    );
                    return;
                }
            }
		}
    }
	
    if (preview && errors) {
        preview = false;
    }
%>

<%  String title = titlePrefix + ": " + forum.getName() + ": Post"; %>
<%@ include file="include/header.jsp" %>

<%@ include file="include/branding/header.jsp" %>

<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
    <td width="98%" valign="top">
    
    <span class="header">
    <%  if (reply) { %>
    Post a reply
    <%  } else { %>
    Post a new topic
    <%  } %>
    <br>
    <font size="-1">
    <%  if (rootBreadcrumbText != null && rootBreadcrumbLink != null) { %>
    <a href="<%= rootBreadcrumbLink %>" class="header"
    ><%= rootBreadcrumbText %></a>
    &raquo;
    <%  } %>
    <a href="index.jsp" class="header" title="Go back to the forum listing"
    >Forums</a>
    &raquo;
    <a href="forum.jsp?forum=<%= forumID %>" class="header" title="Go back to the topic list"
    ><%= forum.getName() %></a>
    </font>
    </span>
    
    </td>
    <td width="1%"><img src="images/blank.gif" width="8" height="1" border="0"></td>
    <td width="1%" valign="top">
    &nbsp;
    </td>
</tr>
</table>

<p>

<font size="-1" color="<%= deckTextColor %>">
<%  if (reply) { %>
Post a response in <a href="forum.jsp?forum=<%= forumID %>"><%= forum.getName() %></a>
to the message <b><%= parentMessage.getSubject() %></b>.
<%  } else { %>
Post in
<a href="forum.jsp?forum=<%= forumID %>"><%= forum.getName() %></a>.
<%  } %>
</font>
<p>

<p>

<font size="-1" color="<%= deckTextColor %>">
<%	if (preview) { %>
Below is a preview of how your message will look. You <b>must</b> click
on the "Post" button to submit your message. If you need to make changes, 
click the "Edit" button.
<%	} else { %>
    <%  if (reply) { %>
    Type a reply to the topic using the form below. When finished, you can   
    optionally preview your reply by clicking on the "Preview" button. Otherwise,  
    click the "Post" button to submit your message immediately.
    <%      if (isMsgModOn) { %>
        <p>
        <font color="#cc3300">
        Please note, your reply will need to be approved by a moderator before
        it will be posted in the forum.
        </font>
    <%      } %>
    
    <%  } else { %>
    Type your message using the form below. When finished, you can   
    optionally preview your post by clicking on the "Preview" button. Otherwise,  
    click the "Post" button to submit your message immediately. 
    <%      if (isThreadModOn) { %>
        <p>
        <font color="#cc3300">
        Please note, your topic will need to be approved by a moderator before
        it will be posted in the forum.
        </font>
    <%      } %>

    <%  } %>
<%  } %>
</font>    
<p>

<%  if (errors) { %>
    <font size="-1" color="#990000">
    <i><%= errorMessage %></i>
    </font>
    <p>
<%  } %>

<script language="JavaScript" type="text/javascript">
<!--
var checked = false;
function checkPost() {
    if (!checked) {
        checked = true;
        return true;
    }
    return false;
}
//-->
</script>

<form action="post.jsp" method="post" name="postForm" onsubmit="return checkPost();">
<input type="hidden" name="doPost" value="true">
<input type="hidden" name="reply" value="<%=reply%>">
<input type="hidden" name="forum" value="<%=forumID%>">
<input type="hidden" name="thread" value="<%=threadID%>">
<input type="hidden" name="message" value="<%=messageID%>">
<%	if (preview && !errors) { %>
<input type="hidden" name="fromPreview" value="true">
<%	} %>

<%	if (!preview) {
		// Add an "Re: " to the subject if this is a reply
		if (reply) {
			subject = parentMessage.getSubject();
			if (!subject.startsWith("Re: ")) {
				subject = "Re: " + subject;
			}
		}
%>
<table cellpadding="4" cellspacing="0" border="0">
<tr>
	<td align="right">
	<font size="-1">Subject</font>
	</td>
	<td>
	<input type="text" name="subject" value="<%= ((subject!=null)?subject:"") %>" size="40" maxlength="75">
	</td>
</tr>
<%	if (reply) { %>
<tr>
	<td>&nbsp;</td>
	<td>
		<table cellpadding="0" cellspacing="0" border="0">
		<td>
            <font size="-1">
            <a href="post.jsp?forum=<%=forumID%>&thread=<%=threadID%>&message=<%=messageID%>&reply=<%=reply%>&quote=true"
    		>[quote original]</a>
            </font>
		</td>
		</table>
	</td>

</tr>
<%	} %>

<script language="JavaScript" type="text/javascript">
<!--
function tag(el, theTag) {
    if (theTag == 'b') {
        el.value += "[b][/b]";
    } else if (theTag == 'i') {
        el.value += "[i][/i]";
    } else if (theTag == 'u') {
        el.value += "[u][/u]";
    } else if (theTag == 'code') {
        el.value += "\n[code]\n// your java code here\n[/code]";
    } else if (theTag == 'image') {
        var url = prompt("Please enter an image URL","http://");
        if (url != null) {
            el.value += "[img]" + url + "[/img]";
        }
    } else if (theTag == 'link') {
        var url = prompt("Please enter a link URL","http://");
        var text = prompt("Please enter the text of the link");
        if (url != null) {
            if (text != null) {
                el.value += "[link=" + url + "]" + text + "[/link]";
            } else {
                el.value += "[link]" + url + "[/link]";
            }
        }
    }
}
//-->
</script>
<tr>
    <td>&nbsp;</td>
	<td>
        <table cellpadding="0" cellspacing="0" border="0">
        <tr><td>
        	<%= printBox("<b>B</b>","javascript:tag(document.postForm.body,'b')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            <td><img src="images/blank.gif" width="5" height="1" border="0"></td>
            <td>
            <%= printBox("<i>i</i>","javascript:tag(document.postForm.body,'i')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            <td><img src="images/blank.gif" width="5" height="1" border="0"></td>
            <td>
            <%= printBox("<u>U</u>","javascript:tag(document.postForm.body,'u')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            <td><img src="images/blank.gif" width="5" height="1" border="0"></td>
            <td>
            <%= printBox("<u>code</u>","javascript:tag(document.postForm.body,'code')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            <%--
            <td><img src="images/blank.gif" width="5" height="1" border="0"></td>
            <td>
            <%= printBox("image","javascript:tag(document.postForm.body,'image')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            <td><img src="images/blank.gif" width="5" height="1" border="0"></td>
            <td>
            <%= printBox("link","javascript:tag(document.postForm.body,'link')",buttonBorderColor,buttonBgColor,buttonBorderColorHover,buttonBgColorHover,"") %>
            </td>
            --%>
        </tr>
        </table>
	</td>
</tr>
<tr>
	<td valign="top" align="right">
    <font size="-1">
	<%	if (reply) { %>
	Your Reply
	<%	} else { %>
	Message:
	<%	} %>
    </font>
	</td>
<%	if (quote) {
		String pBody = parentMessage.getUnfilteredBody();
		if( pBody != null ) {
			body = SkinUtils.quoteOriginal(pBody,"&gt; ",54);
			body += "\n";
		}
	}
%>
	<td>
	<textarea name="body" wrap="virtual" cols="55" rows="10"><%= ((body!=null)?body:"") %></textarea>
	</td>
</tr>
<tr>
	<td>&nbsp;</td>
	<td>
	<%	if (!preview) { %>
	<input type="submit" value="Preview" name="postButton">
	<%	} else { %>
	<input type="submit" value="Go Back/Edit" name="postButton">
	<%	} %>
	&nbsp;
	<input type="submit" value="Post!" name="postButton">
	</td>
</tr>
</table>
<script language="JavaScript" type="text/javascript">
<!--
<%	if (subject == null) { %>
	document.postForm.subject.focus();
<%	} else { %>
	document.postForm.body.focus();
<%	} %>
//-->
</script>

<%	} else if (preview && !errors) { // end if(!preview)
		// Message Preview:
%>

<%  if (!reply) { %>
    <b><%= newMessage.getSubject() %></b>
<p>
<%  } %>

<%	User author = newMessage.getUser();
%>
<%	if (!reply) { // new root message %>

<table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="98%" align="center">
<tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="4" cellspacing="1" border="0" width="100%">
    <tr bgcolor="<%= tableRowColor2 %>">
        <td width="1%" rowspan="2" valign="top">
        <table cellpadding="0" cellspacing="0" border="0" width="140">
        <tr><td>
            <font size="-1">
		<%	if (author == null) { %>
			<i>Guest</i>
		<%	} else { %>
			<a href="profile.jsp?user=<%= author.getID() %>"
             ><b><%= author.getUsername() %></b></a>
            <br><br>
            Posts: <%= userManager.userMessageCount(author) %>
            <br>
            From:
            <br>
            Since: <%= shortDateFormatter.format(author.getCreationDate()) %>
            <br>
		<%	} %>
            </font>
            </td>
        </tr>
        </table>
        </td>
        <td width="98%">
        <font size="-1">
        Date Posted: <%= SkinUtils.formatDate(request,response,pageUser,newMessage.getCreationDate()) %>
        </font>
		</td>
        <td width="1%" nowrap align="center">
        <font size="-1" color="#666666">
        <b>&raquo; Reply</b>
        </font>
        </td>
    </tr>
    <tr bgcolor="<%= tableRowColor2 %>">
        <td width="99%" colspan="3" valign="top">
        <font size="-1">
<%= newMessage.getBody() %>
        </font>
		<p>
        </td>
    </tr>
    </table>
</td></tr>
</table><br>

<%	} else { // if reply %>

<table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="98%" align="center">
<tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="4" cellspacing="1" border="0" width="100%">
    <tr bgcolor="<%= tableRowColor1 %>">
        <td width="1%" rowspan="2" valign="top">
        <table cellpadding="0" cellspacing="0" border="0" width="140">
        <tr><td>
            <font size="-1">
		<%	if (author == null) { %>
			<i>Guest</i>
		<%	} else { %>
			<a href="profile.jsp?user=<%= author.getID() %>"
             ><b><%= author.getUsername() %></b></a>
            <br><br>
            Posts: <%= userManager.userMessageCount(author) %>
            <br>
            From:
            <br>
            Since: <%= shortDateFormatter.format(author.getCreationDate()) %>
            <br>
		<%	} %>
            </font>
            </td>
        </tr>
        </table>
        </td>
        <td width="98%">
        <font size="-1">
        <b><%= newMessage.getSubject() %></b>
        <br>
        Date Posted: <%= SkinUtils.formatDate(request,response,pageUser,newMessage.getCreationDate()) %>
        </font>
		</td>
        <td width="1%" nowrap align="center">
        <font size="-1" color="#666666">
        <b>&raquo; Reply</b>
        </font>
        </td>
    </tr>
    <tr bgcolor="<%= tableRowColor1 %>">
        <td width="99%" colspan="3" valign="top">
        <font size="-1">
<%= newMessage.getBody() %>
        </font>
		<p>
        </td>
    </tr>
    </table>
</td></tr>
</table><br>

<%	} %>
<p>
<%	if (!preview) { %>
<input type="submit" value="Preview" name="postButton">
<%	} else { %>
<input type="submit" value="Go Back/Edit" name="postButton">
<%	} %>
&nbsp;
<input type="submit" value="Post!" name="postButton">

<%	} // end else %>

</form>

<p>

<%	if (reply && !preview) { %>

<font size="-1">
<b>Original Message</b>
</font>
<p>

<%	User author = parentMessage.getUser();
	long parentForumID = parentMessage.getForumThread().getForum().getID();
	long parentThreadID = parentMessage.getForumThread().getID();
	long parentID = parentMessage.getID();
	boolean parentIsRoot = (parentMessage.getForumThread().getRootMessage().getID() == parentID);
%>

	<%	if (parentIsRoot) { %>
<table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="98%" align="center">
<tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="4" cellspacing="1" border="0" width="100%">
    <tr bgcolor="<%= tableRowColor2 %>">
        <td width="1%" rowspan="2" valign="top">
        <table cellpadding="0" cellspacing="0" border="0" width="140">
        <tr><td>
            <font size="-1">
		<%	if (author == null) { %>
			<i>Guest</i>
		<%	} else { %>
			<a href="profile.jsp?user=<%= author.getID() %>"
             ><b><%= author.getUsername() %></b></a>
            <br><br>
            Posts: <%= userManager.userMessageCount(author) %>
            <br>
            From:
            <br>
            Since: <%= shortDateFormatter.format(author.getCreationDate()) %>
            <br>
		<%	} %>
            </font>
            </td>
        </tr>
        </table>
        </td>
        <td width="98%">
        <font size="-1">
        Date Posted: <%= SkinUtils.formatDate(request,response,pageUser,parentMessage.getCreationDate()) %>
        </font>
		</td>
        <td width="1%" nowrap align="center">
        <font size="-1" color="#666666">
        <b>&raquo; Reply</b>
        </font>
        </td>
    </tr>
    <tr bgcolor="<%= tableRowColor2 %>">
        <td width="99%" colspan="3" valign="top">
        <font size="-1">
<%= parentMessage.getBody() %>
        </font>
		<p>
        </td>
    </tr>
    </table>
</td></tr>
</table><br>
	<%	} else { // parent isn't root %>
<table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="98%" align="center">
<tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="4" cellspacing="1" border="0" width="100%">
    <tr bgcolor="<%= tableRowColor1 %>">
        <td width="1%" rowspan="2" valign="top">
        <table cellpadding="0" cellspacing="0" border="0" width="140">
        <tr><td>
            <font size="-1">
		<%	if (author == null) { %>
			<i>Guest</i>
		<%	} else { %>
			<a href="profile.jsp?user=<%= author.getID() %>"
             ><b><%= author.getUsername() %></b></a>
            <br><br>
            Posts: <%= userManager.userMessageCount(author) %>
            <br>
            From:
            <br>
            Since: <%= shortDateFormatter.format(author.getCreationDate()) %>
            <br>
		<%	} %>
            </font>
            </td>
        </tr>
        </table>
        </td>
        <td width="98%">
        <font size="-1">
        Date Posted: <%= SkinUtils.formatDate(request,response,pageUser,parentMessage.getCreationDate()) %>
        </font>
		</td>
        <td width="1%" nowrap align="center">
        <font size="-1" color="#666666">
        <b>&raquo; Reply</b>
        </font>
        </td>
    </tr>
    <tr bgcolor="<%= tableRowColor1 %>">
        <td width="99%" colspan="3" valign="top">
        <font size="-1">
<%= parentMessage.getBody() %>
        </font>
		<p>
        </td>
    </tr>
    </table>
</td></tr>
</table><br>
	<% } // end else parent message isn't root message %>

<%	} // end if reply %>

<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
    <td align="right">
    <a href="http://www.jivesoftware.com/poweredby/" target="_blank"
    ><img src="images/powered_by_jive.gif" width="100" height="30" alt="Powered by Jive" border="0"></a>
    </td>
</tr>
</table>

<%@ include file="include/branding/footer.jsp" %>

<%@ include file="include/footer.jsp" %>