added support for configuration of max size of a single upload and the maximum number...
[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 maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
151     String numOfMedia = req.getParameter("medianum");
152     if(numOfMedia==null||numOfMedia.equals("")){
153       numOfMedia="1";
154     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
155       numOfMedia = maxMedia;
156     }
157     
158     int mediaNum = Integer.parseInt(numOfMedia);
159     SimpleList mediaFields = new SimpleList();
160     for(int i =0; i<mediaNum;i++){
161       Integer mNum = new Integer(i+1);
162       mediaFields.add(mNum.toString());
163     }
164     mergeData.put("medianum",numOfMedia);
165     mergeData.put("mediafields",mediaFields);
166     
167     
168     SimpleHash extraInfo = new SimpleHash();
169     /** @todo popups missing */
170     try{
171       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
172       extraInfo.put("languagePopUpData", popUpData );
173       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
174     } catch (Exception e) {
175       theLog.printError("languagePopUpData or getTopicslist failed "
176                         +e.toString());
177       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
178     } 
179       
180     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
181   }
182
183   /**
184    *  Method for inserting an open posting into the Database and delivering
185    *  the postingDone Page
186    */
187
188   public void insposting(HttpServletRequest req, HttpServletResponse res)
189     throws ServletModuleException, ServletModuleUserException
190   {
191     SimpleHash mergeData = new SimpleHash();
192     boolean setMedia=false;
193                 boolean setTopic = false;
194
195     try {
196       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
197           
198       HashMap withValues = mp.getParameters();
199
200       if ((((String)withValues.get("title")).length() == 0) ||
201           (((String)withValues.get("description")).length() == 0) ||
202           (((String)withValues.get("content_data")).length() == 0))
203             throw new ServletModuleUserException("Missing field");
204       
205       // call the routines that escape html
206
207       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
208         String k=(String)i.next();
209         String v=(String)withValues.get(k);
210         
211         if (k.equals("content_data")){
212           //this doesn't quite work yet, so for now, all html goes
213           //withValues.put(k,StringUtil.approveHTMLTags(v));
214           //withValues.put(k,StringUtil.removeHTMLTags(v));
215         } else {
216           withValues.put(k,StringUtil.removeHTMLTags(v));
217         }
218         
219       }
220
221       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
222       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
223       withValues.put("is_produced", "0");
224       // op-articles are not immediatly published
225       // we don't know that all is good yet (media, title is present, etc..)
226       withValues.put("is_published","0");
227       // if op direct article-type == newswire
228       if (directOp.equals("yes")) withValues.put("to_article_type","1");
229       
230       // owner is openposting user
231       withValues.put("to_publisher","1");
232       if (withValues.get("creator").toString().equals(""))
233         withValues.put("creator","Anonym");
234
235       // inserting  content into database
236       String cid = contentModule.add(withValues);
237       theLog.printDebugInfo("id: "+cid);
238       //insert was not successfull
239       if(cid==null){
240         //How do we know that it was not succesful cause of a
241         //dupe, what if it failed cause of "No space left on device"?
242         //Or is there something I am missing? Wouldn't it be better
243         //to have an explicit dupe check and then insert? I have no
244         //idea what I am talking about. this comment is in case
245         //I forget to explicitely ask. -mh
246         deliver(req, res, mergeData, postingFormDupeTemplate);
247       }
248
249       String[] to_topicsArr = mp.getParameterValues("to_topic");
250       
251                         if (to_topicsArr != null && to_topicsArr.length > 0) {
252         try{
253           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
254           setTopic = true;
255         } catch (Exception e) {
256           theLog.printError("setting content_x_topic failed");
257           contentModule.deleteById(cid);
258           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
259         } //end try
260       } //end if
261         
262       // if op contains uploaddata
263       String mediaId=null;
264       int i=1;
265       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
266         MpRequest mpReq = (MpRequest)it.next();
267         String fileName = mpReq.getFilename();
268
269         //get the content-type from what the client browser
270         //sends us. (the "Oreilly method")
271         String contentType = mpReq.getContentType();
272
273         theLog.printInfo("FROM BROWSER: "+contentType);
274
275         //if the client browser sent us unknown (text/plain is default)
276         //or if we got application/octet-stream, it's possible that
277         //the browser is in error, better check against the file extension
278         if (contentType.equals("text/plain") ||
279             contentType.equals("application/octet-stream")) {
280           /**
281            * Fallback to finding the mime-type through the standard ServletApi
282            * ServletContext getMimeType() method.
283            *
284            * This is a way to get the content-type via the .extension,
285            * we could maybe use a magic method as an additional method of
286            * figuring out the content-type, by looking at the header (first
287            * few bytes) of the file. (like the file(1) command). We could 
288            * also call the "file" command through Runtime. This is an
289            * option that I almost prefer as it is already implemented and
290            * exists with an up-to-date map on most modern Unix like systems.
291            * I haven't found a really nice implementation of the magic method
292            * in pure java yet.
293            *
294            * The first method we try thought is the "Oreilly method". It
295            * relies on the content-type that the client browser sends and 
296            * that sometimes is application-octet stream with
297            * broken/mis-configured browsers.
298            *
299            * The map file we use for the extensions is the standard web-app
300            * deployment descriptor file (web.xml). See Mir's web.xml or see
301            * your Servlet containers (most likely Tomcat) documentation.
302            * So if you support a new media type you have to make sure that 
303            * it is in this file -mh
304            */
305           ServletContext ctx =
306             (ServletContext)MirConfig.getPropAsObject("ServletContext");
307           contentType = ctx.getMimeType(fileName);
308           if (contentType==null)
309             contentType = "text/plain"; // rfc1867 says this is the default
310         }
311         HashMap mediaValues = new HashMap();
312
313         theLog.printInfo("CONTENT TYPE IS: "+contentType);
314         
315         if (contentType.equals("text/plain") ||
316             contentType.equals("application/octet-stream")) {
317           contentModule.deleteById(cid);
318           _throwBadContentType(fileName, contentType);
319         }
320
321         String mediaTitle=(String)withValues.get("media_title"+i);
322         i++;
323
324         if (mediaTitle==null)
325             mediaTitle = (String)withValues.get("title");
326
327         mediaValues.put("title", mediaTitle);
328         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
329         mediaValues.put("to_publisher", "1"); // op user
330         mediaValues.put("to_media_folder", "7"); // op media_folder
331         mediaValues.put("is_produced", "0");
332         mediaValues.put("is_published","0");
333
334         // @todo this should probably be moved to DatabaseMediaType -mh
335         String[] cTypeSplit = StringUtil.split(contentType, "/");
336         String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
337
338         DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
339         EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
340
341         String mediaTypeId = null;
342         MirMedia mediaHandler;
343         Database mediaStorage;
344         ProducerMedia mediaProducer;
345  
346         //if we didn't find an entry matching the
347         //content-type int the table.
348         if (mediaTypesList.size() == 0) {
349           contentModule.deleteById(cid);
350           _throwBadContentType(fileName, contentType);
351         }
352
353         Entity mediaType = null;
354         Entity mediaType2 = null;
355         
356         // find out if we an exact content-type match if so take it.
357         // otherwise try to match majortype/*
358         // @todo this should probably be moved to DatabaseMediaType -mh
359         for(int j=0;j<mediaTypesList.size();j++) {
360           if(contentType.equals(
361                 mediaTypesList.elementAt(j).getValue("mime_type")))
362             mediaType = mediaTypesList.elementAt(j);
363           else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
364                     cTypeSplit[0]+"/*") )
365             mediaType2= mediaTypesList.elementAt(j); 
366         } 
367
368         if ( (mediaType == null) && (mediaType2 == null) ) {
369           contentModule.deleteById(cid);
370           _throwBadContentType(fileName, contentType);
371         }
372         else if( (mediaType == null) && (mediaType2 != null) )
373           mediaType = mediaType2;
374
375         //get the class names from the media_type table.
376         mediaTypeId = mediaType.getId();
377         try {
378           // ############### @todo: merge these and the getURL call into one
379           // getURL helper call that just takes the Entity as a parameter
380           // along with media_type
381           mediaHandler = MediaHelper.getHandler(mediaType);
382           mediaStorage = MediaHelper.getStorage(mediaType,
383                                               "mircoders.storage.Database");
384           Class prodCls = Class.forName("mircoders.producer.Producer"
385                                             +mediaType.getValue("tablename"));
386           mediaProducer = (ProducerMedia)prodCls.newInstance();
387         } catch (Exception e) {
388           theLog.printError("getting media handler failed: "+e.toString());
389           contentModule.deleteById(cid);
390           throw new ServletModuleException("getting media handler failed: "
391                                           +e.toString());
392         }
393
394         mediaValues.put("to_media_type",mediaTypeId);
395
396         //load the classes via reflection
397         String MediaId;
398         Entity mediaEnt = null;
399         try {
400           mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
401           mediaEnt.setStorage(mediaStorage);
402           mediaEnt.setValues(mediaValues);
403           mediaId = mediaEnt.insert();
404
405           //save and store the media data/metadata
406           mediaHandler.set(mpReq.getMedia(), mediaEnt,
407                           mediaType);
408
409           //were done with mpReq at this point, dereference it.
410           //as it contains mucho mem. -mh 01.10.2001
411           mpReq=null;
412           
413           //we got this far, associate the media to the article
414           mediaEnt.setValueForProperty("is_published","1");
415           mediaEnt.update();
416           //produce it
417           mediaProducer.handle(null, null, false, false, mediaId);
418           DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
419         } catch (Exception e) {
420           theLog.printError("setting media failed: "+e.toString());
421           contentModule.deleteById(cid);
422           throw new ServletModuleException("setting media failed: "
423                                             +e.toString());
424         }
425
426       } //end for Iterator...
427
428       //if we're here all is ok...
429       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
430       contentEnt.setValueForProperty("is_published","1");
431       contentEnt.update();
432
433
434       //dereference mp. -mh
435       mp=null;
436
437       // producing openpostinglist
438       new ProducerOpenPosting().handle(null,null,false,false);
439       // producing new page
440       new ProducerContent().handle(null, null, false, false,cid);
441       //if direct op producing startpage
442       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
443       
444                         //produce the topicPages if set
445                         //should be more intelligent
446                         //if(setTopic==true) new ProducerTopics().handle(null,null);
447                         
448       // sync the server
449       //should be configureable
450       int exitValue = Helper.rsync();
451       theLog.printDebugInfo("rsync: "+exitValue);
452
453     }
454     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
455     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
456     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
457
458     deliver(req, res, mergeData, postingFormDoneTemplate);
459   }
460
461   private void _throwBadContentType (String fileName, String contentType)
462     throws ServletModuleUserException {
463
464     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
465                           +contentType);
466     throw new ServletModuleUserException("The file you uploaded is of the "
467         +"following mime-type: "+contentType
468         +", we do not support this mime-type. "
469         +"Error One or more files of unrecognized type. Sorry");
470   }
471       
472 }
473
474