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