cleanup coding style of getpdf() method
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 package mircoders.servlet;
2
3 import java.io.*;
4 import java.lang.*;
5 import java.sql.*;
6 import java.util.*;
7 import java.net.*;
8 import java.lang.reflect.*;
9 import javax.servlet.*;
10 import javax.servlet.http.*;
11
12 import freemarker.template.*;
13 import com.oreilly.servlet.multipart.*;
14 import com.oreilly.servlet.*;
15
16 import org.xml.sax.InputSource;
17 import org.xml.sax.XMLReader;
18
19 import org.apache.fop.apps.Driver;
20 import org.apache.fop.apps.Version;
21 import org.apache.fop.apps.XSLTInputHandler;
22
23 import org.apache.log.*;
24
25 import mir.servlet.*;
26 import mir.module.*;
27 import mir.misc.*;
28 import mir.entity.*;
29 import mir.storage.*;
30 import mir.media.*;
31
32 import mircoders.entity.*;
33 import mircoders.storage.*;
34 import mircoders.module.*;
35 import mircoders.producer.*;
36 import mircoders.media.MediaRequest;
37
38 /*
39  *  ServletModuleOpenIndy -
40  *   is the open-access-servlet, which is responsible for
41  *    adding comments to articles &
42  *    open-postings to the newswire
43  *
44  * @author $Author: mh $
45  * @version $Revision: 1.38 $ $Date: 2002/07/21 22:50:14 $
46  *
47  * $Log: ServletModuleOpenIndy.java,v $
48  * Revision 1.38  2002/07/21 22:50:14  mh
49  * cleanup coding style of getpdf() method
50  *
51  * Revision 1.37  2002/07/21 22:41:45  mh
52  * make use of new MediaRequest class. A big cleanup and optimization.
53  *
54  * Revision 1.36  2002/06/29 15:45:20  mh
55  * cvs macros
56  *
57  *
58  */
59
60 public class ServletModuleOpenIndy extends ServletModule
61 {
62
63   private String        commentFormTemplate, commentFormDoneTemplate,
64                         commentFormDupeTemplate;
65   private String        postingFormTemplate, postingFormDoneTemplate,
66                         postingFormDupeTemplate;
67   private ModuleContent contentModule;
68   private ModuleImages  imageModule;
69   private ModuleTopics  themenModule;
70   private String        directOp ="yes";
71   private String        passwdProtection ="yes";
72   // Singelton / Kontruktor
73   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
74   public static ServletModule getInstance() { return instance; }
75
76   private ServletModuleOpenIndy() {
77     try {
78       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
79       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
80       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
81       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
82       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
83       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
84       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
85       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
86                         passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
87       mainModule = new ModuleComment(DatabaseComment.getInstance());
88       contentModule = new ModuleContent(DatabaseContent.getInstance());
89       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
90       imageModule = new ModuleImages(DatabaseImages.getInstance());
91       defaultAction="addposting";
92                         
93     }
94     catch (StorageObjectException e) {
95         theLog.printError("servletmoduleopenindy could not be initialized");
96     }
97   }
98
99
100   /**
101    *  Method for making a comment
102    */
103
104   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
105   {
106     String aid = req.getParameter("aid"); // the article id the comment will belong to
107     if (aid!=null && !aid.equals(""))
108     {
109                         SimpleHash mergeData = new SimpleHash();
110
111                         // onetimepasswd
112                         if(passwdProtection.equals("yes")){
113                                 String passwd = this.createOneTimePasswd();
114                                 System.out.println(passwd);
115                                 HttpSession session = req.getSession(false);
116                                 session.setAttribute("passwd",passwd);
117                                 mergeData.put("passwd", passwd);
118                         }
119                         
120       mergeData.put("aid", aid);
121       deliver(req, res, mergeData, commentFormTemplate);
122     }
123     else throw new ServletModuleException("aid not set!");
124   }
125
126   /**
127    *  Method for inserting a comment into the Database and delivering
128    *  the commentDone Page
129    */
130
131   public void inscomment(HttpServletRequest req, HttpServletResponse res)
132         throws ServletModuleException,ServletModuleUserException
133   {
134     String aid = req.getParameter("to_media"); // the article id the comment will belong to
135     if (aid!=null && !aid.equals(""))
136     {
137       // ok, collecting data from form
138       try {
139         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
140        
141         //no html in comments(for now)
142         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
143             String k=(String)i.next();
144             String v=(String)withValues.get(k);
145             
146             withValues.put(k,StringUtil.removeHTMLTags(v));
147         }
148         withValues.put("is_published","1");
149                                 
150                                 //checking the onetimepasswd
151                                 if(passwdProtection.equals("yes")){
152                                         HttpSession session = req.getSession(false);
153                                         String sessionPasswd = (String)session.getAttribute("passwd");
154                                         if ( sessionPasswd == null){
155                                                 throw new ServletModuleUserException("Lost password");
156                                         }
157                                         String passwd = req.getParameter("passwd");
158                                         if ( passwd == null || (!sessionPasswd.equals(passwd))) {
159                                                 throw new ServletModuleUserException("Missing password");
160                                         }
161                                         session.invalidate();
162                                 }
163                                 
164         // inserting into database
165         String id = mainModule.add(withValues);
166         theLog.printDebugInfo("id: "+id);
167         //insert was not successfull
168         if(id==null){
169           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
170         }
171         
172         // producing new page
173         new ProducerContent().handle(null, null, true, false, aid);
174
175         // sync the server
176         int exitValue = Helper.rsync();
177         theLog.printDebugInfo("rsync:"+exitValue);
178
179         // redirecting to url
180         // should implement back to article
181         SimpleHash mergeData = new SimpleHash();
182         deliver(req, res, mergeData, commentFormDoneTemplate);
183       }
184       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
185       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
186
187     }
188     else throw new ServletModuleException("aid not set!");
189
190   }
191
192   /**
193    *  Method for delivering the form-Page for open posting
194    */
195
196   public void addposting(HttpServletRequest req, HttpServletResponse res)
197     throws ServletModuleException {
198     SimpleHash mergeData = new SimpleHash();
199                 
200                 // onetimepasswd
201                 if(passwdProtection.equals("yes")){
202                         String passwd = this.createOneTimePasswd();
203                         System.out.println(passwd);
204                         HttpSession session = req.getSession(false);
205                         session.setAttribute("passwd",passwd);
206                         mergeData.put("passwd", passwd);
207                 }
208                         
209     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
210     String numOfMedia = req.getParameter("medianum");
211     if(numOfMedia==null||numOfMedia.equals("")){
212       numOfMedia="1";
213     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
214       numOfMedia = maxMedia;
215     }
216     
217     int mediaNum = Integer.parseInt(numOfMedia);
218     SimpleList mediaFields = new SimpleList();
219     for(int i =0; i<mediaNum;i++){
220       Integer mNum = new Integer(i+1);
221       mediaFields.add(mNum.toString());
222     }
223     mergeData.put("medianum",numOfMedia);
224     mergeData.put("mediafields",mediaFields);
225     
226     
227     SimpleHash extraInfo = new SimpleHash();
228     try{
229       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
230       extraInfo.put("languagePopUpData", popUpData );
231       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
232     } catch (Exception e) {
233       theLog.printError("languagePopUpData or getTopicslist failed "
234                         +e.toString());
235       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
236     }
237       
238     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
239   }
240
241   /**
242    *  Method for inserting an open posting into the Database and delivering
243    *  the postingDone Page
244    */
245
246   public void insposting(HttpServletRequest req, HttpServletResponse res)
247     throws ServletModuleException, ServletModuleUserException
248   {
249     SimpleHash mergeData = new SimpleHash();
250     boolean setMedia=false;
251                 boolean setTopic = false;
252
253     try {
254       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
255
256       EntityList mediaList = null;
257       try {
258         // new MediaRequest, "1" is the id for the openPosting user
259         mediaList = new MediaRequest(mp, "1").getMedia(true, true);
260       } catch (MirMediaUserException e) {
261         throw new ServletModuleUserException(e.getMsg());
262       }
263           
264       HashMap withValues = mp.getParameters();
265                                                         
266                         //checking the onetimepasswd
267                         if(passwdProtection.equals("yes")){
268                                 HttpSession session = req.getSession(false);
269                                 String sessionPasswd = (String)session.getAttribute("passwd");
270                                 if ( sessionPasswd == null){
271                                         throw new ServletModuleUserException("Lost password");
272                                 }
273                                 String passwd = (String)withValues.get("passwd");
274                                 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
275                                         throw new ServletModuleUserException("Missing password");
276                                 }
277                                 session.invalidate();
278                         }
279
280       if ((((String)withValues.get("title")).length() == 0) ||
281           (((String)withValues.get("description")).length() == 0) ||
282           (((String)withValues.get("content_data")).length() == 0))
283             throw new ServletModuleUserException("Missing field");
284       
285       // call the routines that escape html
286
287       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
288         String k=(String)i.next();
289         String v=(String)withValues.get(k);
290         
291         if (k.equals("content_data")){
292           //this doesn't quite work yet, so for now, all html goes
293           //withValues.put(k,StringUtil.approveHTMLTags(v));
294           //withValues.put(k,StringUtil.removeHTMLTags(v));
295         } else {
296           withValues.put(k,StringUtil.removeHTMLTags(v));
297         }
298         
299       }
300
301       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
302       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
303       withValues.put("is_produced", "0");
304       // by default stuff is published, they can be un-published through the
305       // admin interface.
306       withValues.put("is_published","1");
307       // if op direct article-type == newswire
308       if (directOp.equals("yes")) withValues.put("to_article_type","1");
309       
310       // owner is openposting user
311       withValues.put("to_publisher","1");
312       if (withValues.get("creator").toString().equals(""))
313         withValues.put("creator","Anonym");
314
315       // inserting  content into database
316       String cid = contentModule.add(withValues);
317       theLog.printDebugInfo("id: "+cid);
318       //insert was not successfull
319       if(cid==null){
320         //How do we know that it was not succesful cause of a
321         //dupe, what if it failed cause of "No space left on device"?
322         //Or is there something I am missing? Wouldn't it be better
323         //to have an explicit dupe check and then insert? I have no
324         //idea what I am talking about. this comment is in case
325         //I forget to explicitely ask. -mh
326         deliver(req, res, mergeData, postingFormDupeTemplate);
327       }
328
329       String[] to_topicsArr = mp.getParameterValues("to_topic");
330       
331                         if (to_topicsArr != null && to_topicsArr.length > 0) {
332         try{
333           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
334           setTopic = true;
335         } catch (Exception e) {
336           theLog.printError("setting content_x_topic failed");
337           contentModule.deleteById(cid);
338           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
339         } //end try
340       } //end if
341        
342       //if we're here all is ok... associate the media to the article
343       for(int i=0;i<mediaList.size();i++) {
344         Entity mediaEnt = (Entity)mediaList.elementAt(i);
345         DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
346       }
347
348       // producing openpostinglist
349       new ProducerOpenPosting().handle(null,null,false,false);
350       // producing new page
351       new ProducerContent().handle(null, null, false, false,cid);
352       //if direct op producing startpage
353       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
354       
355                         //produce the topicPages if set
356                         //should be more intelligent
357                         //if(setTopic==true) new ProducerTopics().handle(null,null);
358                         
359       // sync the server
360       //should be configureable
361       int exitValue = Helper.rsync();
362       theLog.printDebugInfo("rsync: "+exitValue);
363
364     }
365     catch (MirMediaException e) { throw new ServletModuleException("MediaException: "+ e.toString());}
366     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
367     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
368     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
369
370     deliver(req, res, mergeData, postingFormDoneTemplate);
371   }
372
373   /*
374    * Method for dynamically generating a pdf from a fo file
375    */
376   public void getpdf(HttpServletRequest req, HttpServletResponse res)
377     throws ServletModuleException, ServletModuleUserException {
378     String ID_REQUEST_PARAM = "id";
379     
380     String generateFO=MirConfig.getProp("GenerateFO");
381     String generatePDF=MirConfig.getProp("GeneratePDF");
382
383     //don't do anything if we are not making FO files, or if we are
384     //pregenerating PDF's
385     if (generateFO.equals("yes") && generatePDF.equals("no")){
386       //fop complains unless you do the logging this way
387       Logger log = null;
388       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
389       log = hierarchy.getLoggerFor("fop");
390       log.setPriority(Priority.WARN);
391     
392       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
393       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
394       String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
395       String xslSheet=templateDir + "/" 
396         + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
397       try {
398         String idParam = req.getParameter(ID_REQUEST_PARAM);
399         if (idParam != null) {
400           EntityContent contentEnt =
401             (EntityContent)contentModule.getById(idParam);
402           String publishPath = contentEnt.getValue("publish_path");
403           String foFile = producerStorageRoot + producerDocRoot + "/" 
404                           + publishPath + "/" + idParam + ".fo";
405           XSLTInputHandler input = new XSLTInputHandler(new File(foFile), 
406                                                        new File(xslSheet));
407           
408           ByteArrayOutputStream out = new ByteArrayOutputStream();
409           res.setContentType("application/pdf");
410
411           Driver driver = new Driver();
412           driver.setLogger(log);
413           driver.setRenderer(Driver.RENDER_PDF);
414           driver.setOutputStream(out);
415           driver.render(input.getParser(), input.getInputSource());
416
417           byte[] content = out.toByteArray();
418           res.setContentLength(content.length);
419           res.getOutputStream().write(content);
420           res.getOutputStream().flush();
421         } else {
422           throw new ServletModuleUserException("Missing id parameter.");
423         }
424       } catch (Exception ex) {
425         throw new ServletModuleException(ex.toString());
426       }
427     } else {
428       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
429     }
430   }
431   
432   private void _throwBadContentType (String fileName, String contentType)
433     throws ServletModuleUserException {
434
435     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
436                           +contentType);
437     throw new ServletModuleUserException("The file you uploaded is of the "
438         +"following mime-type: "+contentType
439         +", we do not support this mime-type. "
440         +"Error One or more files of unrecognized type. Sorry");
441   }
442         
443         protected String createOneTimePasswd(){
444                 Random r = new Random();
445                 int random = r.nextInt();
446                 long l = System.currentTimeMillis();
447                 l = (l*l*l*l)/random;
448                 if(l<0) l = l * -1;
449                 String returnString = ""+l;
450                 return returnString.substring(5);
451         }
452       
453 }
454
455
456