use ServletContext.getMimeType() as fallback to find media mime-type from .extension...
[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 mir.servlet.*;
17 import mir.module.*;
18 import mir.misc.*;
19 import mir.entity.*;
20 import mir.storage.*;
21 import mir.media.*;
22
23 import mircoders.entity.*;
24 import mircoders.storage.*;
25 import mircoders.module.*;
26 import mircoders.producer.*;
27
28 /*
29  *  ServletModuleOpenIndy -
30  *   is the open-access-servlet, which is responsible for
31  *    adding comments to articles &
32  *    open-postings to the newswire
33  *
34  * @author RK
35  */
36
37 public class ServletModuleOpenIndy extends ServletModule
38 {
39
40   private String        commentFormTemplate, commentFormDoneTemplate,
41                         commentFormDupeTemplate;
42   private String        postingFormTemplate, postingFormDoneTemplate,
43                         postingFormDupeTemplate;
44   private ModuleContent contentModule;
45   private ModuleImages  imageModule;
46   private ModuleTopics  themenModule;
47   private String        directOp ="yes";
48
49   // Singelton / Kontruktor
50   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
51   public static ServletModule getInstance() { return instance; }
52
53   private ServletModuleOpenIndy() {
54     try {
55       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
56       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
57       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
58       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
59       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
60       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
61       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
62       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
63       mainModule = new ModuleComment(DatabaseComment.getInstance());
64       contentModule = new ModuleContent(DatabaseContent.getInstance());
65       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
66       imageModule = new ModuleImages(DatabaseImages.getInstance());
67       defaultAction="addposting";
68     }
69     catch (StorageObjectException e) {
70         theLog.printError("servletmoduleopenindy could not be initialized");
71     }
72   }
73
74
75   /**
76    *  Method for making a comment
77    */
78
79   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
80   {
81     String aid = req.getParameter("aid"); // the article id the comment will belong to
82     if (aid!=null && !aid.equals(""))
83     {
84       SimpleHash mergeData = new SimpleHash();
85       // ok, article
86       mergeData.put("aid", aid);
87       deliver(req, res, mergeData, commentFormTemplate);
88     }
89     else throw new ServletModuleException("aid not set!");
90   }
91
92   /**
93    *  Method for inserting a comment into the Database and delivering
94    *  the commentDone Page
95    */
96
97   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
98   {
99     String aid = req.getParameter("to_media"); // the article id the comment will belong to
100     if (aid!=null && !aid.equals(""))
101     {
102       // ok, collecting data from form
103       try {
104         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
105        
106         //no html in comments(for now)
107         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
108             String k=(String)i.next();
109             String v=(String)withValues.get(k);
110             
111             withValues.put(k,StringUtil.removeHTMLTags(v));
112         }
113         withValues.put("is_published","1");
114
115         // inserting into database
116         String id = mainModule.add(withValues);
117         theLog.printDebugInfo("id: "+id);
118         //insert was not successfull
119         if(id==null){
120           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
121         }
122         
123         // producing new page
124         new ProducerContent().handle(null, null, true, false, aid);
125
126         // sync the server
127         int exitValue = Helper.rsync();
128         theLog.printDebugInfo("rsync:"+exitValue);
129
130         // redirecting to url
131         // should implement back to article
132         SimpleHash mergeData = new SimpleHash();
133         deliver(req, res, mergeData, commentFormDoneTemplate);
134       }
135       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
136       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
137
138     }
139     else throw new ServletModuleException("aid not set!");
140
141   }
142
143   /**
144    *  Method for delivering the form-Page for open posting
145    */
146
147   public void addposting(HttpServletRequest req, HttpServletResponse res)
148     throws ServletModuleException {
149     SimpleHash mergeData = new SimpleHash();
150     String numOfMedia = req.getParameter("medianum");
151     if(numOfMedia==null||numOfMedia.equals("")){
152       numOfMedia="1";
153     }
154     
155     int mediaNum = Integer.parseInt(numOfMedia);
156     SimpleList mediaFields = new SimpleList();
157     for(int i =0; i<mediaNum;i++){
158       Integer mNum = new Integer(i+1);
159       mediaFields.add(mNum.toString());
160     }
161     mergeData.put("medianum",numOfMedia);
162     mergeData.put("mediafields",mediaFields);
163     
164     
165     SimpleHash extraInfo = new SimpleHash();
166     /** @todo popups missing */
167     try{
168       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
169       extraInfo.put("languagePopUpData", popUpData );
170       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
171     } catch (Exception e) {
172       theLog.printError("languagePopUpData or getTopicslist failed "
173                         +e.toString());
174       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
175     } 
176       
177     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
178   }
179
180   /**
181    *  Method for inserting an open posting into the Database and delivering
182    *  the postingDone Page
183    */
184
185   public void insposting(HttpServletRequest req, HttpServletResponse res)
186     throws ServletModuleException, ServletModuleUserException
187   {
188     SimpleHash mergeData = new SimpleHash();
189     boolean setMedia=false;
190                 boolean setTopic = false;
191
192     try {
193       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
194           
195       HashMap withValues = mp.getParameters();
196
197       if ((((String)withValues.get("title")).length() == 0) ||
198           (((String)withValues.get("description")).length() == 0) ||
199           (((String)withValues.get("content_data")).length() == 0))
200             throw new ServletModuleUserException("Missing field");
201       
202       // call the routines that escape html
203
204       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
205         String k=(String)i.next();
206         String v=(String)withValues.get(k);
207         
208         if (k.equals("content_data")){
209           //this doesn't quite work yet, so for now, all html goes
210           //withValues.put(k,StringUtil.approveHTMLTags(v));
211           //withValues.put(k,StringUtil.removeHTMLTags(v));
212         } else {
213           withValues.put(k,StringUtil.removeHTMLTags(v));
214         }
215         
216       }
217
218       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
219       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
220       withValues.put("is_produced", "0");
221       // op-articles are not immediatly published
222       // we don't know that all is good yet (media, title is present, etc..)
223       withValues.put("is_published","0");
224       // if op direct article-type == newswire
225       if (directOp.equals("yes")) withValues.put("to_article_type","1");
226       
227       // owner is openposting user
228       withValues.put("to_publisher","1");
229       if (withValues.get("creator").toString().equals(""))
230         withValues.put("creator","Anonym");
231
232       // inserting  content into database
233       String cid = contentModule.add(withValues);
234       theLog.printDebugInfo("id: "+cid);
235       //insert was not successfull
236       if(cid==null){
237         //How do we know that it was not succesful cause of a
238         //dupe, what if it failed cause of "No space left on device"?
239         //Or is there something I am missing? Wouldn't it be better
240         //to have an explicit dupe check and then insert? I have no
241         //idea what I am talking about. this comment is in case
242         //I forget to explicitely ask. -mh
243         deliver(req, res, mergeData, postingFormDupeTemplate);
244       }
245
246       String[] to_topicsArr = mp.getParameterValues("to_topic");
247       
248                         if (to_topicsArr != null && to_topicsArr.length > 0) {
249         try{
250           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
251           setTopic = true;
252         } catch (Exception e) {
253           theLog.printError("setting content_x_topic failed");
254           contentModule.deleteById(cid);
255           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
256         } //end try
257       } //end if
258         
259       // if op contains uploaddata
260       String mediaId=null;
261       int i=1;
262       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
263         MpRequest mpReq = (MpRequest)it.next();
264         String fileName = mpReq.getFilename();
265
266         //get the content-type from what the client browser
267         //sends us. (the "Oreilly method")
268         String contentType = mpReq.getContentType();
269
270         theLog.printInfo("FROM BROWSER: "+contentType);
271
272         //if the client browser sent us unknown (text/plain is default)
273         //or if we got application/octet-stream, it's possible that
274         //the browser is in error, better check against the file extension
275         if (contentType.equals("text/plain") ||
276             contentType.equals("application/octet-stream")) {
277           /**
278            * Fallback to finding the mime-type through the standard ServletApi
279            * ServletContext getMimeType() method.
280            *
281            * This is a way to get the content-type via the .extension,
282            * we could maybe use a magic method as an additional method of
283            * figuring out the content-type, by looking at the header (first
284            * few bytes) of the file. (like the file(1) command). We could 
285            * also call the "file" command through Runtime. This is an
286            * option that I almost prefer as it is already implemented and
287            * exists with an up-to-date map on most modern Unix like systems.
288            * I haven't found a really nice implementation of the magic method
289            * in pure java yet.
290            *
291            * The first method we try thought is the "Oreilly method". It
292            * relies on the content-type that the client browser sends and 
293            * that sometimes is application-octet stream with
294            * broken/mis-configured browsers.
295            *
296            * The map file we use for the extensions is the standard web-app
297            * deployment descriptor file (web.xml). See Mir's web.xml or see
298            * your Servlet containers (most likely Tomcat) documentation.
299            * So if you support a new media type you have to make sure that 
300            * it is in this file -mh
301            */
302           ServletContext ctx =
303             (ServletContext)MirConfig.getPropAsObject("ServletContext");
304           contentType = ctx.getMimeType(fileName);
305           if (contentType==null)
306             contentType = "text/plain"; // rfc1867 says this is the default
307         }
308         HashMap mediaValues = new HashMap();
309
310         theLog.printInfo("CONTENT TYPE IS: "+contentType);
311         
312         if (contentType.equals("text/plain") ||
313             contentType.equals("application/octet-stream")) {
314           contentModule.deleteById(cid);
315           _throwBadContentType(fileName, contentType);
316         }
317
318         String mediaTitle=(String)withValues.get("media_title"+i);
319         i++;
320
321         if (mediaTitle==null)
322             mediaTitle = (String)withValues.get("title");
323
324         mediaValues.put("title", mediaTitle);
325         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
326         mediaValues.put("to_publisher", "1"); // op user
327         mediaValues.put("to_media_folder", "7"); // op media_folder
328         mediaValues.put("is_produced", "0");
329         mediaValues.put("is_published","0");
330
331         // @todo this should probably be moved to DatabaseMediaType -mh
332         String[] cTypeSplit = StringUtil.split(contentType, "/");
333         String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
334
335         DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
336         EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
337
338         String mediaTypeId = null;
339         MirMedia mediaHandler;
340         Database mediaStorage;
341         ProducerMedia mediaProducer;
342  
343         //if we didn't find an entry matching the
344         //content-type int the table.
345         if (mediaTypesList.size() == 0) {
346           contentModule.deleteById(cid);
347           _throwBadContentType(fileName, contentType);
348         }
349
350         Entity mediaType = null;
351         Entity mediaType2 = null;
352         
353         // find out if we an exact content-type match if so take it.
354         // otherwise try to match majortype/*
355         // @todo this should probably be moved to DatabaseMediaType -mh
356         for(int j=0;j<mediaTypesList.size();j++) {
357           if(contentType.equals(
358                 mediaTypesList.elementAt(j).getValue("mime_type")))
359             mediaType = mediaTypesList.elementAt(j);
360           else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
361                     cTypeSplit[0]+"/*") )
362             mediaType2= mediaTypesList.elementAt(j); 
363         } 
364
365         if ( (mediaType == null) && (mediaType2 == null) ) {
366           contentModule.deleteById(cid);
367           _throwBadContentType(fileName, contentType);
368         }
369         else if( (mediaType == null) && (mediaType2 != null) )
370           mediaType = mediaType2;
371
372         //get the class names from the media_type table.
373         mediaTypeId = mediaType.getId();
374         try {
375           // ############### @todo: merge these and the getURL call into one
376           // getURL helper call that just takes the Entity as a parameter
377           // along with media_type
378           mediaHandler = MediaHelper.getHandler(mediaType);
379           mediaStorage = MediaHelper.getStorage(mediaType,
380                                               "mircoders.storage.Database");
381           Class prodCls = Class.forName("mircoders.producer.Producer"
382                                             +mediaType.getValue("tablename"));
383           mediaProducer = (ProducerMedia)prodCls.newInstance();
384         } catch (Exception e) {
385           theLog.printError("getting media handler failed: "+e.toString());
386           contentModule.deleteById(cid);
387           throw new ServletModuleException("getting media handler failed: "
388                                           +e.toString());
389         }
390
391         mediaValues.put("to_media_type",mediaTypeId);
392
393         //load the classes via reflection
394         String MediaId;
395         Entity mediaEnt = null;
396         try {
397           mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
398           mediaEnt.setStorage(mediaStorage);
399           mediaEnt.setValues(mediaValues);
400           mediaId = mediaEnt.insert();
401
402           //save and store the media data/metadata
403           mediaHandler.set(mpReq.getMedia(), mediaEnt,
404                           mediaType);
405
406           //were done with mpReq at this point, dereference it.
407           //as it contains mucho mem. -mh 01.10.2001
408           mpReq=null;
409           
410           //we got this far, associate the media to the article
411           mediaEnt.setValueForProperty("is_published","1");
412           mediaEnt.update();
413           //produce it
414           mediaProducer.handle(null, null, false, false, mediaId);
415           DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
416         } catch (Exception e) {
417           theLog.printError("setting media failed: "+e.toString());
418           contentModule.deleteById(cid);
419           throw new ServletModuleException("setting media failed: "
420                                             +e.toString());
421         }
422
423       } //end for Iterator...
424
425       //if we're here all is ok...
426       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
427       contentEnt.setValueForProperty("is_published","1");
428       contentEnt.update();
429
430
431       //dereference mp. -mh
432       mp=null;
433
434       // producing openpostinglist
435       new ProducerOpenPosting().handle(null,null,false,false);
436       // producing new page
437       new ProducerContent().handle(null, null, false, false,cid);
438       //if direct op producing startpage
439       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
440       
441                         //produce the topicPages if set
442                         //should be more intelligent
443                         //if(setTopic==true) new ProducerTopics().handle(null,null);
444                         
445       // sync the server
446       //should be configureable
447       int exitValue = Helper.rsync();
448       theLog.printDebugInfo("rsync: "+exitValue);
449
450     }
451     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
452     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
453     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
454
455     deliver(req, res, mergeData, postingFormDoneTemplate);
456   }
457
458   private void _throwBadContentType (String fileName, String contentType)
459     throws ServletModuleUserException {
460
461     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
462                           +contentType);
463     throw new ServletModuleUserException("The file you uploaded is of the "
464         +"following mime-type: "+contentType
465         +", we do not support this mime-type. "
466         +"Error One or more files of unrecognized type. Sorry");
467   }
468       
469 }
470
471