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