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