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