9e7f5be470c6e1f08e5f01bb40f647e032dfd80c
[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.File;
35 import java.io.FileNotFoundException;
36 import java.io.FileReader;
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.Enumeration;
44 import java.util.GregorianCalendar;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.ListIterator;
49 import java.util.Locale;
50 import java.util.Map;
51 import java.util.Random;
52 import java.util.Set;
53 import java.util.Vector;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import javax.servlet.http.HttpSession;
57 import javax.servlet.http.HttpUtils;
58
59 import org.apache.commons.fileupload.FileItem;
60 import org.apache.commons.net.smtp.SMTPClient;
61 import org.apache.commons.net.smtp.SMTPReply;
62 import org.apache.lucene.analysis.standard.StandardAnalyzer;
63 import org.apache.lucene.document.Document;
64 import org.apache.lucene.queryParser.QueryParser;
65 import org.apache.lucene.search.Hits;
66 import org.apache.lucene.search.IndexSearcher;
67 import org.apache.lucene.search.Query;
68 import org.apache.lucene.search.Searcher;
69 import org.apache.struts.util.MessageResources;
70 import gnu.regexp.RE;
71 import gnu.regexp.REMatch;
72
73 import mir.entity.Entity;
74 import mir.generator.Generator;
75 import mir.log.LoggerWrapper;
76 import mir.misc.StringUtil;
77 import mir.servlet.ServletModule;
78 import mir.servlet.ServletModuleExc;
79 import mir.servlet.ServletModuleFailure;
80 import mir.servlet.ServletModuleUserExc;
81 import mir.session.HTTPAdapters;
82 import mir.session.Request;
83 import mir.session.Session;
84 import mir.session.SessionHandler;
85 import mir.session.SimpleResponse;
86 import mir.session.UploadedFile;
87 import mir.storage.StorageObjectFailure;
88 import mir.util.ExceptionFunctions;
89 import mir.util.HTTPParsedRequest;
90 import mir.util.HTTPRequestParser;
91 import mir.util.StringRoutines;
92 import mircoders.entity.EntityComment;
93 import mircoders.entity.EntityContent;
94 import mircoders.global.MirGlobal;
95 import mircoders.media.MediaUploadProcessor;
96 import mircoders.module.ModuleComment;
97 import mircoders.module.ModuleContent;
98 import mircoders.module.ModuleImages;
99 import mircoders.module.ModuleMediaType;
100 import mircoders.module.ModuleTopics;
101 import mircoders.pdf.PDFGenerator;
102 import mircoders.search.AudioSearchTerm;
103 import mircoders.search.ContentSearchTerm;
104 import mircoders.search.ImagesSearchTerm;
105 import mircoders.search.KeywordSearchTerm;
106 import mircoders.search.TextSearchTerm;
107 import mircoders.search.TopicSearchTerm;
108 import mircoders.search.UnIndexedSearchTerm;
109 import mircoders.search.VideoSearchTerm;
110 import mircoders.storage.DatabaseComment;
111 import mircoders.storage.DatabaseContent;
112 import mircoders.storage.DatabaseContentToMedia;
113 import mircoders.storage.DatabaseContentToTopics;
114 import mircoders.storage.DatabaseImages;
115 import mircoders.storage.DatabaseLanguage;
116 import mircoders.storage.DatabaseTopics;
117
118 /*
119  *  ServletModuleOpenIndy -
120  *   is the open-access-servlet, which is responsible for
121  *    adding comments to articles &
122  *    open-postings to the newswire
123  *
124  * @author mir-coders group
125  * @version $Id: ServletModuleOpenIndy.java,v 1.84 2003/04/29 02:36:50 zapata Exp $
126  *
127  */
128
129 public class ServletModuleOpenIndy extends ServletModule
130 {
131
132   private String        commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
133   private String        postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
134   private String        searchResultsTemplate;
135   private String        prepareMailTemplate,sentMailTemplate;
136   private ModuleContent contentModule;
137   private ModuleComment commentModule;
138   private ModuleImages  imageModule;
139   private ModuleTopics  topicsModule;
140   private String        directOp ="yes";
141   // Singelton / Kontruktor
142   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
143   public static ServletModule getInstance() { return instance; }
144
145   private ServletModuleOpenIndy() {
146     super();
147     try {
148       logger = new LoggerWrapper("ServletModule.OpenIndy");
149
150       commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
151       commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
152       commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
153
154       postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
155       postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
156       postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
157
158       searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
159       prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
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   {
315     try {
316       if (MirGlobal.abuse().getOpenPostingDisabled()) {
317         openPostingDisabled(req, res);
318
319         return;
320       }
321
322       Map mergeData = new HashMap();
323
324       // onetimepasswd
325       if (MirGlobal.abuse().getOpenPostingPassword()) {
326         String passwd = generateOnetimePassword();
327         HttpSession session = req.getSession(false);
328         session.setAttribute("passwd", passwd);
329         mergeData.put("passwd", passwd);
330       }
331       else {
332         mergeData.put("passwd", (String)null);
333       }
334
335       String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
336       String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
337       String numOfMedia = req.getParameter("medianum");
338
339       if (numOfMedia == null || numOfMedia.equals("")) {
340         numOfMedia = defaultMedia;
341       }
342       else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
343         numOfMedia = maxMedia;
344       }
345
346       int mediaNum = Integer.parseInt(numOfMedia);
347       List mediaFields = new Vector();
348       for (int i = 0; i < mediaNum; i++) {
349         Integer mNum = new Integer(i + 1);
350         mediaFields.add(mNum.toString());
351       }
352       mergeData.put("medianum", numOfMedia);
353       mergeData.put("mediafields", mediaFields);
354       mergeData.put("to_topic", null);
355
356       Map extraInfo = new HashMap();
357       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
358       extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());
359
360       extraInfo.put("topics", topicsModule.getTopicsList());
361       deliver(req, res, mergeData, extraInfo, postingFormTemplate);
362     }
363     catch (Throwable t) {
364       throw new ServletModuleFailure(t);
365     }
366   }
367
368   /**
369    *  Method for inserting an open posting into the Database and delivering
370    *  the postingDone Page
371    */
372
373   public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
374       ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
375     if (MirGlobal.abuse().getOpenPostingDisabled()) {
376       openPostingDisabled(aRequest, aResponse);
377
378       return;
379     }
380
381     try {
382       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
383           aRequest,
384           configuration.getString("Mir.DefaultEncoding"),
385           configuration.getInt("MaxMediaUploadSize")*1024,
386           configuration.getString("TempDir"));
387
388       Map mergeData = new HashMap();
389
390       HttpSession session = aRequest.getSession(false);
391       String sessionPasswd = (String) session.getAttribute("passwd");
392       if (sessionPasswd != null) {
393         String passwd = (String) parsedRequest.getParameter("passwd");
394
395         if (passwd == null || passwd.length() == 0) {
396           throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
397         }
398         if (!sessionPasswd.equals(passwd)) {
399           throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
400         }
401         session.invalidate();
402       }
403
404       if ((((String) parsedRequest.getParameter("title")).length() == 0) ||
405           (((String) parsedRequest.getParameter("description")).length() == 0) ||
406           (((String) parsedRequest.getParameter("content_data")).length() == 0))
407         throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
408
409       List mediaList = new Vector();
410       Iterator i = parsedRequest.getFiles().iterator();
411
412       while (i.hasNext()) {
413         UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
414         Map mediaValues = new HashMap();
415
416         String suffix = file.getFieldName().substring(5); // media${m}
417         logger.debug("media_title" + suffix);
418         String title = parsedRequest.getParameter("media_title" + suffix);
419
420         mediaValues.put("title", StringUtil.removeHTMLTags(title));
421         mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
422         mediaValues.put("to_publisher", "0");
423         mediaValues.put("is_published", "1");
424         mediaValues.put("to_media_folder", "7");
425
426         mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
427       }
428
429       Map withValues = new HashMap();
430       i = DatabaseContent.getInstance().getFields().iterator();
431       while (i.hasNext()) {
432         String field = (String) i.next();
433         String value = parsedRequest.getParameter(field);
434         if (value!=null)
435           withValues.put(field, value);
436       }
437
438
439       for (i = withValues.keySet().iterator(); i.hasNext(); ) {
440         String k = (String) i.next();
441         String v = (String) withValues.get(k);
442
443         if (k.equals("content_data")) {
444           //this doesn't quite work yet, so for now, all html goes
445           //withValues.put(k,StringUtil.approveHTMLTags(v));
446           withValues.put(k, StringUtil.deleteForbiddenTags(v));
447         }
448         else if (k.equals("description")) {
449           String tmp = StringUtil.deleteForbiddenTags(v);
450           withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
451         }
452         else {
453           withValues.put(k, StringUtil.removeHTMLTags(v));
454         }
455       }
456
457       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
458       withValues.put("publish_path",
459                      StringUtil.webdbDate2path( (String) withValues.get("date")));
460       withValues.put("is_produced", "0");
461       withValues.put("is_published", "1");
462       if (directOp.equals("yes"))
463         withValues.put("to_article_type", "1");
464
465       withValues.put("to_publisher", "1");
466
467       // inserting  content into database
468       String cid = contentModule.add(withValues);
469       logger.debug("id: " + cid);
470       //insert was not successfull
471       if (cid == null) {
472         deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
473         return;
474       }
475
476       List topics = parsedRequest.getParameterList("to_topic");
477       if (topics.size() > 0) {
478         try {
479           DatabaseContentToTopics.getInstance().setTopics(cid, topics);
480         }
481         catch (Throwable e) {
482           logger.error("setting content_x_topic failed");
483           contentModule.deleteById(cid);
484           throw new ServletModuleFailure(
485               "smod - openindy :: insposting: setting content_x_topic failed: " +
486               e.toString(), e);
487         }
488       }
489
490       i = mediaList.iterator();
491       while (i.hasNext()) {
492         Entity mediaEnt = (Entity) i.next();
493         DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
494       }
495
496       EntityContent article = (EntityContent) contentModule.getById(cid);
497       try {
498         MirGlobal.abuse().checkArticle(
499             article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
500         MirGlobal.localizer().openPostings().afterContentPosting(article);
501       }
502       catch (Throwable t) {
503         logger.error("Error while post-processing article: " + t.getMessage());
504       }
505       deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
506     }
507     catch (Throwable e) {
508       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
509       Throwable cause = ExceptionFunctions.traceCauseException(e);
510
511       if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
512         throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
513       }
514       throw new ServletModuleFailure(e);
515     }
516   }
517
518   /**
519    * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
520    *   generated into open session urls. Tomcat 3.3 makes it impossible to
521    *   distinguish between sessions that are identified using a url and those
522    *   that are identified using cookies: if both a sessionid cookie and a sessionid
523    *   url are available, tomcat 3.3 pretends the url wasn't there...
524    */
525   private static final String SESSION_REQUEST_KEY="sessionid";
526
527   /**
528    * Dispatch method for open sessions: a flexible extensible and customizable way
529    *   for open access. Can be used for postings, but also for lots of other stuff.
530    *
531    * @param aRequest
532    * @param aResponse
533    * @throws ServletModuleExc
534    * @throws ServletModuleUserExc
535    * @throws ServletModuleFailure
536    */
537
538   public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
539       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
540
541     try {
542       Request request =
543           new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
544               configuration.getString("Mir.DefaultEncoding"),
545               configuration.getInt("MaxMediaUploadSize")*1024,
546               configuration.getString("TempDir")));
547
548       if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
549           !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
550         aRequest.getSession().invalidate();
551
552       Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
553
554       SimpleResponse response = new SimpleResponse(
555           ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},
556              "bundles.open"));
557
558       response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
559
560       SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
561
562       handler.processRequest(request, session, response);
563       ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
564     }
565     catch (Throwable t) {
566       logger.error(t.toString());
567       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
568
569       throw new ServletModuleFailure(t);
570     }
571   }
572
573   /**
574    * Method for preparing and sending a content as an email message
575    */
576
577   public void mail(HttpServletRequest req, HttpServletResponse res)
578       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
579   {
580     String aid = req.getParameter("mail_aid");
581     if (aid == null){
582       throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
583     }
584
585     String to = req.getParameter("mail_to");
586     String from = req.getParameter("mail_from");
587     String from_name = req.getParameter("mail_from_name");
588     String comment = req.getParameter("mail_comment");
589     String mail_language = req.getParameter("mail_language");
590
591     Map mergeData = new HashMap();
592
593     if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
594
595       for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
596         String pName=(String)theParams.nextElement();
597         if (pName.startsWith("mail_")){
598           mergeData.put( pName,req.getParameter(pName) );
599         }
600       }
601
602       deliver(req, res, mergeData, null, prepareMailTemplate);
603     }
604     else {
605       //run checks on to and from and mail_language to make sure no monkey business occurring
606       if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
607         throw new ServletModuleExc("Invalid language");
608       }
609       if (to.indexOf('\n') != -1
610           || to.indexOf('\r') != -1
611           || to.indexOf(',') != -1) {
612         throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
613       }
614       if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
615         throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
616       }
617
618
619       EntityContent contentEnt;
620       try{
621         contentEnt = (EntityContent)contentModule.getById(aid);
622       }
623       catch (Throwable e){
624         throw new ServletModuleFailure("Couldn't get content for article "+aid + ": " + e.getMessage(), e);
625       }
626       String producerStorageRoot=configuration.getString("Producer.StorageRoot");
627       String producerDocRoot=configuration.getString("Producer.DocRoot");
628       String publishPath = contentEnt.getValue("publish_path");
629       String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +
630                                                                                                          publishPath + "/" + aid + ".txt";
631
632
633       File inputFile = new File(txtFilePath);
634       String content;
635
636       try{
637         FileReader in = new FileReader(inputFile);
638         StringWriter out = new StringWriter();
639         int c;
640         while ((c = in.read()) != -1)
641           out.write(c);
642         in.close();
643         content= out.toString();
644       }
645       catch (FileNotFoundException e){
646         throw new ServletModuleFailure("No text file found in " + txtFilePath, e);
647       }
648       catch (IOException e){
649         throw new ServletModuleFailure("Problem reading file in " + txtFilePath, e);
650       }
651       // add some headers
652       content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
653       // put in the comment where it should go
654       if (comment != null) {
655         String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
656         try {
657           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
658         }
659         catch (Throwable e){
660           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
661         }
662       }
663       else{
664         try {
665           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
666         }
667         catch (Throwable e){
668           throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
669         }
670       }
671
672       SMTPClient client=new SMTPClient();
673       try {
674         int reply;
675         client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
676
677         reply = client.getReplyCode();
678
679         if (!SMTPReply.isPositiveCompletion(reply)) {
680           client.disconnect();
681           throw new ServletModuleExc("SMTP server refused connection.");
682         }
683
684         client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
685
686         client.disconnect();
687         //mission accomplished
688         deliver(req, res, mergeData, null, sentMailTemplate);
689       }
690       catch(IOException e) {
691         if(client.isConnected()) {
692           try {
693             client.disconnect();
694           } catch(IOException f) {
695             // do nothing
696           }
697         }
698         throw new ServletModuleFailure(e);
699       }
700     }
701   }
702
703
704
705   /**
706    * Method for querying a lucene index
707    *
708    * @param req
709    * @param res
710    * @throws ServletModuleExc
711    * @throws ServletModuleUserExc
712    * @throws ServletModuleFailure
713    */
714
715   public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
716     try {
717       final String[] search_variables = {
718           "search_content", "search_boolean", "search_creator",
719           "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
720           "search_submit", "search_back", "search_forward"};
721       HTTPRequestParser requestParser = new HTTPRequestParser(req);
722
723       int increment = 10;
724
725       HttpSession session = req.getSession(false);
726
727       String queryString = "";
728
729       Map mergeData = new HashMap();
730
731       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
732       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
733       TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
734       TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
735       TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
736       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
737       TopicSearchTerm topicTerm = new TopicSearchTerm();
738       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
739       AudioSearchTerm audioTerm = new AudioSearchTerm();
740       VideoSearchTerm videoTerm = new VideoSearchTerm();
741
742       //make the query available to subsequent iterations
743
744       Iterator j = Arrays.asList(search_variables).iterator();
745       while (j.hasNext()) {
746         String variable = (String) j.next();
747
748         mergeData.put(variable, requestParser.getParameter(variable));
749       }
750
751       try {
752         mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
753       }
754       catch (Throwable e) {
755         logger.debug("Can't get topics: " + e.toString());
756       }
757
758       String searchBackValue = req.getParameter("search_back");
759       String searchForwardValue = req.getParameter("search_forward");
760
761       if (searchBackValue != null) {
762         int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
763         int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
764         if (newPosition < 0)
765           newPosition = 0;
766         if (newPosition >= totalHits)
767           newPosition = totalHits - 1;
768         session.setAttribute("positionInResults", new Integer(newPosition));
769       }
770       else {
771         if (searchForwardValue != null) {
772           int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
773           int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
774           if (newPosition < 0)
775             newPosition = 0;
776           if (newPosition >= totalHits)
777             newPosition = totalHits - 1;
778
779           session.setAttribute("positionInResults", new Integer(newPosition));
780         }
781         else {
782           String indexPath = configuration.getString("IndexPath");
783
784           String creatorFragment = creatorTerm.makeTerm(req);
785           if (creatorFragment != null) {
786             queryString = queryString + " +" + creatorFragment;
787           }
788
789           // search title, description, and content for something
790           // the contentTerm uses param "search_boolean" to combine its terms
791           String contentFragment = contentTerm.makeTerm(req);
792           if (contentFragment != null) {
793             logger.debug("contentFragment: " + contentFragment);
794             queryString = queryString + " +" + contentFragment;
795           }
796
797           String topicFragment = topicTerm.makeTerm(req);
798           if (topicFragment != null) {
799             queryString = queryString + " +" + topicFragment;
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) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
993     String ID_REQUEST_PARAM = "id";
994     try {
995       String idParam = req.getParameter(ID_REQUEST_PARAM);
996       if (idParam != null) {
997         ByteArrayOutputStream out = new ByteArrayOutputStream();
998         PDFGenerator pdfMaker = new PDFGenerator(out);
999
1000         RE re = new RE("[0-9]+");
1001
1002         REMatch[] idMatches = re.getAllMatches(idParam);
1003
1004         if (idMatches.length > 1) {
1005           pdfMaker.addLine();
1006           for (int i = 0; i < idMatches.length; i++) {
1007             REMatch aMatch = idMatches[i];
1008             String id = aMatch.toString();
1009             EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1010             pdfMaker.addIndexItem(contentEnt);
1011
1012           }
1013         }
1014
1015         for (int i = 0; i < idMatches.length; i++) {
1016           REMatch aMatch = idMatches[i];
1017
1018           String id = aMatch.toString();
1019
1020           EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1021           pdfMaker.add(contentEnt);
1022
1023         }
1024
1025         pdfMaker.stop();
1026         res.setContentType("application/pdf");
1027         byte[] content = out.toByteArray();
1028         res.setContentLength(content.length);
1029         res.getOutputStream().write(content);
1030         res.getOutputStream().flush();
1031
1032       }
1033       else {
1034         throw new ServletModuleExc("Missing id.");
1035       }
1036     }
1037     catch (Throwable t) {
1038       logger.error(t.toString());
1039       throw new ServletModuleFailure(t);
1040     }
1041
1042   }
1043
1044   public String generateOnetimePassword() {
1045     Random r = new Random();
1046     int random = r.nextInt();
1047
1048     long l = System.currentTimeMillis();
1049
1050     l = (l * l * l * l) / random;
1051     if (l < 0)
1052       l = l * -1;
1053
1054     String returnString = "" + l;
1055
1056     return returnString.substring(5);
1057   }
1058
1059   public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1060     try {
1061       deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1062     }
1063     catch (Throwable t) {
1064       throw new ServletModuleFailure(t);
1065     }
1066   }
1067
1068   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1069       throws ServletModuleFailure {
1070     try {
1071       Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1072       responseData.put("data", aData);
1073       responseData.put("extra", anExtra);
1074
1075
1076       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1077       generator.generate(anOutputWriter, responseData, logger);
1078
1079       anOutputWriter.close();
1080     }
1081     catch (Throwable e) {
1082       logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1083
1084       throw new ServletModuleFailure(e);
1085     }
1086   }
1087
1088   public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1089     try {
1090       logger.error("error: " + anException);
1091       Map data = new HashMap();
1092
1093       data.put("errorstring", anException.getMessage());
1094       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1095
1096       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1097     }
1098     catch (Throwable e) {
1099       throw new ServletModuleFailure(e);
1100     }
1101   }
1102
1103   public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1104                                PrintWriter out, ServletModuleUserExc anException) {
1105     try {
1106       logger.warn("user error: " + anException.getMessage());
1107       Map data = new HashMap();
1108
1109       MessageResources messages = MessageResources.getMessageResources("bundles.open");
1110       data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1111       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1112
1113       deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1114     }
1115     catch (Throwable e) {
1116       throw new ServletModuleFailure(e);
1117     }
1118   }
1119
1120   private String createOneTimePasswd() {
1121     return "";
1122   }
1123 }