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