more complicated topic searches now possible...
[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.89.2.2 2003/06/03 20:58:30 john 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", topicsModule.getTopicsAsSimpleList());
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    * Dispatch method for open sessions: a flexible extensible and customizable way
528    *   for open access. Can be used for postings, but also for lots of other stuff.
529    *
530    * @param aRequest
531    * @param aResponse
532    * @throws ServletModuleExc
533    * @throws ServletModuleUserExc
534    * @throws ServletModuleFailure
535    */
536
537   public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
538       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
539
540     try {
541       Request request =
542           new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
543               configuration.getString("Mir.DefaultEncoding"),
544               configuration.getInt("MaxMediaUploadSize")*1024,
545               configuration.getString("TempDir")));
546
547       if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
548           !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
549         aRequest.getSession().invalidate();
550
551       Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
552
553       SimpleResponse response = new SimpleResponse(
554           ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},
555              "bundles.open"));
556
557       response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
558
559       SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
560
561       handler.processRequest(request, session, response);
562       ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
563     }
564     catch (Throwable t) {
565       logger.error(t.toString());
566       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
567
568       throw new ServletModuleFailure(t);
569     }
570   }
571
572   /**
573    * Method for preparing and sending a content as an email message
574    */
575
576   public void mail(HttpServletRequest req, HttpServletResponse res)
577       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
578   {
579     String aid = req.getParameter("mail_aid");
580     if (aid == null){
581       throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
582     }
583
584     String to = req.getParameter("mail_to");
585     String from = req.getParameter("mail_from");
586     String from_name = req.getParameter("mail_from_name");
587     String from_ip = req.getRemoteAddr();
588     String comment = req.getParameter("mail_comment");
589     String mail_language = req.getParameter("mail_language");
590
591     Map mergeData = new HashMap();
592     mergeData.put("mail_to",to);
593     mergeData.put("mail_from",from);
594     mergeData.put("mail_from_name",from_name);
595     mergeData.put("mail_comment",comment);
596     mergeData.put("mail_aid",aid);
597     mergeData.put("mail_language",mail_language);
598
599
600     if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
601       deliver(req, res, mergeData, null, prepareMailTemplate);
602     }
603     else {
604       //run checks on to and from and mail_language to make sure no monkey business occurring
605       if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
606         throw new ServletModuleExc("Invalid language");
607       }
608       if (to.indexOf('\n') != -1
609           || to.indexOf('\r') != -1
610           || to.indexOf(',') != -1) {
611         throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
612       }
613       if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
614         throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
615       }
616
617       CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
618       String theEmailText;
619
620       if (MirGlobal.mruCache().hasObject(theCacheKey)){
621   logger.info("fetching email text for article "+aid+" from cache");
622   theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
623       }
624       else {
625         EntityContent contentEnt;
626         try {
627           contentEnt = (EntityContent) contentModule.getById(aid);
628           StringWriter theEMailTextWriter = new StringWriter();
629           PrintWriter dest = new PrintWriter(theEMailTextWriter);
630           Map articleData = new HashMap();
631           articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
632           articleData.put("languagecode", mail_language);
633           deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
634           theEmailText = theEMailTextWriter.toString();
635           MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
636         }
637         catch (Throwable e) {
638           throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
639         }
640       }
641
642       String content = theEmailText;
643
644
645       // add some headers
646       content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
647       // put in the comment where it should go
648       if (comment != null) {
649         String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
650         try {
651           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
652         }
653         catch (Throwable e){
654           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
655         }
656       }
657       else{
658         try {
659           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
660         }
661         catch (Throwable e){
662           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
663         }
664       }
665
666       SMTPClient client=new SMTPClient();
667       try {
668         int reply;
669         client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
670
671         reply = client.getReplyCode();
672
673         if (!SMTPReply.isPositiveCompletion(reply)) {
674           client.disconnect();
675           throw new ServletModuleExc("SMTP server refused connection.");
676         }
677
678         client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
679
680         client.disconnect();
681         //mission accomplished
682         deliver(req, res, mergeData, null, sentMailTemplate);
683       }
684       catch(IOException e) {
685         if(client.isConnected()) {
686           try {
687             client.disconnect();
688           } catch(IOException f) {
689             // do nothing
690           }
691         }
692         throw new ServletModuleFailure(e);
693       }
694     }
695   }
696
697
698
699   /**
700    * Method for querying a lucene index
701    *
702    * @param req
703    * @param res
704    * @throws ServletModuleExc
705    * @throws ServletModuleUserExc
706    * @throws ServletModuleFailure
707    */
708
709   public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
710     try {
711       final String[] search_variables = {
712           "search_content", "search_boolean", "search_creator",
713           "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
714           "search_submit", "search_back", "search_forward"};
715       HTTPRequestParser requestParser = new HTTPRequestParser(req);
716
717       int increment = 10;
718
719       HttpSession session = req.getSession(false);
720
721       String queryString = "";
722
723       Map mergeData = new HashMap();
724
725       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
726       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
727       TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
728       TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
729       TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
730       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
731       TopicSearchTerm topicTerm = new TopicSearchTerm();
732       TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
733       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
734       AudioSearchTerm audioTerm = new AudioSearchTerm();
735       VideoSearchTerm videoTerm = new VideoSearchTerm();
736
737       //make the query available to subsequent iterations
738
739       Iterator j = Arrays.asList(search_variables).iterator();
740       while (j.hasNext()) {
741         String variable = (String) j.next();
742
743         mergeData.put(variable, requestParser.getParameter(variable));
744       }
745
746       try {
747         mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
748       }
749       catch (Throwable e) {
750         logger.debug("Can't get topics: " + e.toString());
751       }
752
753       String searchBackValue = req.getParameter("search_back");
754       String searchForwardValue = req.getParameter("search_forward");
755
756       if (searchBackValue != null) {
757         int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
758         int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
759         if (newPosition < 0)
760           newPosition = 0;
761         if (newPosition >= totalHits)
762           newPosition = totalHits - 1;
763         session.setAttribute("positionInResults", new Integer(newPosition));
764       }
765       else {
766         if (searchForwardValue != null) {
767           int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
768           int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
769           if (newPosition < 0)
770             newPosition = 0;
771           if (newPosition >= totalHits)
772             newPosition = totalHits - 1;
773
774           session.setAttribute("positionInResults", new Integer(newPosition));
775         }
776         else {
777           String indexPath = configuration.getString("IndexPath");
778
779           String creatorFragment = creatorTerm.makeTerm(req);
780           if (creatorFragment != null) {
781             queryString = queryString + " +" + creatorFragment;
782           }
783
784           // search title, description, and content for something
785           // the contentTerm uses param "search_boolean" to combine its terms
786           String contentFragment = contentTerm.makeTerm(req);
787           if (contentFragment != null) {
788             logger.debug("contentFragment: " + contentFragment);
789             queryString = queryString + " +" + contentFragment;
790           }
791
792           String topicFragment = topicTerm.makeTerm(req);
793           if (topicFragment != null) {
794             queryString = queryString + " +" + topicFragment;
795           }
796
797           String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
798           if (topicMatrixFragment != null) {
799             queryString = queryString + " +" + topicMatrixFragment;
800           }
801
802           String imagesFragment = imagesTerm.makeTerm(req);
803           if (imagesFragment != null) {
804             queryString = queryString + " +" + imagesFragment;
805           }
806
807           String audioFragment = audioTerm.makeTerm(req);
808           if (audioFragment != null) {
809             queryString = queryString + " +" + audioFragment;
810           }
811
812           String videoFragment = videoTerm.makeTerm(req);
813           if (videoFragment != null) {
814             queryString = queryString + " +" + videoFragment;
815           }
816
817           if (queryString == null || queryString == "") {
818             queryString = "";
819           }
820           else {
821             try {
822               Searcher searcher = null;
823               try {
824                 searcher = new IndexSearcher(indexPath);
825               }
826               catch (IOException e) {
827                 logger.debug("Can't open indexPath: " + indexPath);
828                 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
829               }
830
831               Query query = null;
832               try {
833                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
834               }
835               catch (Exception e) {
836                 searcher.close();
837                 logger.debug("Query don't parse: " + queryString);
838                 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
839               }
840
841               Hits hits = null;
842               try {
843                 hits = searcher.search(query);
844               }
845               catch (IOException e) {
846                 searcher.close();
847                 logger.debug("Can't get hits: " + e.toString());
848                 throw new ServletModuleExc("Problem getting hits!");
849               }
850
851               int start = 0;
852               int end = hits.length();
853
854               String sortBy = req.getParameter("search_sort");
855               if (sortBy == null || sortBy.equals("")) {
856                 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
857               }
858
859               // here is where the documents will go for storage across sessions
860               ArrayList theDocumentsSorted = new ArrayList();
861
862               if (sortBy.equals("score")) {
863                 for (int i = start; i < end; i++) {
864                   theDocumentsSorted.add(hits.doc(i));
865                 }
866               }
867               else {
868                 // then we'll sort by date!
869                 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
870                 for (int i = start; i < end; i++) {
871                   String creationDate = (hits.doc(i)).get("creationDate");
872                   // do a little dance in case two contents created at the same second!
873                   if (dateToPosition.containsKey(creationDate)) {
874                     ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
875                   }
876                   else {
877                     ArrayList thePositions = new ArrayList();
878                     thePositions.add(new Integer(i));
879                     dateToPosition.put(creationDate, thePositions);
880                   }
881                 }
882                 Set keys = dateToPosition.keySet();
883                 ArrayList keyList = new ArrayList(keys);
884                 Collections.sort(keyList);
885                 if (sortBy.equals("date_desc")) {
886                   Collections.reverse(keyList);
887                 }
888                 else {
889                   if (!sortBy.equals("date_asc")) {
890                     throw new ServletModuleExc("don't know how to sort by: " + sortBy);
891                   }
892                 }
893                 ListIterator keyTraverser = keyList.listIterator();
894                 while (keyTraverser.hasNext()) {
895                   ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
896                   ListIterator positionsTraverser = positions.listIterator();
897                   while (positionsTraverser.hasNext()) {
898                     theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
899                   }
900                 }
901               }
902
903               try {
904                 searcher.close();
905               }
906               catch (IOException e) {
907                 logger.debug("Can't close searcher: " + e.toString());
908                 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
909               }
910
911               session.removeAttribute("numberOfHits");
912               session.removeAttribute("theDocumentsSorted");
913               session.removeAttribute("positionInResults");
914
915               session.setAttribute("numberOfHits", new Integer(end));
916               session.setAttribute("theDocumentsSorted", theDocumentsSorted);
917               session.setAttribute("positionInResults", new Integer(0));
918
919             }
920             catch (IOException e) {
921               logger.debug("Can't close searcher: " + e.toString());
922               throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
923             }
924           }
925         }
926       }
927
928       try {
929         ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
930         if (theDocs != null) {
931
932           mergeData.put("numberOfHits", ( (Integer) session.getAttribute("numberOfHits")).toString());
933           List theHits = new Vector();
934           int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
935           int terminus;
936           int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
937
938           if (! (pIR + increment >= numHits)) {
939             mergeData.put("hasNext", "y");
940           }
941           else {
942             mergeData.put("hasNext", null);
943           }
944           if (pIR > 0) {
945             mergeData.put("hasPrevious", "y");
946           }
947           else {
948             mergeData.put("hasPrevious", null);
949           }
950
951           if ( (pIR + increment) > numHits) {
952             terminus = numHits;
953           }
954           else {
955             terminus = pIR + increment;
956           }
957           for (int i = pIR; i < terminus; i++) {
958             Map h = new HashMap();
959             Document theHit = (Document) theDocs.get(i);
960             whereTerm.returnMeta(h, theHit);
961             creatorTerm.returnMeta(h, theHit);
962             titleTerm.returnMeta(h, theHit);
963             descriptionTerm.returnMeta(h, theHit);
964             dateTerm.returnMeta(h, theHit);
965             imagesTerm.returnMeta(h, theHit);
966             audioTerm.returnMeta(h, theHit);
967             videoTerm.returnMeta(h, theHit);
968             theHits.add(h);
969           }
970           mergeData.put("hits", theHits);
971         }
972       }
973       catch (Throwable e) {
974         logger.error("Can't iterate over hits: " + e.toString());
975
976         throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
977       }
978
979       mergeData.put("queryString", queryString);
980
981       deliver(req, res, mergeData, null, searchResultsTemplate);
982     }
983     catch (NullPointerException n) {
984       throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
985     }
986   }
987
988   /*
989    * Method for dynamically generating a pdf using iText
990    */
991
992   public void getpdf(HttpServletRequest req, HttpServletResponse res)
993     throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
994     long starttime=System.currentTimeMillis();
995     String ID_REQUEST_PARAM = "id";
996     int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
997     try {
998       String idParam = req.getParameter(ID_REQUEST_PARAM);
999       if (idParam != null) {
1000
1001
1002   RE re = new RE("[0-9]+");
1003
1004
1005   REMatch[] idMatches=re.getAllMatches(idParam);
1006
1007   String cacheSelector="";
1008
1009   for (int i = 0; i < idMatches.length; i++){
1010     cacheSelector=   cacheSelector + "," + idMatches[i].toString();
1011   }
1012
1013   String cacheType="pdf";
1014
1015   CacheKey theCacheKey = new CacheKey(cacheType,cacheSelector);
1016
1017   byte[] thePDF;
1018
1019   if (MirGlobal.mruCache().hasObject(theCacheKey)){
1020     logger.info("fetching pdf from cache");
1021     thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1022   }
1023   else {
1024     logger.info("generating pdf and caching it");
1025     ByteArrayOutputStream out = new ByteArrayOutputStream();
1026     PDFGenerator pdfMaker = new PDFGenerator(out);
1027
1028     if (idMatches.length > 1){
1029       pdfMaker.addLine();
1030       for (int i = 0; i < idMatches.length  && i < maxArticlesInNewsleter; i++){
1031         REMatch aMatch = idMatches[i];
1032         String id=aMatch.toString();
1033         EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1034         pdfMaker.addIndexItem(contentEnt);
1035       }
1036     }
1037
1038     for (int i = 0; i < idMatches.length; i++){
1039       REMatch aMatch = idMatches[i];
1040       String id=aMatch.toString();
1041       EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1042
1043       pdfMaker.add(contentEnt);
1044     }
1045
1046     pdfMaker.stop();
1047     thePDF  = out.toByteArray();
1048
1049     //and save all our hard work!
1050     MirGlobal.mruCache().storeObject(theCacheKey,thePDF);
1051   }
1052
1053   res.setContentType("application/pdf");
1054   res.setContentLength(thePDF.length);
1055   res.getOutputStream().write(thePDF);
1056   res.getOutputStream().flush();
1057   String elapsedtime=(new Long(System.currentTimeMillis()-starttime)).toString();
1058   logger.info("pdf retireval took "+elapsedtime + " milliseconds"  );
1059
1060       }
1061       else {
1062   throw new ServletModuleExc("Missing id.");
1063       }
1064     }
1065     catch (Throwable t) {
1066       logger.error(t.toString());
1067       throw new ServletModuleFailure(t);
1068     }
1069
1070   }
1071
1072
1073   public String generateOnetimePassword() {
1074     Random r = new Random();
1075     int random = r.nextInt();
1076
1077     long l = System.currentTimeMillis();
1078
1079     l = (l * l * l * l) / random;
1080     if (l < 0)
1081       l = l * -1;
1082
1083     String returnString = "" + l;
1084
1085     return returnString.substring(5);
1086   }
1087
1088   public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1089     try {
1090       deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1091     }
1092     catch (Throwable t) {
1093       throw new ServletModuleFailure(t);
1094     }
1095   }
1096
1097   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1098       throws ServletModuleFailure {
1099     try {
1100       Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1101       responseData.put("data", aData);
1102       responseData.put("extra", anExtra);
1103
1104
1105       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1106       generator.generate(anOutputWriter, responseData, logger);
1107
1108       anOutputWriter.close();
1109     }
1110     catch (Throwable e) {
1111       logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1112
1113       throw new ServletModuleFailure(e);
1114     }
1115   }
1116
1117   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1118       throws ServletModuleFailure {
1119     try {
1120       Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
1121       responseData.put("data", aData);
1122       responseData.put("extra", anExtra);
1123
1124
1125       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1126       generator.generate(anOutputWriter, responseData, logger);
1127
1128       anOutputWriter.close();
1129     }
1130     catch (Throwable e) {
1131       logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1132
1133       throw new ServletModuleFailure(e);
1134     }
1135   }
1136
1137
1138   public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1139     try {
1140       logger.error("error: " + anException);
1141       Map data = new HashMap();
1142
1143       data.put("errorstring", anException.getMessage());
1144       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1145
1146       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1147     }
1148     catch (Throwable e) {
1149       throw new ServletModuleFailure(e);
1150     }
1151   }
1152
1153   public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1154                                PrintWriter out, ServletModuleUserExc anException) {
1155     try {
1156       logger.warn("user error: " + anException.getMessage());
1157       Map data = new HashMap();
1158
1159       MessageResources messages = MessageResources.getMessageResources("bundles.open");
1160       data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1161       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1162
1163       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1164     }
1165     catch (Throwable e) {
1166       throw new ServletModuleFailure(e);
1167     }
1168   }
1169
1170   private String createOneTimePasswd() {
1171     return "";
1172   }
1173 }