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