013b3a3e23316db48b48b009917b3758fce8595b
[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) || (mediaTitle.length() == 0))
383             throw new ServletModuleUserException("Missing field");
384             //mediaTitle = (String)withValues.get("title");
385
386         mediaValues.put("title", mediaTitle);
387         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
388         mediaValues.put("to_publisher", "1"); // op user
389         mediaValues.put("to_media_folder", "7"); // op media_folder
390         mediaValues.put("is_produced", "0");
391         mediaValues.put("is_published","0");
392
393         // @todo this should probably be moved to DatabaseMediaType -mh
394         String[] cTypeSplit = StringUtil.split(contentType, "/");
395         String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
396
397         DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
398         EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
399
400         String mediaTypeId = null;
401         MirMedia mediaHandler;
402         Database mediaStorage;
403         ProducerMedia mediaProducer;
404  
405         //if we didn't find an entry matching the
406         //content-type int the table.
407         if (mediaTypesList.size() == 0) {
408           contentModule.deleteById(cid);
409           _throwBadContentType(fileName, contentType);
410         }
411
412         Entity mediaType = null;
413         Entity mediaType2 = null;
414         
415         // find out if we an exact content-type match if so take it.
416         // otherwise try to match majortype/*
417         // @todo this should probably be moved to DatabaseMediaType -mh
418         for(int j=0;j<mediaTypesList.size();j++) {
419           if(contentType.equals(
420                 mediaTypesList.elementAt(j).getValue("mime_type")))
421             mediaType = mediaTypesList.elementAt(j);
422           else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
423                     cTypeSplit[0]+"/*") )
424             mediaType2= mediaTypesList.elementAt(j);
425         }
426
427         if ( (mediaType == null) && (mediaType2 == null) ) {
428           contentModule.deleteById(cid);
429           _throwBadContentType(fileName, contentType);
430         }
431         else if( (mediaType == null) && (mediaType2 != null) )
432           mediaType = mediaType2;
433
434         //get the class names from the media_type table.
435         mediaTypeId = mediaType.getId();
436         try {
437           // ############### @todo: merge these and the getURL call into one
438           // getURL helper call that just takes the Entity as a parameter
439           // along with media_type
440           mediaHandler = MediaHelper.getHandler(mediaType);
441           mediaStorage = MediaHelper.getStorage(mediaType,
442                                               "mircoders.storage.Database");
443           Class prodCls = Class.forName("mircoders.producer.Producer"
444                                             +mediaType.getValue("tablename"));
445           mediaProducer = (ProducerMedia)prodCls.newInstance();
446         } catch (Exception e) {
447           theLog.printError("getting media handler failed: "+e.toString());
448           contentModule.deleteById(cid);
449           throw new ServletModuleException("getting media handler failed: "
450                                           +e.toString());
451         }
452
453         mediaValues.put("to_media_type",mediaTypeId);
454
455         //load the classes via reflection
456         String MediaId;
457         Entity mediaEnt = null;
458         try {
459           mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
460           mediaEnt.setStorage(mediaStorage);
461           mediaEnt.setValues(mediaValues);
462           mediaId = mediaEnt.insert();
463
464           //save and store the media data/metadata
465           mediaHandler.set(mpReq.getMedia(), mediaEnt,
466                           mediaType);
467
468           //were done with mpReq at this point, dereference it.
469           //as it contains mucho mem. -mh 01.10.2001
470           mpReq=null;
471           
472           //we got this far, associate the media to the article
473           mediaEnt.setValueForProperty("is_published","1");
474           mediaEnt.update();
475           //produce it
476           mediaProducer.handle(null, null, false, false, mediaId);
477           DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
478         } catch (Exception e) {
479           theLog.printError("setting media failed: "+e.toString());
480           contentModule.deleteById(cid);
481           throw new ServletModuleException("setting media failed: "
482                                             +e.toString());
483         }
484
485       } //end for Iterator...
486
487       //if we're here all is ok...
488       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
489       contentEnt.setValueForProperty("is_published","1");
490       contentEnt.update();
491
492
493       //dereference mp. -mh
494       mp=null;
495
496       // producing openpostinglist
497       new ProducerOpenPosting().handle(null,null,false,false);
498       // producing new page
499       new ProducerContent().handle(null, null, false, false,cid);
500       //if direct op producing startpage
501       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
502       
503                         //produce the topicPages if set
504                         //should be more intelligent
505                         //if(setTopic==true) new ProducerTopics().handle(null,null);
506                         
507       // sync the server
508       //should be configureable
509       int exitValue = Helper.rsync();
510       theLog.printDebugInfo("rsync: "+exitValue);
511
512     }
513     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
514     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
515     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
516
517     deliver(req, res, mergeData, postingFormDoneTemplate);
518   }
519
520 /**
521   *  Method for dynamically generating a pdf from a fo file
522   */
523
524
525   public void getpdf(HttpServletRequest req, HttpServletResponse res)
526     throws ServletModuleException, ServletModuleUserException {
527     String ID_REQUEST_PARAM = "id";
528     
529     String generateFO=MirConfig.getProp("GenerateFO");
530     String generatePDF=MirConfig.getProp("GeneratePDF");
531
532     //don't do anything if we are not making FO files, or if we are pregenerating PDF's
533     if (generateFO.equals("yes") && generatePDF.equals("no")){
534     
535       //fop complains unless you do the logging this way
536       Logger log = null;
537       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
538       log = hierarchy.getLoggerFor("fop");
539       log.setPriority(Priority.WARN);
540     
541       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
542       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
543       String templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
544       String xslSheet=templateDir + "/" 
545                     + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
546       try {
547         String idParam = req.getParameter(ID_REQUEST_PARAM);
548         if (idParam != null){
549           EntityContent contentEnt = (EntityContent)contentModule.getById(idParam);
550           String publishPath = contentEnt.getValue("publish_path");
551           String foFile = producerStorageRoot + producerDocRoot + "/" 
552                         + publishPath + "/" + idParam + ".fo";
553           XSLTInputHandler input = new XSLTInputHandler(new File(foFile), 
554                                                        new File(xslSheet));
555           
556           ByteArrayOutputStream out = new ByteArrayOutputStream();
557           res.setContentType("application/pdf");
558
559           Driver driver = new Driver();
560           driver.setLogger(log);
561           driver.setRenderer(Driver.RENDER_PDF);
562           driver.setOutputStream(out);
563           driver.render(input.getParser(), input.getInputSource());
564
565           byte[] content = out.toByteArray();
566           res.setContentLength(content.length);
567           res.getOutputStream().write(content);
568           res.getOutputStream().flush();
569         } 
570         else {
571           throw new ServletModuleUserException("Can't generate a PDF without an id parameter.");
572         }
573       } 
574       catch (Exception ex) {
575         throw new ServletModuleException(ex.toString());
576       }
577     }
578     else {
579       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
580     }
581   }
582   
583   private void _throwBadContentType (String fileName, String contentType)
584     throws ServletModuleUserException {
585
586     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
587                           +contentType);
588     throw new ServletModuleUserException("The file you uploaded is of the "
589         +"following mime-type: "+contentType
590         +", we do not support this mime-type. "
591         +"Error One or more files of unrecognized type. Sorry");
592   }
593         
594         protected String createOneTimePasswd(){
595                 Random r = new Random();
596                 int random = r.nextInt();
597                 long l = System.currentTimeMillis();
598                 l = (l*l*l*l)/random;
599                 if(l<0) l = l * -1;
600                 String returnString = ""+l;
601                 return returnString.substring(5);
602         }
603       
604 }
605
606
607