bug fix...initialize all template variables for the prepare email template
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.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
31 package mircoders.servlet;
32
33 import java.io.ByteArrayOutputStream;
34 import java.io.File;
35 import java.io.FileNotFoundException;
36 import java.io.FileReader;
37 import java.io.IOException;
38 import java.io.PrintWriter;
39 import java.io.StringWriter;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.Enumeration;
44 import java.util.GregorianCalendar;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.ListIterator;
49 import java.util.Locale;
50 import java.util.Map;
51 import java.util.Random;
52 import java.util.Set;
53 import java.util.Vector;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import javax.servlet.http.HttpSession;
57 import javax.servlet.http.HttpUtils;
58
59 import org.apache.commons.fileupload.FileItem;
60 import org.apache.commons.net.smtp.SMTPClient;
61 import org.apache.commons.net.smtp.SMTPReply;
62 import org.apache.lucene.analysis.standard.StandardAnalyzer;
63 import org.apache.lucene.document.Document;
64 import org.apache.lucene.queryParser.QueryParser;
65 import org.apache.lucene.search.Hits;
66 import org.apache.lucene.search.IndexSearcher;
67 import org.apache.lucene.search.Query;
68 import org.apache.lucene.search.Searcher;
69 import org.apache.struts.util.MessageResources;
70 import gnu.regexp.RE;
71 import gnu.regexp.REMatch;
72
73 import mir.entity.Entity;
74 import mir.generator.Generator;
75 import mir.log.LoggerWrapper;
76 import mir.misc.StringUtil;
77 import mir.servlet.ServletModule;
78 import mir.servlet.ServletModuleExc;
79 import mir.servlet.ServletModuleFailure;
80 import mir.servlet.ServletModuleUserExc;
81 import mir.session.HTTPAdapters;
82 import mir.session.Request;
83 import mir.session.Session;
84 import mir.session.SessionHandler;
85 import mir.session.SimpleResponse;
86 import mir.session.UploadedFile;
87 import mir.storage.StorageObjectFailure;
88 import mir.util.ExceptionFunctions;
89 import mir.util.HTTPParsedRequest;
90 import mir.util.HTTPRequestParser;
91 import mir.util.StringRoutines;
92 import mircoders.entity.EntityComment;
93 import mircoders.entity.EntityContent;
94 import mircoders.global.CacheKey;
95 import mircoders.global.MirGlobal;
96 import mircoders.media.MediaUploadProcessor;
97 import mircoders.module.ModuleComment;
98 import mircoders.module.ModuleContent;
99 import mircoders.module.ModuleImages;
100 import mircoders.module.ModuleMediaType;
101 import mircoders.module.ModuleTopics;
102 import mircoders.pdf.PDFGenerator;
103 import mircoders.search.AudioSearchTerm;
104 import mircoders.search.ContentSearchTerm;
105 import mircoders.search.ImagesSearchTerm;
106 import mircoders.search.KeywordSearchTerm;
107 import mircoders.search.TextSearchTerm;
108 import mircoders.search.TopicSearchTerm;
109 import mircoders.search.UnIndexedSearchTerm;
110 import mircoders.search.VideoSearchTerm;
111 import mircoders.storage.DatabaseComment;
112 import mircoders.storage.DatabaseContent;
113 import mircoders.storage.DatabaseContentToMedia;
114 import mircoders.storage.DatabaseContentToTopics;
115 import mircoders.storage.DatabaseImages;
116 import mircoders.storage.DatabaseLanguage;
117 import mircoders.storage.DatabaseTopics;
118
119 /*
120  *  ServletModuleOpenIndy -
121  *   is the open-access-servlet, which is responsible for
122  *    adding comments to articles &
123  *    open-postings to the newswire
124  *
125  * @author mir-coders group
126  * @version $Id: ServletModuleOpenIndy.java,v 1.87 2003/05/04 23:52:14 john Exp $
127  *
128  */
129
130 public class ServletModuleOpenIndy extends ServletModule
131 {
132
133   private String        commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
134   private String        postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
135   private String        searchResultsTemplate;
136   private String        prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
137   private ModuleContent contentModule;
138   private ModuleComment commentModule;
139   private ModuleImages  imageModule;
140   private ModuleTopics  topicsModule;
141   private String        directOp ="yes";
142   // Singelton / Kontruktor
143   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
144   public static ServletModule getInstance() { return instance; }
145
146   private ServletModuleOpenIndy() {
147     super();
148     try {
149       logger = new LoggerWrapper("ServletModule.OpenIndy");
150
151       commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
152       commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
153       commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
154
155       postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
156       postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
157       postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
158
159       searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
160       prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
161       emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
162       sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
163       directOp = configuration.getString("DirectOpenposting").toLowerCase();
164       commentModule = new ModuleComment(DatabaseComment.getInstance());
165       mainModule = commentModule;
166       contentModule = new ModuleContent(DatabaseContent.getInstance());
167       topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
168       imageModule = new ModuleImages(DatabaseImages.getInstance());
169       defaultAction="addposting";
170     }
171     catch (StorageObjectFailure e) {
172       logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
173     }
174   }
175
176   /**
177    * Method to return an "apology" when open postings are disabled
178    *
179    * @param aRequest
180    * @param aResponse
181    * @throws ServletModuleExc
182    * @throws ServletModuleUserExc
183    * @throws ServletModuleFailure
184    */
185   public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
186     deliver(aRequest, aResponse, (Map) null, null,
187        configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
188   }
189
190   /**
191    *  Method for making a comment
192    */
193
194   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
195     if (MirGlobal.abuse().getOpenPostingDisabled()) {
196       openPostingDisabled(req, res);
197
198       return;
199     }
200
201     String aid = req.getParameter("aid"); // the article id the comment will belong to
202
203     if (aid != null && !aid.equals("")) {
204       try {
205         Map mergeData = new HashMap();
206
207         // onetimepasswd
208         if (MirGlobal.abuse().getOpenPostingPassword()) {
209           String passwd = this.createOneTimePasswd();
210           HttpSession session = req.getSession(false);
211           session.setAttribute("passwd", passwd);
212           mergeData.put("passwd", passwd);
213         }
214         else {
215           mergeData.put("passwd", (String)null);
216         }
217         mergeData.put("aid", aid);
218
219         Map extraInfo = new HashMap();
220         extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
221
222         deliver(req, res, mergeData, extraInfo, commentFormTemplate);
223       }
224       catch (Throwable t) {
225         throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
226       }
227     }
228     else
229       throw new ServletModuleExc("aid not set!");
230   }
231
232   /**
233    *  Method for inserting a comment into the Database and delivering
234    *  the commentDone Page
235    */
236
237   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
238     if (MirGlobal.abuse().getOpenPostingDisabled()) {
239       openPostingDisabled(req, res);
240
241       return;
242     }
243
244     String aid = req.getParameter("to_media"); // the article id the comment will belong to
245     if (aid != null && !aid.equals("")) {
246       // ok, collecting data from form
247       try {
248         Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
249
250         //no html in comments(for now)
251         for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
252           String k = (String) i.next();
253           String v = (String) withValues.get(k);
254
255           withValues.put(k, StringUtil.removeHTMLTags(v));
256         }
257         withValues.put("is_published", "1");
258         withValues.put("to_comment_status", "1");
259         withValues.put("is_html", "0");
260
261         //checking the onetimepasswd
262         HttpSession session = req.getSession(false);
263         String sessionPasswd = (String) session.getAttribute("passwd");
264         if (sessionPasswd != null) {
265           String passwd = req.getParameter("passwd");
266           if (passwd == null || passwd.length() == 0) {
267             throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
268           }
269           if (!sessionPasswd.equals(passwd)) {
270             throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
271           }
272           session.invalidate();
273         }
274
275         String id = mainModule.add(withValues);
276
277         SimpleResponse response = new SimpleResponse();
278         response.setResponseGenerator(commentFormDoneTemplate);
279
280         if (id == null) {
281           deliver(req, res, (Map)null, null, commentFormDupeTemplate);
282         }
283         else {
284           DatabaseContent.getInstance().setUnproduced("id=" + aid);
285
286           try {
287             EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
288             MirGlobal.localizer().openPostings().afterCommentPosting(comment);
289             MirGlobal.abuse().checkComment(
290                 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
291           }
292           catch (Throwable t) {
293             throw new ServletModuleExc(t.getMessage());
294           }
295         }
296
297         // redirecting to url
298         // should implement back to article
299         deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
300       }
301       catch (Throwable e) {
302         throw new ServletModuleFailure(e);
303       }
304     }
305     else
306       throw new ServletModuleExc("aid not set!");
307
308   }
309
310   /**
311    *  Method for delivering the form-Page for open posting
312    */
313
314   public void addposting(HttpServletRequest req, HttpServletResponse res)
315       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
316   {
317     try {
318       if (MirGlobal.abuse().getOpenPostingDisabled()) {
319         openPostingDisabled(req, res);
320
321         return;
322       }
323
324       Map mergeData = new HashMap();
325
326       // onetimepasswd
327       if (MirGlobal.abuse().getOpenPostingPassword()) {
328         String passwd = generateOnetimePassword();
329         HttpSession session = req.getSession(false);
330         session.setAttribute("passwd", passwd);
331         mergeData.put("passwd", passwd);
332       }
333       else {
334         mergeData.put("passwd", (String)null);
335       }
336
337       String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
338       String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
339       String numOfMedia = req.getParameter("medianum");
340
341       if (numOfMedia == null || numOfMedia.equals("")) {
342         numOfMedia = defaultMedia;
343       }
344       else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
345         numOfMedia = maxMedia;
346       }
347
348       int mediaNum = Integer.parseInt(numOfMedia);
349       List mediaFields = new Vector();
350       for (int i = 0; i < mediaNum; i++) {
351         Integer mNum = new Integer(i + 1);
352         mediaFields.add(mNum.toString());
353       }
354       mergeData.put("medianum", numOfMedia);
355       mergeData.put("mediafields", mediaFields);
356       mergeData.put("to_topic", null);
357
358       Map extraInfo = new HashMap();
359       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
360       extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());
361
362       extraInfo.put("topics", topicsModule.getTopicsList());
363       deliver(req, res, mergeData, extraInfo, postingFormTemplate);
364     }
365     catch (Throwable t) {
366       throw new ServletModuleFailure(t);
367     }
368   }
369
370   /**
371    *  Method for inserting an open posting into the Database and delivering
372    *  the postingDone Page
373    */
374
375   public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
376       ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
377     if (MirGlobal.abuse().getOpenPostingDisabled()) {
378       openPostingDisabled(aRequest, aResponse);
379
380       return;
381     }
382
383     try {
384       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
385           aRequest,
386           configuration.getString("Mir.DefaultEncoding"),
387           configuration.getInt("MaxMediaUploadSize")*1024,
388           configuration.getString("TempDir"));
389
390       Map mergeData = new HashMap();
391
392       HttpSession session = aRequest.getSession(false);
393       String sessionPasswd = (String) session.getAttribute("passwd");
394       if (sessionPasswd != null) {
395         String passwd = (String) parsedRequest.getParameter("passwd");
396
397         if (passwd == null || passwd.length() == 0) {
398           throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
399         }
400         if (!sessionPasswd.equals(passwd)) {
401           throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
402         }
403         session.invalidate();
404       }
405
406       if ((((String) parsedRequest.getParameter("title")).length() == 0) ||
407           (((String) parsedRequest.getParameter("description")).length() == 0) ||
408           (((String) parsedRequest.getParameter("content_data")).length() == 0))
409         throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
410
411       List mediaList = new Vector();
412       Iterator i = parsedRequest.getFiles().iterator();
413
414       while (i.hasNext()) {
415         UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
416         Map mediaValues = new HashMap();
417
418         String suffix = file.getFieldName().substring(5); // media${m}
419         logger.debug("media_title" + suffix);
420         String title = parsedRequest.getParameter("media_title" + suffix);
421
422         mediaValues.put("title", StringUtil.removeHTMLTags(title));
423         mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
424         mediaValues.put("to_publisher", "0");
425         mediaValues.put("is_published", "1");
426         mediaValues.put("to_media_folder", "7");
427
428         mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
429       }
430
431       Map withValues = new HashMap();
432       i = DatabaseContent.getInstance().getFields().iterator();
433       while (i.hasNext()) {
434         String field = (String) i.next();
435         String value = parsedRequest.getParameter(field);
436         if (value!=null)
437           withValues.put(field, value);
438       }
439
440
441       for (i = withValues.keySet().iterator(); i.hasNext(); ) {
442         String k = (String) i.next();
443         String v = (String) withValues.get(k);
444
445         if (k.equals("content_data")) {
446           //this doesn't quite work yet, so for now, all html goes
447           //withValues.put(k,StringUtil.approveHTMLTags(v));
448           withValues.put(k, StringUtil.deleteForbiddenTags(v));
449         }
450         else if (k.equals("description")) {
451           String tmp = StringUtil.deleteForbiddenTags(v);
452           withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
453         }
454         else {
455           withValues.put(k, StringUtil.removeHTMLTags(v));
456         }
457       }
458
459       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
460       withValues.put("publish_path",
461                      StringUtil.webdbDate2path( (String) withValues.get("date")));
462       withValues.put("is_produced", "0");
463       withValues.put("is_published", "1");
464       if (directOp.equals("yes"))
465         withValues.put("to_article_type", "1");
466
467       withValues.put("to_publisher", "1");
468
469       // inserting  content into database
470       String cid = contentModule.add(withValues);
471       logger.debug("id: " + cid);
472       //insert was not successfull
473       if (cid == null) {
474         deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
475         return;
476       }
477
478       List topics = parsedRequest.getParameterList("to_topic");
479       if (topics.size() > 0) {
480         try {
481           DatabaseContentToTopics.getInstance().setTopics(cid, topics);
482         }
483         catch (Throwable e) {
484           logger.error("setting content_x_topic failed");
485           contentModule.deleteById(cid);
486           throw new ServletModuleFailure(
487               "smod - openindy :: insposting: setting content_x_topic failed: " +
488               e.toString(), e);
489         }
490       }
491
492       i = mediaList.iterator();
493       while (i.hasNext()) {
494         Entity mediaEnt = (Entity) i.next();
495         DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
496       }
497
498       EntityContent article = (EntityContent) contentModule.getById(cid);
499       try {
500         MirGlobal.abuse().checkArticle(
501             article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
502         MirGlobal.localizer().openPostings().afterContentPosting(article);
503       }
504       catch (Throwable t) {
505         logger.error("Error while post-processing article: " + t.getMessage());
506       }
507       deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
508     }
509     catch (Throwable e) {
510       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
511       Throwable cause = ExceptionFunctions.traceCauseException(e);
512
513       if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
514         throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
515       }
516       throw new ServletModuleFailure(e);
517     }
518   }
519
520   /**
521    * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
522    *   generated into open session urls. Tomcat 3.3 makes it impossible to
523    *   distinguish between sessions that are identified using a url and those
524    *   that are identified using cookies: if both a sessionid cookie and a sessionid
525    *   url are available, tomcat 3.3 pretends the url wasn't there...
526    */
527   private static final String SESSION_REQUEST_KEY="sessionid";
528
529   /**
530    * Dispatch method for open sessions: a flexible extensible and customizable way
531    *   for open access. Can be used for postings, but also for lots of other stuff.
532    *
533    * @param aRequest
534    * @param aResponse
535    * @throws ServletModuleExc
536    * @throws ServletModuleUserExc
537    * @throws ServletModuleFailure
538    */
539
540   public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
541       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
542
543     try {
544       Request request =
545           new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
546               configuration.getString("Mir.DefaultEncoding"),
547               configuration.getInt("MaxMediaUploadSize")*1024,
548               configuration.getString("TempDir")));
549
550       if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
551           !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
552         aRequest.getSession().invalidate();
553
554       Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
555
556       SimpleResponse response = new SimpleResponse(
557           ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},
558              "bundles.open"));
559
560       response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
561
562       SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
563
564       handler.processRequest(request, session, response);
565       ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
566     }
567     catch (Throwable t) {
568       logger.error(t.toString());
569       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
570
571       throw new ServletModuleFailure(t);
572     }
573   }
574
575   /**
576    * Method for preparing and sending a content as an email message
577    */
578
579   public void mail(HttpServletRequest req, HttpServletResponse res)
580       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
581   {
582     String aid = req.getParameter("mail_aid");
583     if (aid == null){
584       throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
585     }
586
587     String to = req.getParameter("mail_to");
588     String from = req.getParameter("mail_from");
589     String from_name = req.getParameter("mail_from_name");
590     String comment = req.getParameter("mail_comment");
591     String mail_language = req.getParameter("mail_language");
592
593     Map mergeData = new HashMap();
594     mergeData.put("mail_to",to);
595     mergeData.put("mail_from",from);
596     mergeData.put("mail_from_name",from_name);
597     mergeData.put("mail_comment",comment);
598     mergeData.put("mail_aid",aid);
599     mergeData.put("mail_language",mail_language);
600     
601     
602     if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
603       deliver(req, res, mergeData, null, prepareMailTemplate);
604     }
605     else {
606       //run checks on to and from and mail_language to make sure no monkey business occurring
607       if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
608         throw new ServletModuleExc("Invalid language");
609       }
610       if (to.indexOf('\n') != -1
611           || to.indexOf('\r') != -1
612           || to.indexOf(',') != -1) {
613         throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
614       }
615       if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
616         throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
617       }
618       
619       CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
620       String theEmailText;
621       
622       if (MirGlobal.mruCache().hasObject(theCacheKey)){
623         logger.info("fetching email text for article "+aid+" from cache");
624         theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
625       }
626       else {
627         EntityContent contentEnt;
628         try{
629           contentEnt = (EntityContent)contentModule.getById(aid);
630           StringWriter theEMailTextWriter=new StringWriter();
631           PrintWriter dest = new PrintWriter(theEMailTextWriter);
632           Map articleData = new HashMap();
633           articleData.put("article",mir.generator.FreemarkerGenerator.makeAdapter(contentEnt));
634           articleData.put("languagecode",mail_language);
635           deliver(dest,req, res, articleData, null, emailAnArticleTemplate,mail_language);
636           theEmailText=theEMailTextWriter.toString();
637           MirGlobal.mruCache().storeObject(theCacheKey,theEmailText);
638         }
639         catch (Throwable e){
640           throw new ServletModuleFailure("Couldn't get content for article "+aid + mail_language + ": " + e.getMessage(), e);
641         }
642       }
643             
644       String content = theEmailText;
645
646
647       // add some headers
648       content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
649       // put in the comment where it should go
650       if (comment != null) {
651         String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
652         try {
653           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
654         }
655         catch (Throwable e){
656           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
657         }
658       }
659       else{
660         try {
661           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
662         }
663         catch (Throwable e){
664           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
665         }
666       }
667
668       SMTPClient client=new SMTPClient();
669       try {
670         int reply;
671         client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
672
673         reply = client.getReplyCode();
674
675         if (!SMTPReply.isPositiveCompletion(reply)) {
676           client.disconnect();
677           throw new ServletModuleExc("SMTP server refused connection.");
678         }
679
680         client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
681
682         client.disconnect();
683         //mission accomplished
684         deliver(req, res, mergeData, null, sentMailTemplate);
685       }
686       catch(IOException e) {
687         if(client.isConnected()) {
688           try {
689             client.disconnect();
690           } catch(IOException f) {
691             // do nothing
692           }
693         }
694         throw new ServletModuleFailure(e);
695       }
696     }
697   }
698
699
700
701   /**
702    * Method for querying a lucene index
703    *
704    * @param req
705    * @param res
706    * @throws ServletModuleExc
707    * @throws ServletModuleUserExc
708    * @throws ServletModuleFailure
709    */
710
711   public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
712     try {
713       final String[] search_variables = {
714           "search_content", "search_boolean", "search_creator",
715           "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
716           "search_submit", "search_back", "search_forward"};
717       HTTPRequestParser requestParser = new HTTPRequestParser(req);
718
719       int increment = 10;
720
721       HttpSession session = req.getSession(false);
722
723       String queryString = "";
724
725       Map mergeData = new HashMap();
726
727       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
728       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
729       TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
730       TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
731       TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
732       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
733       TopicSearchTerm topicTerm = new TopicSearchTerm();
734       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
735       AudioSearchTerm audioTerm = new AudioSearchTerm();
736       VideoSearchTerm videoTerm = new VideoSearchTerm();
737
738       //make the query available to subsequent iterations
739
740       Iterator j = Arrays.asList(search_variables).iterator();
741       while (j.hasNext()) {
742         String variable = (String) j.next();
743
744         mergeData.put(variable, requestParser.getParameter(variable));
745       }
746
747       try {
748         mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
749       }
750       catch (Throwable e) {
751         logger.debug("Can't get topics: " + e.toString());
752       }
753
754       String searchBackValue = req.getParameter("search_back");
755       String searchForwardValue = req.getParameter("search_forward");
756
757       if (searchBackValue != null) {
758         int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
759         int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
760         if (newPosition < 0)
761           newPosition = 0;
762         if (newPosition >= totalHits)
763           newPosition = totalHits - 1;
764         session.setAttribute("positionInResults", new Integer(newPosition));
765       }
766       else {
767         if (searchForwardValue != null) {
768           int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
769           int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
770           if (newPosition < 0)
771             newPosition = 0;
772           if (newPosition >= totalHits)
773             newPosition = totalHits - 1;
774
775           session.setAttribute("positionInResults", new Integer(newPosition));
776         }
777         else {
778           String indexPath = configuration.getString("IndexPath");
779
780           String creatorFragment = creatorTerm.makeTerm(req);
781           if (creatorFragment != null) {
782             queryString = queryString + " +" + creatorFragment;
783           }
784
785           // search title, description, and content for something
786           // the contentTerm uses param "search_boolean" to combine its terms
787           String contentFragment = contentTerm.makeTerm(req);
788           if (contentFragment != null) {
789             logger.debug("contentFragment: " + contentFragment);
790             queryString = queryString + " +" + contentFragment;
791           }
792
793           String topicFragment = topicTerm.makeTerm(req);
794           if (topicFragment != null) {
795             queryString = queryString + " +" + topicFragment;
796           }
797
798           String imagesFragment = imagesTerm.makeTerm(req);
799           if (imagesFragment != null) {
800             queryString = queryString + " +" + imagesFragment;
801           }
802
803           String audioFragment = audioTerm.makeTerm(req);
804           if (audioFragment != null) {
805             queryString = queryString + " +" + audioFragment;
806           }
807
808           String videoFragment = videoTerm.makeTerm(req);
809           if (videoFragment != null) {
810             queryString = queryString + " +" + videoFragment;
811           }
812
813           if (queryString == null || queryString == "") {
814             queryString = "";
815           }
816           else {
817             try {
818               Searcher searcher = null;
819               try {
820                 searcher = new IndexSearcher(indexPath);
821               }
822               catch (IOException e) {
823                 logger.debug("Can't open indexPath: " + indexPath);
824                 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
825               }
826
827               Query query = null;
828               try {
829                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
830               }
831               catch (Exception e) {
832                 searcher.close();
833                 logger.debug("Query don't parse: " + queryString);
834                 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
835               }
836
837               Hits hits = null;
838               try {
839                 hits = searcher.search(query);
840               }
841               catch (IOException e) {
842                 searcher.close();
843                 logger.debug("Can't get hits: " + e.toString());
844                 throw new ServletModuleExc("Problem getting hits!");
845               }
846
847               int start = 0;
848               int end = hits.length();
849
850               String sortBy = req.getParameter("search_sort");
851               if (sortBy == null || sortBy.equals("")) {
852                 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
853               }
854
855               // here is where the documents will go for storage across sessions
856               ArrayList theDocumentsSorted = new ArrayList();
857
858               if (sortBy.equals("score")) {
859                 for (int i = start; i < end; i++) {
860                   theDocumentsSorted.add(hits.doc(i));
861                 }
862               }
863               else {
864                 // then we'll sort by date!
865                 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
866                 for (int i = start; i < end; i++) {
867                   String creationDate = (hits.doc(i)).get("creationDate");
868                   // do a little dance in case two contents created at the same second!
869                   if (dateToPosition.containsKey(creationDate)) {
870                     ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
871                   }
872                   else {
873                     ArrayList thePositions = new ArrayList();
874                     thePositions.add(new Integer(i));
875                     dateToPosition.put(creationDate, thePositions);
876                   }
877                 }
878                 Set keys = dateToPosition.keySet();
879                 ArrayList keyList = new ArrayList(keys);
880                 Collections.sort(keyList);
881                 if (sortBy.equals("date_desc")) {
882                   Collections.reverse(keyList);
883                 }
884                 else {
885                   if (!sortBy.equals("date_asc")) {
886                     throw new ServletModuleExc("don't know how to sort by: " + sortBy);
887                   }
888                 }
889                 ListIterator keyTraverser = keyList.listIterator();
890                 while (keyTraverser.hasNext()) {
891                   ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
892                   ListIterator positionsTraverser = positions.listIterator();
893                   while (positionsTraverser.hasNext()) {
894                     theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
895                   }
896                 }
897               }
898
899               try {
900                 searcher.close();
901               }
902               catch (IOException e) {
903                 logger.debug("Can't close searcher: " + e.toString());
904                 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
905               }
906
907               session.removeAttribute("numberOfHits");
908               session.removeAttribute("theDocumentsSorted");
909               session.removeAttribute("positionInResults");
910
911               session.setAttribute("numberOfHits", new Integer(end));
912               session.setAttribute("theDocumentsSorted", theDocumentsSorted);
913               session.setAttribute("positionInResults", new Integer(0));
914
915             }
916             catch (IOException e) {
917               logger.debug("Can't close searcher: " + e.toString());
918               throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
919             }
920           }
921         }
922       }
923
924       try {
925         ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
926         if (theDocs != null) {
927
928           mergeData.put("numberOfHits", ( (Integer) session.getAttribute("numberOfHits")).toString());
929           List theHits = new Vector();
930           int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
931           int terminus;
932           int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
933
934           if (! (pIR + increment >= numHits)) {
935             mergeData.put("hasNext", "y");
936           }
937           else {
938             mergeData.put("hasNext", null);
939           }
940           if (pIR > 0) {
941             mergeData.put("hasPrevious", "y");
942           }
943           else {
944             mergeData.put("hasPrevious", null);
945           }
946
947           if ( (pIR + increment) > numHits) {
948             terminus = numHits;
949           }
950           else {
951             terminus = pIR + increment;
952           }
953           for (int i = pIR; i < terminus; i++) {
954             Map h = new HashMap();
955             Document theHit = (Document) theDocs.get(i);
956             whereTerm.returnMeta(h, theHit);
957             creatorTerm.returnMeta(h, theHit);
958             titleTerm.returnMeta(h, theHit);
959             descriptionTerm.returnMeta(h, theHit);
960             dateTerm.returnMeta(h, theHit);
961             imagesTerm.returnMeta(h, theHit);
962             audioTerm.returnMeta(h, theHit);
963             videoTerm.returnMeta(h, theHit);
964             theHits.add(h);
965           }
966           mergeData.put("hits", theHits);
967         }
968       }
969       catch (Throwable e) {
970         logger.error("Can't iterate over hits: " + e.toString());
971
972         throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
973       }
974
975       mergeData.put("queryString", queryString);
976
977       deliver(req, res, mergeData, null, searchResultsTemplate);
978     }
979     catch (NullPointerException n) {
980       throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
981     }
982   }
983
984   /*
985    * Method for dynamically generating a pdf using iText
986    */
987
988   public void getpdf(HttpServletRequest req, HttpServletResponse res)
989     throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
990     long starttime=System.currentTimeMillis();
991     String ID_REQUEST_PARAM = "id";
992     int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
993     try {
994       String idParam = req.getParameter(ID_REQUEST_PARAM);
995       if (idParam != null) {
996           
997
998         RE re = new RE("[0-9]+");
999           
1000           
1001         REMatch[] idMatches=re.getAllMatches(idParam);
1002           
1003         String cacheSelector="";
1004           
1005         for (int i = 0; i < idMatches.length; i++){
1006           cacheSelector=   cacheSelector + "," + idMatches[i].toString();
1007         }
1008           
1009         String cacheType="pdf";
1010           
1011         CacheKey theCacheKey = new CacheKey(cacheType,cacheSelector);
1012           
1013         byte[] thePDF;
1014           
1015         if (MirGlobal.mruCache().hasObject(theCacheKey)){
1016           logger.info("fetching pdf from cache");
1017           thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1018         }
1019         else {
1020           logger.info("generating pdf and caching it");
1021           ByteArrayOutputStream out = new ByteArrayOutputStream();
1022           PDFGenerator pdfMaker = new PDFGenerator(out);
1023             
1024           if (idMatches.length > 1){
1025             pdfMaker.addLine();
1026             for (int i = 0; i < idMatches.length  && i < maxArticlesInNewsleter; i++){
1027               REMatch aMatch = idMatches[i];
1028               String id=aMatch.toString();
1029               EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1030               pdfMaker.addIndexItem(contentEnt);
1031             }
1032           }
1033             
1034           for (int i = 0; i < idMatches.length; i++){
1035             REMatch aMatch = idMatches[i];
1036             String id=aMatch.toString();
1037             EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1038               
1039             pdfMaker.add(contentEnt);
1040           }
1041             
1042           pdfMaker.stop();
1043           thePDF  = out.toByteArray();
1044             
1045           //and save all our hard work!
1046           MirGlobal.mruCache().storeObject(theCacheKey,thePDF);
1047         }
1048           
1049         res.setContentType("application/pdf");
1050         res.setContentLength(thePDF.length);
1051         res.getOutputStream().write(thePDF);
1052         res.getOutputStream().flush();
1053         String elapsedtime=(new Long(System.currentTimeMillis()-starttime)).toString();
1054         logger.info("pdf retireval took "+elapsedtime + " milliseconds"  );
1055
1056       }
1057       else {
1058         throw new ServletModuleExc("Missing id.");
1059       }
1060     }
1061     catch (Throwable t) {
1062       logger.error(t.toString());
1063       throw new ServletModuleFailure(t);
1064     }
1065
1066   }
1067   
1068
1069   public String generateOnetimePassword() {
1070     Random r = new Random();
1071     int random = r.nextInt();
1072
1073     long l = System.currentTimeMillis();
1074
1075     l = (l * l * l * l) / random;
1076     if (l < 0)
1077       l = l * -1;
1078
1079     String returnString = "" + l;
1080
1081     return returnString.substring(5);
1082   }
1083
1084   public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1085     try {
1086       deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1087     }
1088     catch (Throwable t) {
1089       throw new ServletModuleFailure(t);
1090     }
1091   }
1092
1093   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1094       throws ServletModuleFailure {
1095     try {
1096       Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1097       responseData.put("data", aData);
1098       responseData.put("extra", anExtra);
1099
1100
1101       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1102       generator.generate(anOutputWriter, responseData, logger);
1103
1104       anOutputWriter.close();
1105     }
1106     catch (Throwable e) {
1107       logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1108
1109       throw new ServletModuleFailure(e);
1110     }
1111   }
1112
1113   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1114       throws ServletModuleFailure {
1115     try {
1116       Map responseData = ServletHelper.makeGenerationData(new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
1117       responseData.put("data", aData);
1118       responseData.put("extra", anExtra);
1119
1120
1121       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1122       generator.generate(anOutputWriter, responseData, logger);
1123
1124       anOutputWriter.close();
1125     }
1126     catch (Throwable e) {
1127       logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1128
1129       throw new ServletModuleFailure(e);
1130     }
1131   }
1132
1133
1134   public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1135     try {
1136       logger.error("error: " + anException);
1137       Map data = new HashMap();
1138
1139       data.put("errorstring", anException.getMessage());
1140       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1141
1142       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1143     }
1144     catch (Throwable e) {
1145       throw new ServletModuleFailure(e);
1146     }
1147   }
1148
1149   public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1150                                PrintWriter out, ServletModuleUserExc anException) {
1151     try {
1152       logger.warn("user error: " + anException.getMessage());
1153       Map data = new HashMap();
1154
1155       MessageResources messages = MessageResources.getMessageResources("bundles.open");
1156       data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1157       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1158
1159       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1160     }
1161     catch (Throwable e) {
1162       throw new ServletModuleFailure(e);
1163     }
1164   }
1165
1166   private String createOneTimePasswd() {
1167     return "";
1168   }
1169 }