organizing imports
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 /*\r
2  * Copyright (C) 2001, 2002  The Mir-coders group\r
3  *\r
4  * This file is part of Mir.\r
5  *\r
6  * Mir is free software; you can redistribute it and/or modify\r
7  * it under the terms of the GNU General Public License as published by\r
8  * the Free Software Foundation; either version 2 of the License, or\r
9  * (at your option) any later version.\r
10  *\r
11  * Mir is distributed in the hope that it will be useful,\r
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14  * GNU General Public License for more details.\r
15  *\r
16  * You should have received a copy of the GNU General Public License\r
17  * along with Mir; if not, write to the Free Software\r
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
19  *\r
20  * In addition, as a special exception, The Mir-coders gives permission to link\r
21  * the code of this program with the com.oreilly.servlet library, any library\r
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
24  * the above that use the same license as the above), and distribute linked\r
25  * combinations including the two.  You must obey the GNU General Public\r
26  * License in all respects for all of the code used other than the above\r
27  * mentioned libraries.  If you modify this file, you may extend this exception\r
28  * to your version of the file, but you are not obligated to do so.  If you do\r
29  * not wish to do so, delete this exception statement from your version.\r
30  */\r
31 \r
32 package mircoders.servlet;\r
33 \r
34 import java.io.ByteArrayOutputStream;\r
35 import java.io.File;\r
36 import java.io.FileNotFoundException;\r
37 import java.io.FileReader;\r
38 import java.io.IOException;\r
39 import java.io.PrintWriter;\r
40 import java.io.StringWriter;\r
41 import java.util.ArrayList;\r
42 import java.util.Collections;\r
43 import java.util.Enumeration;\r
44 import java.util.GregorianCalendar;\r
45 import java.util.HashMap;\r
46 import java.util.Iterator;\r
47 import java.util.ListIterator;\r
48 import java.util.Locale;\r
49 import java.util.Map;\r
50 import java.util.Random;\r
51 import java.util.Set;\r
52 \r
53 import javax.servlet.http.HttpServletRequest;\r
54 import javax.servlet.http.HttpServletResponse;\r
55 import javax.servlet.http.HttpSession;\r
56 \r
57 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
58 import mir.entity.Entity;\r
59 import mir.entity.EntityList;\r
60 import mir.log.LoggerWrapper;\r
61 import mir.misc.FileHandler;\r
62 import mir.misc.FileHandlerException;\r
63 import mir.misc.FileHandlerUserException;\r
64 import mir.misc.HTMLParseException;\r
65 import mir.misc.HTMLTemplateProcessor;\r
66 import mir.misc.StringUtil;\r
67 import mir.misc.WebdbMultipartRequest;\r
68 import mir.module.ModuleException;\r
69 import mir.servlet.ServletModule;\r
70 import mir.servlet.ServletModuleException;\r
71 import mir.servlet.ServletModuleUserException;\r
72 import mir.storage.StorageObjectFailure;\r
73 import mir.util.StringRoutines;\r
74 import mircoders.entity.EntityComment;\r
75 import mircoders.entity.EntityContent;\r
76 import mircoders.global.MirGlobal;\r
77 import mircoders.media.MediaRequest;\r
78 import mircoders.module.ModuleComment;\r
79 import mircoders.module.ModuleContent;\r
80 import mircoders.module.ModuleImages;\r
81 import mircoders.module.ModuleTopics;\r
82 import mircoders.search.AudioSearchTerm;\r
83 import mircoders.search.ContentSearchTerm;\r
84 import mircoders.search.ImagesSearchTerm;\r
85 import mircoders.search.KeywordSearchTerm;\r
86 import mircoders.search.TextSearchTerm;\r
87 import mircoders.search.TopicSearchTerm;\r
88 import mircoders.search.UnIndexedSearchTerm;\r
89 import mircoders.search.VideoSearchTerm;\r
90 import mircoders.storage.DatabaseComment;\r
91 import mircoders.storage.DatabaseContent;\r
92 import mircoders.storage.DatabaseContentToMedia;\r
93 import mircoders.storage.DatabaseContentToTopics;\r
94 import mircoders.storage.DatabaseImages;\r
95 import mircoders.storage.DatabaseLanguage;\r
96 import mircoders.storage.DatabaseTopics;\r
97 \r
98 import org.apache.commons.net.smtp.SMTPClient;\r
99 import org.apache.commons.net.smtp.SMTPReply;\r
100 import org.apache.fop.apps.Driver;\r
101 import org.apache.fop.apps.XSLTInputHandler;\r
102 import org.apache.log.Hierarchy;\r
103 import org.apache.log.Priority;\r
104 import org.apache.lucene.analysis.standard.StandardAnalyzer;\r
105 import org.apache.lucene.document.Document;\r
106 import org.apache.lucene.queryParser.QueryParser;\r
107 import org.apache.lucene.search.Hits;\r
108 import org.apache.lucene.search.IndexSearcher;\r
109 import org.apache.lucene.search.Query;\r
110 import org.apache.lucene.search.Searcher;\r
111 \r
112 import freemarker.template.SimpleHash;\r
113 import freemarker.template.SimpleList;\r
114 import freemarker.template.SimpleScalar;\r
115 import freemarker.template.TemplateModelRoot;\r
116 \r
117 /*\r
118  *  ServletModuleOpenIndy -\r
119  *   is the open-access-servlet, which is responsible for\r
120  *    adding comments to articles &\r
121  *    open-postings to the newswire\r
122  *\r
123  * @author mir-coders group\r
124  * @version $Id: ServletModuleOpenIndy.java,v 1.62 2003/03/05 19:23:16 idfx Exp $\r
125  *\r
126  */\r
127 \r
128 public class ServletModuleOpenIndy extends ServletModule\r
129 {\r
130 \r
131   private String        commentFormTemplate, commentFormDoneTemplate,\r
132     commentFormDupeTemplate;\r
133   private String        postingFormTemplate, postingFormDoneTemplate,\r
134     postingFormDupeTemplate;\r
135   private String        searchResultsTemplate;\r
136   private String        prepareMailTemplate,sentMailTemplate;\r
137   private ModuleContent contentModule;\r
138   private ModuleComment commentModule;\r
139   private ModuleImages  imageModule;\r
140   private ModuleTopics  themenModule;\r
141   private String        directOp ="yes";\r
142   private String        passwdProtection ="yes";\r
143   // Singelton / Kontruktor\r
144   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();\r
145   public static ServletModule getInstance() { return instance; }\r
146 \r
147   private ServletModuleOpenIndy() {\r
148     super();\r
149     try {\r
150       logger = new LoggerWrapper("ServletModule.OpenIndy");\r
151 \r
152       commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");\r
153       commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");\r
154       commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");\r
155       postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");\r
156       postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");\r
157       postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");\r
158       searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");\r
159       prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");\r
160       sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");\r
161       directOp = configuration.getString("DirectOpenposting").toLowerCase();\r
162       passwdProtection = configuration.getString("PasswdProtection").toLowerCase();\r
163       mainModule = new ModuleComment(DatabaseComment.getInstance());\r
164       contentModule = new ModuleContent(DatabaseContent.getInstance());\r
165       themenModule = new ModuleTopics(DatabaseTopics.getInstance());\r
166       imageModule = new ModuleImages(DatabaseImages.getInstance());\r
167       defaultAction="addposting";\r
168 \r
169     }\r
170     catch (StorageObjectFailure e) {\r
171       logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());\r
172     }\r
173   }\r
174 \r
175 \r
176   /**\r
177    *  Method for making a comment\r
178    */\r
179 \r
180   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
181   {\r
182     String aid = req.getParameter("aid"); // the article id the comment will belong to\r
183     String language = req.getParameter("language");\r
184 \r
185     if (aid!=null && !aid.equals("")) {\r
186       try {\r
187         SimpleHash mergeData = new SimpleHash();\r
188 \r
189         // onetimepasswd\r
190         if (passwdProtection.equals("yes")) {\r
191           String passwd = this.createOneTimePasswd();\r
192           HttpSession session = req.getSession(false);\r
193           session.setAttribute("passwd", passwd);\r
194           mergeData.put("passwd", passwd);\r
195         }\r
196 \r
197         if (language != null) {\r
198           HttpSession session = req.getSession(false);\r
199           session.setAttribute("Locale", new Locale(language, ""));\r
200           session.setAttribute("passwd", language);\r
201         }\r
202 \r
203         mergeData.put("aid", aid);\r
204 \r
205         SimpleHash extraInfo = new SimpleHash();\r
206         extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());\r
207 \r
208         deliver(req, res, mergeData, extraInfo, commentFormTemplate);\r
209       }\r
210       catch (Throwable t) {\r
211         throw new ServletModuleException("ServletModuleOpenIndy.addcomment: " + t.getMessage());\r
212       }\r
213     }\r
214     else throw new ServletModuleException("aid not set!");\r
215   }\r
216 \r
217   /**\r
218    *  Method for inserting a comment into the Database and delivering\r
219    *  the commentDone Page\r
220    */\r
221 \r
222   public void inscomment(HttpServletRequest req, HttpServletResponse res)\r
223     throws ServletModuleException,ServletModuleUserException\r
224   {\r
225     String aid = req.getParameter("to_media"); // the article id the comment will belong to\r
226     if (aid!=null && !aid.equals(""))\r
227       {\r
228         // ok, collecting data from form\r
229         try {\r
230           Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());\r
231 \r
232           //no html in comments(for now)\r
233           for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
234             String k=(String)i.next();\r
235             String v=(String)withValues.get(k);\r
236 \r
237             withValues.put(k,StringUtil.removeHTMLTags(v));\r
238           }\r
239           withValues.put("is_published","1");\r
240           withValues.put("to_comment_status","1");\r
241 \r
242           //checking the onetimepasswd\r
243           if(passwdProtection.equals("yes")){\r
244             HttpSession session = req.getSession(false);\r
245             String sessionPasswd = (String)session.getAttribute("passwd");\r
246             if ( sessionPasswd == null){\r
247               throw new ServletModuleUserException("Lost password");\r
248             }\r
249             String passwd = req.getParameter("passwd");\r
250             if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
251               throw new ServletModuleUserException("Missing password");\r
252             }\r
253             session.invalidate();\r
254           }\r
255 \r
256           // inserting into database\r
257           String id = mainModule.add(withValues);\r
258           logger.debug("id: "+id);\r
259           //insert was not successfull\r
260           if(id==null){\r
261             deliver(req, res, new SimpleHash(), commentFormDupeTemplate);\r
262           } else {\r
263             DatabaseContent.getInstance().setUnproduced("id="+aid);\r
264 \r
265             try {\r
266               EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);\r
267               MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
268             }\r
269             catch (Throwable t) {\r
270               throw new ServletModuleException(t.getMessage());\r
271             }\r
272           }\r
273 \r
274           // redirecting to url\r
275           // should implement back to article\r
276           SimpleHash mergeData = new SimpleHash();\r
277           deliver(req, res, mergeData, commentFormDoneTemplate);\r
278         }\r
279         catch (StorageObjectFailure e) { throw new ServletModuleException(e.toString());}\r
280         catch (ModuleException e) { throw new ServletModuleException(e.toString());}\r
281 \r
282       }\r
283     else throw new ServletModuleException("aid not set!");\r
284 \r
285   }\r
286 \r
287   /**\r
288    *  Method for delivering the form-Page for open posting\r
289    */\r
290 \r
291   public void addposting(HttpServletRequest req, HttpServletResponse res)\r
292     throws ServletModuleException {\r
293     SimpleHash mergeData = new SimpleHash();\r
294 \r
295     // onetimepasswd\r
296     if(passwdProtection.equals("yes")){\r
297       String passwd = this.createOneTimePasswd();\r
298       HttpSession session = req.getSession(false);\r
299       session.setAttribute("passwd",passwd);\r
300       mergeData.put("passwd", passwd);\r
301     }\r
302 \r
303     String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");\r
304     String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");\r
305     String numOfMedia = req.getParameter("medianum");\r
306 \r
307     if(numOfMedia==null||numOfMedia.equals("")){\r
308       numOfMedia=defaultMedia;\r
309     }\r
310     else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
311       numOfMedia = maxMedia;\r
312     }\r
313 \r
314     int mediaNum = Integer.parseInt(numOfMedia);\r
315     SimpleList mediaFields = new SimpleList();\r
316     for(int i =0; i<mediaNum;i++){\r
317       Integer mNum = new Integer(i+1);\r
318       mediaFields.add(mNum.toString());\r
319     }\r
320     mergeData.put("medianum",numOfMedia);\r
321     mergeData.put("mediafields",mediaFields);\r
322 \r
323 \r
324     SimpleHash extraInfo = new SimpleHash();\r
325     try{\r
326       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );\r
327       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());\r
328 \r
329       extraInfo.put("topics", themenModule.getTopicsList());\r
330 \r
331     }\r
332     catch (Exception e) {\r
333       logger.error("languagePopUpData or getTopicslist failed "+e.toString());\r
334       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());\r
335     }\r
336 \r
337 \r
338 \r
339     deliver(req, res, mergeData, extraInfo, postingFormTemplate);\r
340   }\r
341 \r
342   /**\r
343    *  Method for inserting an open posting into the Database and delivering\r
344    *  the postingDone Page\r
345    */\r
346 \r
347   public void insposting(HttpServletRequest req, HttpServletResponse res)\r
348     throws ServletModuleException, ServletModuleUserException\r
349   {\r
350     SimpleHash mergeData = new SimpleHash();\r
351     boolean setMedia=false;\r
352     boolean setTopic = false;\r
353 \r
354     try {\r
355 \r
356       WebdbMultipartRequest mp = null;\r
357       EntityList mediaList = null;\r
358       try {\r
359         // new MediaRequest, "1" is the id for the openPosting user\r
360         MediaRequest mediaReq = new MediaRequest("1", true);\r
361         mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
362         mediaList = mediaReq.getEntityList();\r
363       }\r
364       catch (FileHandlerUserException e) {\r
365         throw new ServletModuleUserException(e.getMessage());\r
366       } catch (PropertiesConfigExc e) {\r
367         throw new ServletModuleUserException(e.getMessage());\r
368       }\r
369 \r
370       Map withValues = mp.getParameters();\r
371 \r
372       //checking the onetimepasswd\r
373       if(passwdProtection.equals("yes")){\r
374         HttpSession session = req.getSession(false);\r
375         String sessionPasswd = (String)session.getAttribute("passwd");\r
376         if ( sessionPasswd == null){\r
377           throw new ServletModuleUserException("Lost password");\r
378         }\r
379         String passwd = (String)withValues.get("passwd");\r
380         if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
381           throw new ServletModuleUserException("Missing password");\r
382         }\r
383         session.invalidate();\r
384       }\r
385 \r
386       if ((((String)withValues.get("title")).length() == 0) ||\r
387           (((String)withValues.get("description")).length() == 0) ||\r
388           (((String)withValues.get("content_data")).length() == 0))\r
389         throw new ServletModuleUserException("Missing field");\r
390 \r
391       // call the routines that escape html\r
392 \r
393       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
394         String k=(String)i.next();\r
395         String v=(String)withValues.get(k);\r
396 \r
397         if (k.equals("content_data")){\r
398           //this doesn't quite work yet, so for now, all html goes\r
399           //withValues.put(k,StringUtil.approveHTMLTags(v));\r
400           withValues.put(k,StringUtil.deleteForbiddenTags(v));\r
401         } else if (k.equals("description")) {\r
402           String tmp = StringUtil.deleteForbiddenTags(v);\r
403           withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));\r
404         } else {\r
405           withValues.put(k,StringUtil.removeHTMLTags(v));\r
406         }\r
407 \r
408       }\r
409 \r
410       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
411       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));\r
412       withValues.put("is_produced", "0");\r
413       // by default stuff is published, they can be un-published through the\r
414       // admin interface.\r
415       withValues.put("is_published","1");\r
416       // if op direct article-type == newswire\r
417       if (directOp.equals("yes")) withValues.put("to_article_type","1");\r
418 \r
419       withValues.put("to_publisher","1");\r
420 \r
421       // owner is openposting user\r
422       //      ML: this is not multi-language friendly and this can be done in a template\r
423       //      if (withValues.get("creator").toString().equals(""))\r
424       //        withValues.put("creator","Anonym");\r
425 \r
426       // inserting  content into database\r
427       String cid = contentModule.add(withValues);\r
428       logger.debug("id: "+cid);\r
429       //insert was not successfull\r
430       if(cid==null){\r
431         //How do we know that it was not succesful cause of a\r
432         //dupe, what if it failed cause of "No space left on device"?\r
433         //Or is there something I am missing? Wouldn't it be better\r
434         //to have an explicit dupe check and then insert? I have no\r
435         //idea what I am talking about. this comment is in case\r
436         //I forget to explicitely ask. -mh\r
437         deliver(req, res, mergeData, postingFormDupeTemplate);\r
438       }\r
439 \r
440       String[] to_topicsArr = mp.getParameterValues("to_topic");\r
441 \r
442       if (to_topicsArr != null && to_topicsArr.length > 0) {\r
443         try{\r
444           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);\r
445           setTopic = true;\r
446         }\r
447         catch (Exception e) {\r
448           logger.error("setting content_x_topic failed");\r
449           contentModule.deleteById(cid);\r
450           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());\r
451         } //end try\r
452       } //end if\r
453 \r
454       //if we're here all is ok... associate the media to the article\r
455       for(int i=0;i<mediaList.size();i++) {\r
456         Entity mediaEnt = (Entity)mediaList.elementAt(i);\r
457         DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());\r
458       }\r
459 \r
460       try {\r
461         MirGlobal.localizer().openPostings().afterContentPosting(\r
462                                                                  (EntityContent)contentModule.getById(cid));\r
463       }\r
464       catch (Throwable t) {\r
465         throw new ServletModuleException(t.getMessage());\r
466       }\r
467     }\r
468     catch (FileHandlerException e) {\r
469       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
470       throw new ServletModuleException("MediaException: "+ e.getMessage());\r
471     }\r
472     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.getMessage());}\r
473     catch (StorageObjectFailure e) { throw new ServletModuleException("StorageObjectException" + e.getMessage());}\r
474     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.getMessage());}\r
475 \r
476     deliver(req, res, mergeData, postingFormDoneTemplate);\r
477   }\r
478 \r
479     /*\r
480    * Method for preparing and sending a content as an email message\r
481    */\r
482 \r
483   public void mail(HttpServletRequest req, HttpServletResponse res)\r
484     throws ServletModuleException, ServletModuleUserException {\r
485     String aid = req.getParameter("mail_aid");\r
486     if (aid == null){\r
487       throw new ServletModuleUserException("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");\r
488     }\r
489 \r
490     String to = req.getParameter("mail_to");\r
491     String from = req.getParameter("mail_from");\r
492     String from_name = req.getParameter("mail_from_name");\r
493     String comment = req.getParameter("mail_comment");\r
494     String mail_language = req.getParameter("mail_language");\r
495 \r
496     SimpleHash mergeData = new SimpleHash();\r
497 \r
498     if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){\r
499 \r
500       for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
501         String pName=(String)theParams.nextElement();\r
502         if (pName.startsWith("mail_")){\r
503           mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
504         }\r
505       }\r
506       deliver(req,res,mergeData,prepareMailTemplate);\r
507     }\r
508     else {\r
509       //run checks on to and from and mail_language to make sure no monkey business occurring\r
510       if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ){\r
511         throw new ServletModuleUserException("Sorry, you've entered an illegal character into the language field.  Go back and try again, asshole.");\r
512       }\r
513       if (to.indexOf('\n') != -1\r
514           || to.indexOf('\r') != -1\r
515           || to.indexOf(',') != -1\r
516           || from.indexOf('\n') != -1\r
517           || from.indexOf('\r') != -1\r
518           || from.indexOf(',') != -1 ){\r
519         throw new ServletModuleUserException("Sorry, you've entered an illegal character into the from or to field.  Go back and try again.");\r
520       }\r
521       EntityContent contentEnt;\r
522       try{\r
523         contentEnt = (EntityContent)contentModule.getById(aid);\r
524       }\r
525       catch (ModuleException e){\r
526         throw new ServletModuleUserException("Couldn't get content for article "+aid);\r
527       }\r
528       String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
529       String producerDocRoot=configuration.getString("Producer.DocRoot");\r
530       String publishPath = contentEnt.getValue("publish_path");\r
531       String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +\r
532                                                                                                          publishPath + "/" + aid + ".txt";\r
533 \r
534 \r
535       File inputFile = new File(txtFilePath);\r
536       String content;\r
537 \r
538       try{\r
539         FileReader in = new FileReader(inputFile);\r
540         StringWriter out = new StringWriter();\r
541         int c;\r
542         while ((c = in.read()) != -1)\r
543           out.write(c);\r
544         in.close();\r
545         content= out.toString();\r
546       }\r
547       catch (FileNotFoundException e){\r
548         throw new ServletModuleUserException("No text file found in " + txtFilePath);\r
549       }\r
550       catch (IOException e){\r
551         throw new ServletModuleUserException("Problem reading file in " + txtFilePath);\r
552       }\r
553       // add some headers\r
554       content = "To: " + to + "\nReply-To: "+ from + "\n" + content;\r
555       // put in the comment where it should go\r
556       if (comment != null) {\r
557         String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;\r
558         try {\r
559           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);\r
560         }\r
561         catch (Exception e){\r
562           throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());\r
563         }\r
564       }\r
565       else{\r
566         try {\r
567           content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");\r
568         }\r
569         catch (Exception e){\r
570           throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());\r
571         }\r
572       }\r
573 \r
574       SMTPClient client=new SMTPClient();\r
575       try {\r
576         int reply;\r
577         client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));\r
578 \r
579         reply = client.getReplyCode();\r
580 \r
581         if (!SMTPReply.isPositiveCompletion(reply)) {\r
582           client.disconnect();\r
583           throw new ServletModuleUserException("SMTP server refused connection.");\r
584         }\r
585 \r
586         client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);\r
587 \r
588         client.disconnect();\r
589         //mission accomplished\r
590         deliver(req, res, mergeData, sentMailTemplate);\r
591       }\r
592       catch(IOException e) {\r
593         if(client.isConnected()) {\r
594           try {\r
595             client.disconnect();\r
596           } catch(IOException f) {\r
597             // do nothing\r
598           }\r
599         }\r
600         throw new ServletModuleUserException(e.toString());\r
601       }\r
602     }\r
603   }\r
604 \r
605 \r
606   /*\r
607    * Method for querying a lucene index\r
608    */\r
609   public void search(HttpServletRequest req, HttpServletResponse res)\r
610     throws ServletModuleException, ServletModuleUserException {\r
611     try {\r
612       int increment=10;\r
613 \r
614       HttpSession session = req.getSession(false);\r
615 \r
616       String queryString="";\r
617 \r
618       SimpleHash mergeData = new SimpleHash();\r
619 \r
620       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");\r
621       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");\r
622       TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");\r
623       TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");\r
624       TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");\r
625       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");\r
626       TopicSearchTerm topicTerm = new TopicSearchTerm();\r
627       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();\r
628       AudioSearchTerm audioTerm = new AudioSearchTerm();\r
629       VideoSearchTerm videoTerm = new VideoSearchTerm();\r
630 \r
631       //make the query available to subsequent iterations\r
632 \r
633       for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
634         String pName=(String)theParams.nextElement();\r
635         if (pName.startsWith("search_")){\r
636           mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
637         }\r
638       }\r
639 \r
640       try{\r
641         mergeData.put("topics", themenModule.getTopicsAsSimpleList());\r
642       }\r
643       catch(ModuleException e) {\r
644         logger.debug("Can't get topics: " + e.toString());\r
645       }\r
646 \r
647       String searchBackValue = req.getParameter("search_back");\r
648       String searchForwardValue = req.getParameter("search_forward");\r
649 \r
650       if (searchBackValue != null){\r
651         int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
652         int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
653         if (newPosition<0)\r
654           newPosition=0;\r
655         if (newPosition >= totalHits)\r
656           newPosition=totalHits-1;\r
657         session.setAttribute("positionInResults",new Integer(newPosition));\r
658       }\r
659       else {\r
660         if (searchForwardValue != null){\r
661           int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
662           int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
663           if (newPosition<0)\r
664             newPosition=0;\r
665           if (newPosition >= totalHits)\r
666             newPosition=totalHits-1;\r
667 \r
668           session.setAttribute("positionInResults",new Integer(newPosition));\r
669         }\r
670         else {\r
671           String indexPath=configuration.getString("IndexPath");\r
672 \r
673 \r
674           String creatorFragment = creatorTerm.makeTerm(req);\r
675           if (creatorFragment != null){\r
676             queryString = queryString + " +" + creatorFragment;\r
677           }\r
678 \r
679           // search title, description, and content for something\r
680           // the contentTerm uses param "search_boolean" to combine its terms\r
681           String contentFragment = contentTerm.makeTerm(req);\r
682           if (contentFragment != null){\r
683             logger.debug("contentFragment: " + contentFragment);\r
684             queryString = queryString + " +" + contentFragment;\r
685           }\r
686 \r
687           String topicFragment = topicTerm.makeTerm(req);\r
688           if (topicFragment != null){\r
689             queryString = queryString + " +" + topicFragment;\r
690           }\r
691 \r
692           String imagesFragment = imagesTerm.makeTerm(req);\r
693           if (imagesFragment != null){\r
694             queryString = queryString + " +" + imagesFragment;\r
695           }\r
696 \r
697           String audioFragment = audioTerm.makeTerm(req);\r
698           if (audioFragment != null){\r
699             queryString = queryString + " +" + audioFragment;\r
700           }\r
701 \r
702           String videoFragment = videoTerm.makeTerm(req);\r
703           if (videoFragment != null){\r
704             queryString = queryString + " +" + videoFragment;\r
705           }\r
706 \r
707           if (queryString == null || queryString == ""){\r
708             queryString = "";\r
709           }\r
710           else{\r
711             try{\r
712               Searcher searcher = null;\r
713               try {\r
714                 searcher = new IndexSearcher(indexPath);\r
715               }\r
716               catch(IOException e) {\r
717                 logger.debug("Can't open indexPath: " + indexPath);\r
718                 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());\r
719               }\r
720 \r
721               Query query = null;\r
722               try {\r
723                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
724               }\r
725               catch(Exception e) {\r
726                 searcher.close();\r
727                 logger.debug("Query don't parse: " + queryString);\r
728                 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");\r
729               }\r
730 \r
731               Hits hits = null;\r
732               try {\r
733                 hits = searcher.search(query);\r
734               }\r
735               catch(IOException e) {\r
736                 searcher.close();\r
737                 logger.debug("Can't get hits: " + e.toString());\r
738                 throw new ServletModuleUserException("Problem getting hits!");\r
739               }\r
740 \r
741               int start = 0;\r
742               int end = hits.length();\r
743 \r
744               String sortBy=req.getParameter("search_sort");\r
745               if (sortBy == null || sortBy.equals("")){\r
746                 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");\r
747               }\r
748 \r
749               // here is where the documents will go for storage across sessions\r
750               ArrayList theDocumentsSorted = new ArrayList();\r
751 \r
752               if (sortBy.equals("score")){\r
753                 for(int i = start; i < end; i++) {\r
754                   theDocumentsSorted.add(hits.doc(i));\r
755                 }\r
756               }\r
757               else{\r
758                 // then we'll sort by date!\r
759                 Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
760                 for(int i = start; i < end; i++) {\r
761                   String creationDate=(hits.doc(i)).get("creationDate");\r
762                   // do a little dance in case two contents created at the same second!\r
763                   if (dateToPosition.containsKey(creationDate)){\r
764                     ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
765                   }\r
766                   else{\r
767                     ArrayList thePositions = new ArrayList();\r
768                     thePositions.add(new Integer(i));\r
769                     dateToPosition.put(creationDate,thePositions);\r
770                   }\r
771                 }\r
772                 Set keys = dateToPosition.keySet();\r
773                 ArrayList keyList= new ArrayList(keys);\r
774                 Collections.sort(keyList);\r
775                 if (sortBy.equals("date_desc")){\r
776                   Collections.reverse(keyList);\r
777                 }\r
778                 else{\r
779                   if (!sortBy.equals("date_asc")){\r
780                     throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);\r
781                   }\r
782                 }\r
783                 ListIterator keyTraverser = keyList.listIterator();\r
784                 while (keyTraverser.hasNext()){\r
785                   ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
786                   ListIterator positionsTraverser=positions.listIterator();\r
787                   while (positionsTraverser.hasNext()){\r
788                     theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
789                   }\r
790                 }\r
791               }\r
792 \r
793               try{\r
794                 searcher.close();\r
795               }\r
796               catch (IOException e){\r
797                 logger.debug("Can't close searcher: " + e.toString());\r
798                 throw new ServletModuleUserException("Problem closing searcher(normal)!");\r
799               }\r
800 \r
801 \r
802               session.removeAttribute("numberOfHits");\r
803               session.removeAttribute("theDocumentsSorted");\r
804               session.removeAttribute("positionInResults");\r
805 \r
806               session.setAttribute("numberOfHits",new Integer(end));\r
807               session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
808               session.setAttribute("positionInResults",new Integer(0));\r
809 \r
810             }\r
811             catch (IOException e){\r
812               logger.debug("Can't close searcher: " + e.toString());\r
813               throw new ServletModuleUserException("Problem closing searcher!");\r
814             }\r
815           }\r
816         }\r
817       }\r
818 \r
819       try {\r
820         ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
821         if (theDocs != null){\r
822 \r
823           mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
824           SimpleList theHits = new SimpleList();\r
825           int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
826           int terminus;\r
827           int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
828 \r
829           if (!(pIR+increment>=numHits)){\r
830             mergeData.put("hasNext","y");\r
831           }\r
832           if (pIR>0){\r
833             mergeData.put("hasPrevious","y");\r
834           }\r
835 \r
836           if ((pIR+increment)>numHits){\r
837             terminus=numHits;\r
838           }\r
839           else {\r
840             terminus=pIR+increment;\r
841           }\r
842           for(int i = pIR; i < terminus; i++) {\r
843             SimpleHash h = new SimpleHash();\r
844             Document theHit = (Document)theDocs.get(i);\r
845             whereTerm.returnMeta(h,theHit);\r
846             creatorTerm.returnMeta(h,theHit);\r
847             titleTerm.returnMeta(h,theHit);\r
848             descriptionTerm.returnMeta(h,theHit);\r
849             dateTerm.returnMeta(h,theHit);\r
850             imagesTerm.returnMeta(h,theHit);\r
851             audioTerm.returnMeta(h,theHit);\r
852             videoTerm.returnMeta(h,theHit);\r
853             theHits.add(h);\r
854           }\r
855           mergeData.put("hits",theHits);\r
856         }\r
857       }\r
858       catch (Exception e) {\r
859         logger.debug("Can't iterate over hits: " + e.toString());\r
860         throw new ServletModuleUserException("Problem getting hits!");\r
861       }\r
862 \r
863       mergeData.put("queryString",queryString);\r
864       deliver(req,res,mergeData,searchResultsTemplate);\r
865     }\r
866     catch (NullPointerException n){\r
867       n.printStackTrace();\r
868       throw new ServletModuleUserException("Null Pointer"+n.toString());\r
869     }\r
870   }\r
871 \r
872   /*\r
873    * Method for dynamically generating a pdf from a fo file\r
874    */\r
875   public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
876     throws ServletModuleException, ServletModuleUserException {\r
877     String ID_REQUEST_PARAM = "id";\r
878     String language = req.getParameter("language");\r
879     String generateFO=configuration.getString("GenerateFO");\r
880     String generatePDF=configuration.getString("GeneratePDF");\r
881 \r
882 \r
883     //don't do anything if we are not making FO files, or if we are\r
884     //pregenerating PDF's\r
885     if (generateFO.equals("yes") && generatePDF.equals("no")){\r
886       //fop complains unless you do the logging this way\r
887       org.apache.log.Logger log = null;\r
888       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
889       log = hierarchy.getLoggerFor("fop");\r
890       log.setPriority(Priority.WARN);\r
891 \r
892       String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
893       String producerDocRoot=configuration.getString("Producer.DocRoot");\r
894       //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
895       String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");\r
896       try {\r
897         String idParam = req.getParameter(ID_REQUEST_PARAM);\r
898         if (idParam != null) {\r
899           EntityContent contentEnt =\r
900             (EntityContent)contentModule.getById(idParam);\r
901           String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));\r
902           String foFile;\r
903 \r
904           if (language == null){\r
905             foFile = producerStorageRoot + producerDocRoot + "/"\r
906               + publishPath  + idParam + ".fo";\r
907           }\r
908           else{\r
909             foFile = producerStorageRoot + producerDocRoot + "/"\r
910               + language + publishPath  + idParam + ".fo";\r
911           }\r
912           logger.debug("USING FILES" + foFile + " and " + xslSheet);\r
913           XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
914                                                         new File(xslSheet));\r
915 \r
916           ByteArrayOutputStream out = new ByteArrayOutputStream();\r
917           res.setContentType("application/pdf");\r
918 \r
919           Driver driver = new Driver();\r
920           driver.setLogger(log);\r
921           driver.setRenderer(Driver.RENDER_PDF);\r
922           driver.setOutputStream(out);\r
923           driver.render(input.getParser(), input.getInputSource());\r
924 \r
925           byte[] content = out.toByteArray();\r
926           res.setContentLength(content.length);\r
927           res.getOutputStream().write(content);\r
928           res.getOutputStream().flush();\r
929         } else {\r
930           throw new ServletModuleUserException("Missing id parameter.");\r
931         }\r
932       } catch (Exception ex) {\r
933         logger.error(ex.toString());\r
934         throw new ServletModuleException(ex.toString());\r
935       }\r
936     } else {\r
937       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");\r
938     }\r
939   }\r
940 \r
941   private void _throwBadContentType (String fileName, String contentType)\r
942     throws ServletModuleUserException {\r
943 \r
944     logger.error("Wrong file type uploaded!: " + fileName+" "\r
945                           +contentType);\r
946     throw new ServletModuleUserException("The file you uploaded is of the "\r
947                                          +"following mime-type: "+contentType\r
948                                          +", we do not support this mime-type. "\r
949                                          +"Error One or more files of unrecognized type. Sorry");\r
950   }\r
951 \r
952   protected String createOneTimePasswd(){\r
953     Random r = new Random();\r
954     int random = r.nextInt();\r
955     long l = System.currentTimeMillis();\r
956     l = (l*l*l*l)/random;\r
957     if(l<0) l = l * -1;\r
958     String returnString = ""+l;\r
959     return returnString.substring(5);\r
960   }\r
961 \r
962 \r
963   /* this is an overwritten method of ServletModule in order\r
964      to use different bundles for open and admin */\r
965   public void deliver(HttpServletRequest req, HttpServletResponse res,\r
966                       TemplateModelRoot rtm, TemplateModelRoot popups,\r
967                       String templateFilename)\r
968     throws ServletModuleException {\r
969     if (rtm == null) rtm = new SimpleHash();\r
970     try {\r
971       PrintWriter out = res.getWriter();\r
972       HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,\r
973                                     getLocale(req), "bundles.open");\r
974       out.close();\r
975     }   catch (HTMLParseException e) {\r
976       throw new ServletModuleException(e.toString());\r
977     } catch (IOException e) {\r
978       throw new ServletModuleException(e.toString());\r
979     }\r
980   }\r
981 }\r
982 \r
983 \r
984 \r