* anti-abuse upgrade: filters now stored in the database (experimental)
[mir.git] / source / mircoders / localizer / basic / MirBasicEmailArticleHandler.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mircoders.localizer.basic;
31
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.io.StringWriter;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Locale;
39 import java.util.Map;
40 import java.util.ArrayList;
41
42 import mir.config.MirPropertiesConfiguration;
43 import mir.generator.Generator;
44 import mir.generator.GeneratorHelper;
45 import mir.log.LoggerWrapper;
46 import mir.session.Request;
47 import mir.session.Response;
48 import mir.session.Session;
49 import mir.session.SessionExc;
50 import mir.session.SessionFailure;
51 import mir.session.SessionHandler;
52 import mir.session.ValidationHelper;
53 import mir.session.HTTPAdapters.HTTPRequestAdapter;
54 import mir.util.StringRoutines;
55 import mircoders.entity.EntityContent;
56 import mircoders.global.CacheKey;
57 import mircoders.global.MirGlobal;
58 import mircoders.module.ModuleContent;
59
60 import org.apache.commons.net.smtp.SMTPClient;
61 import org.apache.commons.net.smtp.SMTPReply;
62
63
64 /**
65  *
66  * <p>Title: Tenative session handler for emailing postings </p>
67  * <p>Description: </p>
68  * <p>Copyright: Copyright (c) 2003</p>
69  * <p>Company: </p>
70  * @author john
71  * @version 1.0
72  */
73
74
75 public class MirBasicEmailArticleHandler implements SessionHandler {
76   protected LoggerWrapper logger;
77   protected MirPropertiesConfiguration configuration;
78
79   public MirBasicEmailArticleHandler() {
80     logger = new LoggerWrapper("Localizer.EmailArticle");
81     try {
82       configuration = MirPropertiesConfiguration.instance();
83     }
84     catch (Throwable t) {
85       logger.fatal("Cannot load configuration: " + t.toString());
86
87       throw new RuntimeException("Cannot load configuration: " + t.toString());
88     }
89   }
90
91   public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
92     if (aSession.getAttribute("initialRequest") == null) {
93       aSession.setAttribute("initialRequest", "no");
94       initialRequest(aRequest, aSession, aResponse);
95     }
96     else {
97       subsequentRequest(aRequest, aSession, aResponse);
98     }
99   }
100
101   protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
102     initializeSession(aRequest, aSession);
103     makeInitialResponse(aRequest, aSession, aResponse);
104   }
105
106   protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
107     /* do nothing for now */
108
109   }
110
111   protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
112     /* if you do not supply an aid to this handler, it should return an error page */
113     /* if you supply a non-functioning/non-published  aid to this handler, it should return an error page, but at a
114        later stage, because we don't check the db until we are potentially populating the cache*/
115     /* otherwise you get to address an article and add some comments */
116     String articleID = aRequest.getParameter("mail_aid");
117     if (articleID == null){
118       throw new SessionExc("makeInitialResponse: article id not set!");
119     }
120     else {
121       aSession.setAttribute("email.aid",articleID);
122       aResponse.setResponseValue("errors", null);
123
124       String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
125       aResponse.setResponseValue("mail_language",mail_language);
126       aResponse.setResponseValue("mail_to","");
127       aResponse.setResponseValue("mail_from","");
128       aResponse.setResponseValue("mail_from_name","");
129       aResponse.setResponseValue("mail_comment","");
130
131       aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
132
133
134     }
135   }
136
137   protected boolean shouldSendMail(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
138     if (validate(aRequest,aSession,aResponse,aValidationErrors)){
139       String to=aRequest.getParameter("mail_to");
140       if (to.indexOf('@') == -1
141           || to.indexOf('\n') != -1
142           || to.indexOf('\r') != -1
143           || to.indexOf(',') != -1) {
144         throw new SessionExc("Invalid to address"); // we might want to see this in a log, so it is not a validation error
145       }
146       else return true; // go for it
147     }
148     else{
149       return false; //validation failed, but not in a potentially abusive way
150     }
151
152   }
153
154
155
156
157
158   protected boolean validate(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
159
160     if (ValidationHelper.testFieldEntered(aRequest, "mail_to", "validationerror.missing", aValidationErrors))
161       aResponse.setResponseValue("mail_to",aRequest.getParameter("mail_to"));
162     if (ValidationHelper.testFieldEntered(aRequest, "mail_from", "validationerror.missing", aValidationErrors))
163       aResponse.setResponseValue("mail_from",aRequest.getParameter("mail_from"));
164     if (ValidationHelper.testFieldEntered(aRequest, "mail_from_name", "validationerror.missing", aValidationErrors))
165       aResponse.setResponseValue("mail_from_name",aRequest.getParameter("mail_from_name"));
166     if (ValidationHelper.testFieldEntered(aRequest, "mail_language", "validationerror.missing", aValidationErrors))
167       aResponse.setResponseValue("mail_language",aRequest.getParameter("mail_language"));
168
169     return (aValidationErrors==null || aValidationErrors.size() == 0);
170   }
171
172   protected String getEmailText(String aid,String language) throws SessionExc{
173     String theText;
174     CacheKey theCacheKey=new CacheKey("email",aid+language);
175
176     if (MirGlobal.mruCache().hasObject(theCacheKey)){
177       logger.info("fetching email text for article "+aid+" from cache");
178       theText = (String) MirGlobal.mruCache().getObject(theCacheKey);
179     }
180     else {
181       try {
182         ModuleContent contentModule = new ModuleContent();
183         EntityContent contentEnt = (EntityContent) contentModule.getById(aid);
184
185         Map articleData = new HashMap();
186         articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
187         articleData.put("languagecode", language);
188         Map responseData = GeneratorHelper.makeBasicGenerationData(new Locale[] {new Locale(language,""),new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "")},"bundles.open","bundles.open");
189         responseData.put("data",articleData);
190
191         String emailAnArticleTemplate = configuration.getString("Localizer.OpenSession.email.MailTemplate");
192
193         Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(emailAnArticleTemplate);
194
195         StringWriter theEmailStringWriter = new StringWriter();
196         PrintWriter theEmailPrintWriter = new PrintWriter(theEmailStringWriter);
197         generator.generate(theEmailPrintWriter, responseData, logger);
198
199         theEmailStringWriter.close();
200
201         theText = theEmailStringWriter.toString();
202         MirGlobal.mruCache().storeObject(theCacheKey, theText);
203       }
204       catch (Throwable e) {
205         throw new SessionExc("Couldn't get content for article " + aid + language + ": " + e.getMessage());
206       }
207     }
208
209     return theText;
210   }
211
212   protected String getExtraEmailHeaders(Request aRequest,String to,String from) throws SessionExc {
213
214     String headers = "To: " + to + "\nReply-To: "+ from+"\n";;
215     if (configuration.getString("Localizer.OpenSession.email.includeSenderIP","no").equals("yes"))
216       headers= headers+"X-Originating-IP: "+ ((HTTPRequestAdapter)aRequest).getRequest().getRemoteAddr() + "\n";
217
218     return headers;
219   }
220
221   protected String interpolateComment(String emailText,String comment,String from_name,String language) throws SessionExc{
222     if (comment != null) {
223       String commentTextToInsert =
224           MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new String[] { language }).
225             getValue("email.comment.intro" , Collections.singletonList(from_name)) + "\n";
226
227       try {
228         emailText = StringRoutines.performRegularExpressionReplacement(emailText, "!COMMENT!", commentTextToInsert);
229       }
230       catch (Throwable e) {
231         throw new SessionExc("Problem doing regular expression replacement :" + e.toString());
232       }
233     }
234     else {
235       try {
236         emailText = StringRoutines.performRegularExpressionReplacement(emailText, "!COMMENT!", "");
237       }
238       catch (Throwable e) {
239         throw new SessionExc("Problem doing regular expression replacement " + e.toString());
240       }
241     }
242     return emailText;
243   }
244
245   protected boolean doTheSMTP(String aMessage,String aTo,String aFrom) throws SessionExc{
246    SMTPClient client=new SMTPClient();
247    try {
248      int reply;
249      client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
250      reply = client.getReplyCode();
251
252      if (!SMTPReply.isPositiveCompletion(reply)) {
253        client.disconnect();
254         throw new SessionExc("SMTP server refused connection.");
255      }
256      boolean trueIfItWorked = client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), aTo, aMessage);
257      client.disconnect();
258      // mission accomplished??
259      if (! trueIfItWorked)
260        throw new SessionExc(client.getReplyString());
261      else
262        return trueIfItWorked;
263    }
264    catch(IOException e) {
265       if(client.isConnected()) {
266         try {
267           client.disconnect();
268         } catch(IOException f) {
269           // do nothing
270         }
271       }
272       throw new SessionExc(e.getMessage());
273    }
274   }
275
276   protected boolean sendMail(Request aRequest,Session aSession,Response aResponse) throws SessionExc,SessionFailure {
277     String to=aRequest.getParameter("mail_to");
278     String from=aRequest.getParameter("mail_from");
279     String from_name=aRequest.getParameter("mail_from_name");
280     String language=aRequest.getParameter("mail_language");
281     String comment=aRequest.getParameter("mail_comment");
282
283     String theEmailText=getEmailText((String) aSession.getAttribute("email.aid"),language);
284     String headers=getExtraEmailHeaders(aRequest,to,from);
285     theEmailText=interpolateComment(theEmailText,comment,from_name,language);
286     String message=headers+theEmailText;  // the space between headers and content is in the template
287
288     return doTheSMTP(message,to,from);
289
290   }
291
292
293   protected void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
294     List validationErrors = new ArrayList();
295     if (shouldSendMail(aRequest,aSession,aResponse,validationErrors)){
296
297       sendMail(aRequest,aSession,aResponse);
298       aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.DoneTemplate"));
299     }
300     else {
301       aResponse.setResponseValue("mail_comment",aRequest.getParameter("mail_comment"));  //everything else is required
302       aResponse.setResponseValue("errors",validationErrors);
303       aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
304     }
305
306   }
307
308       /*
309       String mail_language = aRequest.getParameter("mail_language");
310       if (mail_language == null)
311         mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
312
313       aResponse.setResponseValue("mail_language",mail_language);
314       */
315
316
317
318
319 }