Unravel some of the spaghetti logic.

This commit is contained in:
j2blake 2011-05-25 16:31:53 +00:00
parent ff35554bf8
commit 563593981f

View file

@ -56,150 +56,116 @@ public class ContactMailController extends FreemarkerHttpServlet {
@Override @Override
protected ResponseValues processRequest(VitroRequest vreq) { protected ResponseValues processRequest(VitroRequest vreq) {
if (!FreemarkerEmailFactory.isConfigured(vreq)) {
return errorNoSmtpServer();
}
String templateName = null; String[] recipients = figureRecipients(vreq);
Map<String, Object> body = new HashMap<String, Object>(); if (recipients.length == 0) {
return errorNoRecipients();
}
ApplicationBean appBean = vreq.getAppBean(); String webusername = nonNullAndTrim(vreq, WEB_USERNAME_PARAM);
String webuseremail = nonNullAndTrim(vreq, WEB_USEREMAIL_PARAM);
String comments = nonNullAndTrim(vreq, COMMENTS_PARAM);
String formType = nonNullAndTrim(vreq, "DeliveryType");
String statusMsg = null; // holds the error status if (validateInput(webusername, webuseremail, comments) != null) {
return errorParametersNotValid();
}
if (!FreemarkerEmailFactory.isConfigured(vreq)) { String spamReason = checkForSpam(comments, formType);
body.put("errorMessage", if (spamReason != null) {
"This application has not yet been configured to send mail. " + return errorSpam();
"Email properties must be specified in the configuration properties file."); }
templateName = TEMPLATE_ERROR;
}
else { return processValidRequest(vreq, webusername, webuseremail, recipients, comments);
}
String webusername = vreq.getParameter(WEB_USERNAME_PARAM); private String[] figureRecipients(VitroRequest vreq) {
String webuseremail = vreq.getParameter(WEB_USEREMAIL_PARAM); String contactMailAddresses = vreq.getAppBean().getContactMail().trim();
String comments = vreq.getParameter(COMMENTS_PARAM); if ((contactMailAddresses == null) || contactMailAddresses.isEmpty()) {
return new String[0];
}
String validationMessage = validateInput(webusername, webuseremail, return contactMailAddresses.split(",");
comments); }
if (validationMessage != null) { private ResponseValues processValidRequest(VitroRequest vreq,
// rjy7 We should reload the form, not go to the error page! String webusername, String webuseremail, String[] recipients,
body.put("errorMessage", String comments) throws Error {
"Invalid submission"); String statusMsg = null; // holds the error status
templateName = TEMPLATE_ERROR;
}
else { ApplicationBean appBean = vreq.getAppBean();
webusername = webusername.trim(); String deliveryfrom = "Message from the " + appBean.getApplicationName() + " Contact Form";
webuseremail = webuseremail.trim();
comments = comments.trim();
String spamReason = null; String originalReferer = getOriginalRefererFromSession(vreq);
String originalReferer = (String) vreq.getSession().getAttribute("contactFormReferer"); Configuration config = (Configuration) vreq.getAttribute("freemarkerConfig");
if (originalReferer != null) { String msgText = composeEmail(webusername, webuseremail, comments,
vreq.getSession().removeAttribute("contactFormReferer"); deliveryfrom, originalReferer, vreq.getRemoteAddr(), config, vreq);
/* does not support legitimate clients that don't send the Referer header
String referer = request.getHeader("Referer");
if (referer == null ||
(referer.indexOf("comments") <0
&& referer.indexOf("correction") <0) ) {
spamReason = "The form was not submitted from the " +
"Contact Us or Corrections page.";
statusMsg = SPAM_MESSAGE;
}
*/
} else {
originalReferer = "none";
}
if (spamReason == null) { try {
spamReason = checkForSpam(comments); // Write the email to a backup file
if (spamReason != null) { FileWriter fw = new FileWriter(getServletContext().getRealPath(EMAIL_BACKUP_FILE_PATH),true);
statusMsg = SPAM_MESSAGE; PrintWriter outFile = new PrintWriter(fw);
} writeBackupCopy(outFile, msgText, config, vreq);
}
String formType = vreq.getParameter("DeliveryType"); Session s = FreemarkerEmailFactory.getEmailSession(vreq);
String[] deliverToArray = null;
int recipientCount = 0;
String deliveryfrom = null;
if ("contact".equals(formType)) { try {
if (appBean.getContactMail() == null || appBean.getContactMail().trim().length()==0) { sendMessage(s, webuseremail, webusername, recipients, deliveryfrom, msgText);
log.error("No contact mail address defined"); } catch (AddressException e) {
throw new Error( statusMsg = "Please supply a valid email address.";
"To establish the Contact Us mail capability the system administrators must " outFile.println( statusMsg );
+ "specify an email address."); outFile.println( e.getMessage() );
} else { } catch (SendFailedException e) {
deliverToArray = appBean.getContactMail().split(","); statusMsg = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]";
} outFile.println( statusMsg );
deliveryfrom = "Message from the " + appBean.getApplicationName() + " Contact Form"; outFile.println( e.getMessage() );
} else { } catch (MessagingException e) {
deliverToArray = appBean.getContactMail().split(","); statusMsg = "The system was unable to deliver your mail. Please try again later. [MESSAGING]";
statusMsg = SPAM_MESSAGE ; outFile.println( statusMsg );
spamReason = "The form specifies no delivery type."; outFile.println( e.getMessage() );
} e.printStackTrace();
recipientCount=(deliverToArray == null) ? 0 : deliverToArray.length; }
if (recipientCount == 0) {
log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\"");
throw new Error(
"To establish the Contact Us mail capability the system administrators must "
+ "specify at least one email address.");
}
Configuration config = (Configuration) vreq.getAttribute("freemarkerConfig"); outFile.close();
String msgText = composeEmail(webusername, webuseremail, comments, }
deliveryfrom, originalReferer, vreq.getRemoteAddr(), config, vreq); catch (IOException e){
log.error("Can't open file to write email backup");
}
// Write the email to a backup file if (statusMsg == null) {
try { // Message was sent successfully
FileWriter fw = new FileWriter(getServletContext().getRealPath(EMAIL_BACKUP_FILE_PATH),true); return new TemplateResponseValues(TEMPLATE_CONFIRMATION);
PrintWriter outFile = new PrintWriter(fw); } else {
writeBackupCopy(outFile, msgText, spamReason, config, vreq); Map<String, Object> body = new HashMap<String, Object>();
body.put("errorMessage", statusMsg);
return new TemplateResponseValues(TEMPLATE_ERROR, body);
}
}
Session s = FreemarkerEmailFactory.getEmailSession(vreq); private String getOriginalRefererFromSession(VitroRequest vreq) {
try { String originalReferer = (String) vreq.getSession().getAttribute("contactFormReferer");
if (originalReferer != null) {
if (spamReason == null) { vreq.getSession().removeAttribute("contactFormReferer");
sendMessage(s, webuseremail, webusername, deliverToArray, deliveryfrom, /* does not support legitimate clients that don't send the Referer header
recipientCount, msgText); String referer = request.getHeader("Referer");
} if (referer == null ||
(referer.indexOf("comments") <0
} catch (AddressException e) { && referer.indexOf("correction") <0) ) {
statusMsg = "Please supply a valid email address."; spamReason = "The form was not submitted from the " +
outFile.println( statusMsg ); "Contact Us or Corrections page.";
outFile.println( e.getMessage() ); statusMsg = SPAM_MESSAGE;
} catch (SendFailedException e) { }
statusMsg = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]"; */
outFile.println( statusMsg ); } else {
outFile.println( e.getMessage() ); originalReferer = "none";
} catch (MessagingException e) { }
statusMsg = "The system was unable to deliver your mail. Please try again later. [MESSAGING]"; return originalReferer;
outFile.println( statusMsg ); }
outFile.println( e.getMessage() );
e.printStackTrace();
}
outFile.flush();
outFile.close();
}
catch (IOException e){
log.error("Can't open file to write email backup");
}
// Message was sent successfully
if (statusMsg == null && spamReason == null) {
templateName = TEMPLATE_CONFIRMATION;
} else {
body.put("errorMessage", statusMsg);
templateName = TEMPLATE_ERROR;
}
}
}
return new TemplateResponseValues(templateName, body);
}
/** Intended to mangle url so it can get through spam filtering /** Intended to mangle url so it can get through spam filtering
* http://host/dir/servlet?param=value -> host: dir/servlet?param=value */ * http://host/dir/servlet?param=value -> host: dir/servlet?param=value */
@ -236,18 +202,13 @@ public class ContactMailController extends FreemarkerHttpServlet {
} }
private void writeBackupCopy(PrintWriter outFile, String msgText, private void writeBackupCopy(PrintWriter outFile, String msgText,
String spamReason, Configuration config, HttpServletRequest request) { Configuration config, HttpServletRequest request) {
Map<String, Object> backup = new HashMap<String, Object>(); Map<String, Object> backup = new HashMap<String, Object>();
String template = TEMPLATE_BACKUP; String template = TEMPLATE_BACKUP;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
backup.put("datetime", cal.getTime().toString()); backup.put("datetime", cal.getTime().toString());
if (spamReason != null) {
backup.put("spamReason", spamReason);
}
backup.put("msgText", msgText); backup.put("msgText", msgText);
try { try {
@ -261,8 +222,7 @@ public class ContactMailController extends FreemarkerHttpServlet {
} }
private void sendMessage(Session s, String webuseremail, String webusername, private void sendMessage(Session s, String webuseremail, String webusername,
String[] deliverToArray, String deliveryfrom, int recipientCount, String[] recipients, String deliveryfrom, String msgText)
String msgText)
throws AddressException, SendFailedException, MessagingException { throws AddressException, SendFailedException, MessagingException {
// Construct the message // Construct the message
MimeMessage msg = new MimeMessage( s ); MimeMessage msg = new MimeMessage( s );
@ -278,14 +238,11 @@ public class ContactMailController extends FreemarkerHttpServlet {
} }
// Set the recipient address // Set the recipient address
InternetAddress[] address=new InternetAddress[recipients.length];
if (recipientCount>0){ for (int i=0; i<recipients.length; i++){
InternetAddress[] address=new InternetAddress[recipientCount]; address[i] = new InternetAddress(recipients[i]);
for (int i=0; i<recipientCount; i++){
address[i] = new InternetAddress(deliverToArray[i]);
}
msg.setRecipients( Message.RecipientType.TO, address );
} }
msg.setRecipients( Message.RecipientType.TO, address );
// Set the subject and text // Set the subject and text
msg.setSubject( deliveryfrom ); msg.setSubject( deliveryfrom );
@ -300,18 +257,23 @@ public class ContactMailController extends FreemarkerHttpServlet {
} }
private String nonNullAndTrim(HttpServletRequest req, String key) {
String value = req.getParameter(key);
return (value == null) ? "" : value.trim();
}
private String validateInput(String webusername, String webuseremail, private String validateInput(String webusername, String webuseremail,
String comments) { String comments) {
if( webusername == null || "".equals(webusername.trim()) ){ if( webusername.isEmpty() ){
return "A proper webusername field was not found in the form submitted."; return "A proper webusername field was not found in the form submitted.";
} }
if( webuseremail == null || "".equals(webuseremail.trim()) ){ if( webuseremail.isEmpty() ){
return "A proper webuser email field was not found in the form submitted."; return "A proper webuser email field was not found in the form submitted.";
} }
if (comments==null || "".equals(comments.trim())) { if (comments.isEmpty()) {
return "The proper comments field was not found in the form submitted."; return "The proper comments field was not found in the form submitted.";
} }
@ -319,11 +281,14 @@ public class ContactMailController extends FreemarkerHttpServlet {
} }
/** /**
* @param request
* @return null if message not judged to be spam, otherwise a String * @return null if message not judged to be spam, otherwise a String
* containing the reason the message was flagged as spam. * containing the reason the message was flagged as spam.
*/ */
private String checkForSpam(String comments) { private String checkForSpam(String comments, String formType) {
/* If the form doesn't specify a delivery type, treat as spam. */
if (!"contact".equals(formType)) {
return "The form specifies no delivery type.";
}
/* if this blog markup is found, treat comment as blog spam */ /* if this blog markup is found, treat comment as blog spam */
if ( if (
@ -342,4 +307,34 @@ public class ContactMailController extends FreemarkerHttpServlet {
return null; return null;
} }
private ResponseValues errorNoSmtpServer() {
Map<String, Object> body = new HashMap<String, Object>();
body.put("errorMessage",
"This application has not yet been configured to send mail. " +
"Email properties must be specified in the configuration properties file.");
return new TemplateResponseValues(TEMPLATE_ERROR, body);
}
private ResponseValues errorNoRecipients() {
Map<String, Object> body = new HashMap<String, Object>();
body.put("errorMessage", "To establish the Contact Us mail capability "
+ "the system administrators must specify "
+ "at least one email address.");
return new TemplateResponseValues(TEMPLATE_ERROR, body);
}
private ResponseValues errorParametersNotValid() {
// rjy7 We should reload the form, not go to the error page!
Map<String, Object> body = new HashMap<String, Object>();
body.put("errorMessage", "Invalid submission");
return new TemplateResponseValues(TEMPLATE_ERROR, body);
}
private ResponseValues errorSpam() {
Map<String, Object> body = new HashMap<String, Object>();
body.put("errorMessage", SPAM_MESSAGE);
return new TemplateResponseValues(TEMPLATE_ERROR, body);
}
} }