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