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