2c04c82af1ac4ab043568545c079b8a34e8b56c6
[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
37 /*
38  *  ServletModuleOpenIndy -
39  *   is the open-access-servlet, which is responsible for
40  *    adding comments to articles &
41  *    open-postings to the newswire
42  *
43  * @author RK
44  */
45
46 public class ServletModuleOpenIndy extends ServletModule
47 {
48
49   private String        commentFormTemplate, commentFormDoneTemplate,
50                         commentFormDupeTemplate;
51   private String        postingFormTemplate, postingFormDoneTemplate,
52                         postingFormDupeTemplate;
53   private ModuleContent contentModule;
54   private ModuleImages  imageModule;
55   private ModuleTopics  themenModule;
56   private String        directOp ="yes";
57   private String        passwdProtection ="yes";
58   // Singelton / Kontruktor
59   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
60   public static ServletModule getInstance() { return instance; }
61
62   private ServletModuleOpenIndy() {
63     try {
64       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
65       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
66       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
67       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
68       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
69       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
70       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
71       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
72                         passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
73       mainModule = new ModuleComment(DatabaseComment.getInstance());
74       contentModule = new ModuleContent(DatabaseContent.getInstance());
75       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
76       imageModule = new ModuleImages(DatabaseImages.getInstance());
77       defaultAction="addposting";
78                         
79     }
80     catch (StorageObjectException e) {
81         theLog.printError("servletmoduleopenindy could not be initialized");
82     }
83   }
84
85
86   /**
87    *  Method for making a comment
88    */
89
90   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
91   {
92     String aid = req.getParameter("aid"); // the article id the comment will belong to
93     if (aid!=null && !aid.equals(""))
94     {
95                         SimpleHash mergeData = new SimpleHash();
96
97                         // onetimepasswd
98                         if(passwdProtection.equals("yes")){
99                                 String passwd = this.createOneTimePasswd();
100                                 System.out.println(passwd);
101                                 HttpSession session = req.getSession(false);
102                                 session.setAttribute("passwd",passwd);
103                                 mergeData.put("passwd", passwd);
104                         }
105                         
106       mergeData.put("aid", aid);
107       deliver(req, res, mergeData, commentFormTemplate);
108     }
109     else throw new ServletModuleException("aid not set!");
110   }
111
112   /**
113    *  Method for inserting a comment into the Database and delivering
114    *  the commentDone Page
115    */
116
117   public void inscomment(HttpServletRequest req, HttpServletResponse res)
118         throws ServletModuleException,ServletModuleUserException
119   {
120     String aid = req.getParameter("to_media"); // the article id the comment will belong to
121     if (aid!=null && !aid.equals(""))
122     {
123       // ok, collecting data from form
124       try {
125         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
126        
127         //no html in comments(for now)
128         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
129             String k=(String)i.next();
130             String v=(String)withValues.get(k);
131             
132             withValues.put(k,StringUtil.removeHTMLTags(v));
133         }
134         withValues.put("is_published","1");
135                                 
136                                 //checking the onetimepasswd
137                                 if(passwdProtection.equals("yes")){
138                                         HttpSession session = req.getSession(false);
139                                         String sessionPasswd = (String)session.getAttribute("passwd");
140                                         if ( sessionPasswd == null){
141                                                 throw new ServletModuleUserException("Lost password");
142                                         }
143                                         String passwd = req.getParameter("passwd");
144                                         if ( passwd == null || (!sessionPasswd.equals(passwd))) {
145                                                 throw new ServletModuleUserException("Missing password");
146                                         }
147                                         session.invalidate();
148                                 }
149                                 
150         // inserting into database
151         String id = mainModule.add(withValues);
152         theLog.printDebugInfo("id: "+id);
153         //insert was not successfull
154         if(id==null){
155           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
156         }
157         
158         // producing new page
159         new ProducerContent().handle(null, null, true, false, aid);
160
161         // sync the server
162         int exitValue = Helper.rsync();
163         theLog.printDebugInfo("rsync:"+exitValue);
164
165         // redirecting to url
166         // should implement back to article
167         SimpleHash mergeData = new SimpleHash();
168         deliver(req, res, mergeData, commentFormDoneTemplate);
169       }
170       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
171       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
172
173     }
174     else throw new ServletModuleException("aid not set!");
175
176   }
177
178   /**
179    *  Method for delivering the form-Page for open posting
180    */
181
182   public void addposting(HttpServletRequest req, HttpServletResponse res)
183     throws ServletModuleException {
184     SimpleHash mergeData = new SimpleHash();
185                 
186                 // onetimepasswd
187                 if(passwdProtection.equals("yes")){
188                         String passwd = this.createOneTimePasswd();
189                         System.out.println(passwd);
190                         HttpSession session = req.getSession(false);
191                         session.setAttribute("passwd",passwd);
192                         mergeData.put("passwd", passwd);
193                 }
194                         
195     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
196     String numOfMedia = req.getParameter("medianum");
197     if(numOfMedia==null||numOfMedia.equals("")){
198       numOfMedia="1";
199     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
200       numOfMedia = maxMedia;
201     }
202     
203     int mediaNum = Integer.parseInt(numOfMedia);
204     SimpleList mediaFields = new SimpleList();
205     for(int i =0; i<mediaNum;i++){
206       Integer mNum = new Integer(i+1);
207       mediaFields.add(mNum.toString());
208     }
209     mergeData.put("medianum",numOfMedia);
210     mergeData.put("mediafields",mediaFields);
211     
212     
213     SimpleHash extraInfo = new SimpleHash();
214     try{
215       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
216       extraInfo.put("languagePopUpData", popUpData );
217       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
218     } catch (Exception e) {
219       theLog.printError("languagePopUpData or getTopicslist failed "
220                         +e.toString());
221       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
222     }
223       
224     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
225   }
226
227   /**
228    *  Method for inserting an open posting into the Database and delivering
229    *  the postingDone Page
230    */
231
232   public void insposting(HttpServletRequest req, HttpServletResponse res)
233     throws ServletModuleException, ServletModuleUserException
234   {
235     SimpleHash mergeData = new SimpleHash();
236     boolean setMedia=false;
237                 boolean setTopic = false;
238
239     try {
240       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
241           
242       HashMap withValues = mp.getParameters();
243                                                         
244                         //checking the onetimepasswd
245                         if(passwdProtection.equals("yes")){
246                                 HttpSession session = req.getSession(false);
247                                 String sessionPasswd = (String)session.getAttribute("passwd");
248                                 if ( sessionPasswd == null){
249                                         throw new ServletModuleUserException("Lost password");
250                                 }
251                                 String passwd = (String)withValues.get("passwd");
252                                 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
253                                         throw new ServletModuleUserException("Missing password");
254                                 }
255                                 session.invalidate();
256                         }
257
258       if ((((String)withValues.get("title")).length() == 0) ||
259           (((String)withValues.get("description")).length() == 0) ||
260           (((String)withValues.get("content_data")).length() == 0))
261             throw new ServletModuleUserException("Missing field");
262       
263       // call the routines that escape html
264
265       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
266         String k=(String)i.next();
267         String v=(String)withValues.get(k);
268         
269         if (k.equals("content_data")){
270           //this doesn't quite work yet, so for now, all html goes
271           //withValues.put(k,StringUtil.approveHTMLTags(v));
272           //withValues.put(k,StringUtil.removeHTMLTags(v));
273         } else {
274           withValues.put(k,StringUtil.removeHTMLTags(v));
275         }
276         
277       }
278
279       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
280       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
281       withValues.put("is_produced", "0");
282       // op-articles are not immediatly published
283       // we don't know that all is good yet (media, title is present, etc..)
284       withValues.put("is_published","0");
285       // if op direct article-type == newswire
286       if (directOp.equals("yes")) withValues.put("to_article_type","1");
287       
288       // owner is openposting user
289       withValues.put("to_publisher","1");
290       if (withValues.get("creator").toString().equals(""))
291         withValues.put("creator","Anonym");
292
293       // inserting  content into database
294       String cid = contentModule.add(withValues);
295       theLog.printDebugInfo("id: "+cid);
296       //insert was not successfull
297       if(cid==null){
298         //How do we know that it was not succesful cause of a
299         //dupe, what if it failed cause of "No space left on device"?
300         //Or is there something I am missing? Wouldn't it be better
301         //to have an explicit dupe check and then insert? I have no
302         //idea what I am talking about. this comment is in case
303         //I forget to explicitely ask. -mh
304         deliver(req, res, mergeData, postingFormDupeTemplate);
305       }
306
307       String[] to_topicsArr = mp.getParameterValues("to_topic");
308       
309                         if (to_topicsArr != null && to_topicsArr.length > 0) {
310         try{
311           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
312           setTopic = true;
313         } catch (Exception e) {
314           theLog.printError("setting content_x_topic failed");
315           contentModule.deleteById(cid);
316           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
317         } //end try
318       } //end if
319         
320       // if op contains uploaddata
321       String mediaId=null;
322       int i=1;
323       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
324         MpRequest mpReq = (MpRequest)it.next();
325         String fileName = mpReq.getFilename();
326
327         //get the content-type from what the client browser
328         //sends us. (the "Oreilly method")
329         String contentType = mpReq.getContentType();
330
331         theLog.printInfo("FROM BROWSER: "+contentType);
332
333         //if the client browser sent us unknown (text/plain is default)
334         //or if we got application/octet-stream, it's possible that
335         //the browser is in error, better check against the file extension
336         if (contentType.equals("text/plain") ||
337             contentType.equals("application/octet-stream")) {
338           /**
339            * Fallback to finding the mime-type through the standard ServletApi
340            * ServletContext getMimeType() method.
341            *
342            * This is a way to get the content-type via the .extension,
343            * we could maybe use a magic method as an additional method of
344            * figuring out the content-type, by looking at the header (first
345            * few bytes) of the file. (like the file(1) command). We could
346            * also call the "file" command through Runtime. This is an
347            * option that I almost prefer as it is already implemented and
348            * exists with an up-to-date map on most modern Unix like systems.
349            * I haven't found a really nice implementation of the magic method
350            * in pure java yet.
351            *
352            * The first method we try thought is the "Oreilly method". It
353            * relies on the content-type that the client browser sends and
354            * that sometimes is application-octet stream with
355            * broken/mis-configured browsers.
356            *
357            * The map file we use for the extensions is the standard web-app
358            * deployment descriptor file (web.xml). See Mir's web.xml or see
359            * your Servlet containers (most likely Tomcat) documentation.
360            * So if you support a new media type you have to make sure that
361            * it is in this file -mh
362            */
363           ServletContext ctx =
364             (ServletContext)MirConfig.getPropAsObject("ServletContext");
365           contentType = ctx.getMimeType(fileName);
366           if (contentType==null)
367             contentType = "text/plain"; // rfc1867 says this is the default
368         }
369         HashMap mediaValues = new HashMap();
370
371         theLog.printInfo("CONTENT TYPE IS: "+contentType);
372         
373         if (contentType.equals("text/plain") ||
374             contentType.equals("application/octet-stream")) {
375           contentModule.deleteById(cid);
376           _throwBadContentType(fileName, contentType);
377         }
378
379         String mediaTitle=(String)withValues.get("media_title"+i);
380         i++;
381
382         if (mediaTitle==null)
383             mediaTitle = (String)withValues.get("title");
384
385         mediaValues.put("title", mediaTitle);
386         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
387         mediaValues.put("to_publisher", "1"); // op user
388         mediaValues.put("to_media_folder", "7"); // op media_folder
389         mediaValues.put("is_produced", "0");
390         mediaValues.put("is_published","0");
391
392         // @todo this should probably be moved to DatabaseMediaType -mh
393         String[] cTypeSplit = StringUtil.split(contentType, "/");
394         String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
395
396         DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
397         EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
398
399         String mediaTypeId = null;
400         MirMedia mediaHandler;
401         Database mediaStorage;
402         ProducerMedia mediaProducer;
403  
404         //if we didn't find an entry matching the
405         //content-type int the table.
406         if (mediaTypesList.size() == 0) {
407           contentModule.deleteById(cid);
408           _throwBadContentType(fileName, contentType);
409         }
410
411         Entity mediaType = null;
412         Entity mediaType2 = null;
413         
414         // find out if we an exact content-type match if so take it.
415         // otherwise try to match majortype/*
416         // @todo this should probably be moved to DatabaseMediaType -mh
417         for(int j=0;j<mediaTypesList.size();j++) {
418           if(contentType.equals(
419                 mediaTypesList.elementAt(j).getValue("mime_type")))
420             mediaType = mediaTypesList.elementAt(j);
421           else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
422                     cTypeSplit[0]+"/*") )
423             mediaType2= mediaTypesList.elementAt(j);
424         }
425
426         if ( (mediaType == null) && (mediaType2 == null) ) {
427           contentModule.deleteById(cid);
428           _throwBadContentType(fileName, contentType);
429         }
430         else if( (mediaType == null) && (mediaType2 != null) )
431           mediaType = mediaType2;
432
433         //get the class names from the media_type table.
434         mediaTypeId = mediaType.getId();
435         try {
436           // ############### @todo: merge these and the getURL call into one
437           // getURL helper call that just takes the Entity as a parameter
438           // along with media_type
439           mediaHandler = MediaHelper.getHandler(mediaType);
440           mediaStorage = MediaHelper.getStorage(mediaType,
441                                               "mircoders.storage.Database");
442           Class prodCls = Class.forName("mircoders.producer.Producer"
443                                             +mediaType.getValue("tablename"));
444           mediaProducer = (ProducerMedia)prodCls.newInstance();
445         } catch (Exception e) {
446           theLog.printError("getting media handler failed: "+e.toString());
447           contentModule.deleteById(cid);
448           throw new ServletModuleException("getting media handler failed: "
449                                           +e.toString());
450         }
451
452         mediaValues.put("to_media_type",mediaTypeId);
453
454         //load the classes via reflection
455         String MediaId;
456         Entity mediaEnt = null;
457         try {
458           mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
459           mediaEnt.setStorage(mediaStorage);
460           mediaEnt.setValues(mediaValues);
461           mediaId = mediaEnt.insert();
462
463           //save and store the media data/metadata
464           mediaHandler.set(mpReq.getMedia(), mediaEnt,
465                           mediaType);
466
467           //were done with mpReq at this point, dereference it.
468           //as it contains mucho mem. -mh 01.10.2001
469           mpReq=null;
470           
471           //we got this far, associate the media to the article
472           mediaEnt.setValueForProperty("is_published","1");
473           mediaEnt.update();
474           //produce it
475           mediaProducer.handle(null, null, false, false, mediaId);
476           DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
477         } catch (Exception e) {
478           theLog.printError("setting media failed: "+e.toString());
479           contentModule.deleteById(cid);
480           throw new ServletModuleException("setting media failed: "
481                                             +e.toString());
482         }
483
484       } //end for Iterator...
485
486       //if we're here all is ok...
487       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
488       contentEnt.setValueForProperty("is_published","1");
489       contentEnt.update();
490
491
492       //dereference mp. -mh
493       mp=null;
494
495       // producing openpostinglist
496       new ProducerOpenPosting().handle(null,null,false,false);
497       // producing new page
498       new ProducerContent().handle(null, null, false, false,cid);
499       //if direct op producing startpage
500       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
501       
502                         //produce the topicPages if set
503                         //should be more intelligent
504                         //if(setTopic==true) new ProducerTopics().handle(null,null);
505                         
506       // sync the server
507       //should be configureable
508       int exitValue = Helper.rsync();
509       theLog.printDebugInfo("rsync: "+exitValue);
510
511     }
512     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
513     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
514     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
515
516     deliver(req, res, mergeData, postingFormDoneTemplate);
517   }
518
519 /**
520   *  Method for dynamically generating a pdf from a fo file
521   */
522
523
524   public void getpdf(HttpServletRequest req, HttpServletResponse res)
525     throws ServletModuleException, ServletModuleUserException {
526     String ID_REQUEST_PARAM = "id";
527     
528     String generateFO=MirConfig.getProp("GenerateFO");
529     String generatePDF=MirConfig.getProp("GeneratePDF");
530
531     //don't do anything if we are not making FO files, or if we are pregenerating PDF's
532     if (generateFO.equals("yes") && generatePDF.equals("no")){
533     
534       //fop complains unless you do the logging this way
535       Logger log = null;
536       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
537       log = hierarchy.getLoggerFor("fop");
538       log.setPriority(Priority.WARN);
539     
540       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
541       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
542       String templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
543       String xslSheet=templateDir + "/" 
544                     + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
545       try {
546         String idParam = req.getParameter(ID_REQUEST_PARAM);
547         if (idParam != null){
548           EntityContent contentEnt = (EntityContent)contentModule.getById(idParam);
549           String publishPath = contentEnt.getValue("publish_path");
550           String foFile = producerStorageRoot + producerDocRoot + "/" 
551                         + publishPath + "/" + idParam + ".fo";
552           XSLTInputHandler input = new XSLTInputHandler(new File(foFile), 
553                                                        new File(xslSheet));
554           
555           ByteArrayOutputStream out = new ByteArrayOutputStream();
556           res.setContentType("application/pdf");
557
558           Driver driver = new Driver();
559           driver.setLogger(log);
560           driver.setRenderer(Driver.RENDER_PDF);
561           driver.setOutputStream(out);
562           driver.render(input.getParser(), input.getInputSource());
563
564           byte[] content = out.toByteArray();
565           res.setContentLength(content.length);
566           res.getOutputStream().write(content);
567           res.getOutputStream().flush();
568         } 
569         else {
570           throw new ServletModuleUserException("Can't generate a PDF without an id parameter.");
571         }
572       } 
573       catch (Exception ex) {
574         throw new ServletModuleException(ex.toString());
575       }
576     }
577     else {
578       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
579     }
580   }
581   
582   private void _throwBadContentType (String fileName, String contentType)
583     throws ServletModuleUserException {
584
585     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
586                           +contentType);
587     throw new ServletModuleUserException("The file you uploaded is of the "
588         +"following mime-type: "+contentType
589         +", we do not support this mime-type. "
590         +"Error One or more files of unrecognized type. Sorry");
591   }
592         
593         protected String createOneTimePasswd(){
594                 Random r = new Random();
595                 int random = r.nextInt();
596                 long l = System.currentTimeMillis();
597                 l = (l*l*l*l)/random;
598                 if(l<0) l = l * -1;
599                 String returnString = ""+l;
600                 return returnString.substring(5);
601         }
602       
603 }
604
605
606