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