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