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