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