slightly improved the way next/prev page was determined.
[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.57 2003/01/21 18:32:03 zapata 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 = StringUtil.webdbDate2path(contentEnt.getValue("date"));\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(MirConfig.getProp("ServletModule.OpenIndy.SMTPServer"));\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 searchBackValue = req.getParameter("search_back");\r
614       String searchForwardValue = req.getParameter("search_forward");\r
615 \r
616       if (searchBackValue != null){\r
617         int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
618         int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
619         if (newPosition<0)\r
620           newPosition=0;\r
621         if (newPosition >= totalHits)\r
622           newPosition=totalHits-1;\r
623         session.setAttribute("positionInResults",new Integer(newPosition));\r
624       }\r
625       else {\r
626         if (searchForwardValue != null){\r
627           int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
628           int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
629           if (newPosition<0)\r
630             newPosition=0;\r
631           if (newPosition >= totalHits)\r
632             newPosition=totalHits-1;\r
633 \r
634           session.setAttribute("positionInResults",new Integer(newPosition));\r
635         }\r
636         else {\r
637           String indexPath=MirConfig.getProp("IndexPath");\r
638 \r
639 \r
640           String creatorFragment = creatorTerm.makeTerm(req);\r
641           if (creatorFragment != null){\r
642             queryString = queryString + " +" + creatorFragment;\r
643           }\r
644 \r
645           // search title, description, and content for something\r
646           // the contentTerm uses param "search_boolean" to combine its terms\r
647           String contentFragment = contentTerm.makeTerm(req);\r
648           if (contentFragment != null){\r
649             logger.debug("contentFragment: " + contentFragment);\r
650             queryString = queryString + " +" + contentFragment;\r
651           }\r
652 \r
653           String topicFragment = topicTerm.makeTerm(req);\r
654           if (topicFragment != null){\r
655             queryString = queryString + " +" + topicFragment;\r
656           }\r
657 \r
658           String imagesFragment = imagesTerm.makeTerm(req);\r
659           if (imagesFragment != null){\r
660             queryString = queryString + " +" + imagesFragment;\r
661           }\r
662 \r
663           String audioFragment = audioTerm.makeTerm(req);\r
664           if (audioFragment != null){\r
665             queryString = queryString + " +" + audioFragment;\r
666           }\r
667 \r
668           String videoFragment = videoTerm.makeTerm(req);\r
669           if (videoFragment != null){\r
670             queryString = queryString + " +" + videoFragment;\r
671           }\r
672 \r
673           if (queryString == null || queryString == ""){\r
674             queryString = "";\r
675           }\r
676           else{\r
677             try{\r
678               Searcher searcher = null;\r
679               try {\r
680                 searcher = new IndexSearcher(indexPath);\r
681               }\r
682               catch(IOException e) {\r
683                 logger.debug("Can't open indexPath: " + indexPath);\r
684                 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());\r
685               }\r
686 \r
687               Query query = null;\r
688               try {\r
689                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
690               }\r
691               catch(Exception e) {\r
692                 searcher.close();\r
693                 logger.debug("Query don't parse: " + queryString);\r
694                 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");\r
695               }\r
696 \r
697               Hits hits = null;\r
698               try {\r
699                 hits = searcher.search(query);\r
700               }\r
701               catch(IOException e) {\r
702                 searcher.close();\r
703                 logger.debug("Can't get hits: " + e.toString());\r
704                 throw new ServletModuleUserException("Problem getting hits!");\r
705               }\r
706 \r
707               int start = 0;\r
708               int end = hits.length();\r
709 \r
710               String sortBy=req.getParameter("search_sort");\r
711               if (sortBy == null || sortBy.equals("")){\r
712                 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");\r
713               }\r
714 \r
715               // here is where the documents will go for storage across sessions\r
716               ArrayList theDocumentsSorted = new ArrayList();\r
717 \r
718               if (sortBy.equals("score")){\r
719                 for(int i = start; i < end; i++) {\r
720                   theDocumentsSorted.add(hits.doc(i));\r
721                 }\r
722               }\r
723               else{\r
724                 // then we'll sort by date!\r
725                 HashMap dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
726                 for(int i = start; i < end; i++) {\r
727                   String creationDate=(hits.doc(i)).get("creationDate");\r
728                   // do a little dance in case two contents created at the same second!\r
729                   if (dateToPosition.containsKey(creationDate)){\r
730                     ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
731                   }\r
732                   else{\r
733                     ArrayList thePositions = new ArrayList();\r
734                     thePositions.add(new Integer(i));\r
735                     dateToPosition.put(creationDate,thePositions);\r
736                   }\r
737                 }\r
738                 Set keys = dateToPosition.keySet();\r
739                 ArrayList keyList= new ArrayList(keys);\r
740                 Collections.sort(keyList);\r
741                 if (sortBy.equals("date_desc")){\r
742                   Collections.reverse(keyList);\r
743                 }\r
744                 else{\r
745                   if (!sortBy.equals("date_asc")){\r
746                     throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);\r
747                   }\r
748                 }\r
749                 ListIterator keyTraverser = keyList.listIterator();\r
750                 while (keyTraverser.hasNext()){\r
751                   ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
752                   ListIterator positionsTraverser=positions.listIterator();\r
753                   while (positionsTraverser.hasNext()){\r
754                     theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
755                   }\r
756                 }\r
757               }\r
758 \r
759               try{\r
760                 searcher.close();\r
761               }\r
762               catch (IOException e){\r
763                 logger.debug("Can't close searcher: " + e.toString());\r
764                 throw new ServletModuleUserException("Problem closing searcher(normal)!");\r
765               }\r
766 \r
767 \r
768               session.removeAttribute("numberOfHits");\r
769               session.removeAttribute("theDocumentsSorted");\r
770               session.removeAttribute("positionInResults");\r
771 \r
772               session.setAttribute("numberOfHits",new Integer(end));\r
773               session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
774               session.setAttribute("positionInResults",new Integer(0));\r
775 \r
776             }\r
777             catch (IOException e){\r
778               logger.debug("Can't close searcher: " + e.toString());\r
779               throw new ServletModuleUserException("Problem closing searcher!");\r
780             }\r
781           }\r
782         }\r
783       }\r
784 \r
785       try {\r
786         ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
787         if (theDocs != null){\r
788 \r
789           mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
790           SimpleList theHits = new SimpleList();\r
791           int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
792           int terminus;\r
793           int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
794 \r
795           if (!(pIR+increment>=numHits)){\r
796             mergeData.put("hasNext","y");\r
797           }\r
798           if (pIR>0){\r
799             mergeData.put("hasPrevious","y");\r
800           }\r
801 \r
802           if ((pIR+increment)>numHits){\r
803             terminus=numHits;\r
804           }\r
805           else {\r
806             terminus=pIR+increment;\r
807           }\r
808           for(int i = pIR; i < terminus; i++) {\r
809             SimpleHash h = new SimpleHash();\r
810             Document theHit = (Document)theDocs.get(i);\r
811             whereTerm.returnMeta(h,theHit);\r
812             creatorTerm.returnMeta(h,theHit);\r
813             titleTerm.returnMeta(h,theHit);\r
814             descriptionTerm.returnMeta(h,theHit);\r
815             dateTerm.returnMeta(h,theHit);\r
816             imagesTerm.returnMeta(h,theHit);\r
817             audioTerm.returnMeta(h,theHit);\r
818             videoTerm.returnMeta(h,theHit);\r
819             theHits.add(h);\r
820           }\r
821           mergeData.put("hits",theHits);\r
822         }\r
823       }\r
824       catch (Exception e) {\r
825         logger.debug("Can't iterate over hits: " + e.toString());\r
826         throw new ServletModuleUserException("Problem getting hits!");\r
827       }\r
828 \r
829       mergeData.put("queryString",queryString);\r
830       deliver(req,res,mergeData,searchResultsTemplate);\r
831     }\r
832     catch (NullPointerException n){\r
833       n.printStackTrace();\r
834       throw new ServletModuleUserException("Null Pointer"+n.toString());\r
835     }\r
836   }\r
837 \r
838   /*\r
839    * Method for dynamically generating a pdf from a fo file\r
840    */\r
841   public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
842     throws ServletModuleException, ServletModuleUserException {\r
843     String ID_REQUEST_PARAM = "id";\r
844     String language = req.getParameter("language");\r
845 \r
846     String generateFO=MirConfig.getProp("GenerateFO");\r
847     String generatePDF=MirConfig.getProp("GeneratePDF");\r
848 \r
849     //don't do anything if we are not making FO files, or if we are\r
850     //pregenerating PDF's\r
851     if (generateFO.equals("yes") && generatePDF.equals("no")){\r
852       //fop complains unless you do the logging this way\r
853       org.apache.log.Logger log = null;\r
854       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
855       log = hierarchy.getLoggerFor("fop");\r
856       log.setPriority(Priority.WARN);\r
857 \r
858       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");\r
859       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");\r
860       //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
861       String xslSheet=MirConfig.getProp("Producer.HTML2FOStyleSheet");\r
862       try {\r
863         String idParam = req.getParameter(ID_REQUEST_PARAM);\r
864         if (idParam != null) {\r
865           EntityContent contentEnt =\r
866             (EntityContent)contentModule.getById(idParam);\r
867           String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));\r
868           String foFile;\r
869 \r
870           if (language == null){\r
871             foFile = producerStorageRoot + producerDocRoot + "/"\r
872               + publishPath  + idParam + ".fo";\r
873           }\r
874           else{\r
875             foFile = producerStorageRoot + producerDocRoot + "/"\r
876               + language + publishPath  + idParam + ".fo";\r
877           }\r
878           logger.debug("USING FILES" + foFile + " and " + xslSheet);\r
879           XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
880                                                         new File(xslSheet));\r
881 \r
882           ByteArrayOutputStream out = new ByteArrayOutputStream();\r
883           res.setContentType("application/pdf");\r
884 \r
885           Driver driver = new Driver();\r
886           driver.setLogger(log);\r
887           driver.setRenderer(Driver.RENDER_PDF);\r
888           driver.setOutputStream(out);\r
889           driver.render(input.getParser(), input.getInputSource());\r
890 \r
891           byte[] content = out.toByteArray();\r
892           res.setContentLength(content.length);\r
893           res.getOutputStream().write(content);\r
894           res.getOutputStream().flush();\r
895         } else {\r
896           throw new ServletModuleUserException("Missing id parameter.");\r
897         }\r
898       } catch (Exception ex) {\r
899         logger.error(ex.toString());\r
900         throw new ServletModuleException(ex.toString());\r
901       }\r
902     } else {\r
903       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");\r
904     }\r
905   }\r
906 \r
907   private void _throwBadContentType (String fileName, String contentType)\r
908     throws ServletModuleUserException {\r
909 \r
910     logger.error("Wrong file type uploaded!: " + fileName+" "\r
911                           +contentType);\r
912     throw new ServletModuleUserException("The file you uploaded is of the "\r
913                                          +"following mime-type: "+contentType\r
914                                          +", we do not support this mime-type. "\r
915                                          +"Error One or more files of unrecognized type. Sorry");\r
916   }\r
917 \r
918   protected String createOneTimePasswd(){\r
919     Random r = new Random();\r
920     int random = r.nextInt();\r
921     long l = System.currentTimeMillis();\r
922     l = (l*l*l*l)/random;\r
923     if(l<0) l = l * -1;\r
924     String returnString = ""+l;\r
925     return returnString.substring(5);\r
926   }\r
927 \r
928 \r
929   /* this is an overwritten method of ServletModule in order\r
930      to use different bundles for open and admin */\r
931   public void deliver(HttpServletRequest req, HttpServletResponse res,\r
932                       TemplateModelRoot rtm, TemplateModelRoot popups,\r
933                       String templateFilename)\r
934     throws ServletModuleException {\r
935     if (rtm == null) rtm = new SimpleHash();\r
936     try {\r
937       PrintWriter out = res.getWriter();\r
938       HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,\r
939                                     getLocale(req), "bundles.open");\r
940       out.close();\r
941     }   catch (HTMLParseException e) {\r
942       throw new ServletModuleException(e.toString());\r
943     } catch (IOException e) {\r
944       throw new ServletModuleException(e.toString());\r
945     }\r
946   }\r
947 }\r
948 \r
949 \r
950 \r