a bunch of bufixes and also a new ServletModuleUserException so that we
[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, commentFormDupeTemplate;
41   private String          postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
42   private ModuleContent   contentModule;
43   private ModuleImages    imageModule;
44   private ModuleTopics    themenModule;
45   private String          directOp ="yes";
46
47   // Singelton / Kontruktor
48   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
49   public static ServletModule getInstance() { return instance; }
50
51   private ServletModuleOpenIndy() {
52     try {
53       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
54       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
55       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
56       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
57       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
58       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
59       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
60       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
61       mainModule = new ModuleComment(DatabaseComment.getInstance());
62       contentModule = new ModuleContent(DatabaseContent.getInstance());
63       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
64       imageModule = new ModuleImages(DatabaseImages.getInstance());
65       defaultAction="addposting";
66     }
67     catch (StorageObjectException e) {
68         theLog.printError("servletmoduleopenindy could not be initialized");
69     }
70   }
71
72
73   /**
74    *  Method for making a comment
75    */
76
77   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
78   {
79     String aid = req.getParameter("aid"); // the article id the comment will belong to
80     if (aid!=null && !aid.equals(""))
81     {
82       SimpleHash mergeData = new SimpleHash();
83       // ok, article
84       mergeData.put("aid", aid);
85       deliver(req, res, mergeData, commentFormTemplate);
86     }
87     else throw new ServletModuleException("aid not set!");
88   }
89
90   /**
91    *  Method for inserting a comment into the Database and delivering
92    *  the commentDone Page
93    */
94
95   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
96   {
97     String aid = req.getParameter("to_media"); // the article id the comment will belong to
98     if (aid!=null && !aid.equals(""))
99     {
100       // ok, collecting data from form
101       try {
102         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
103        
104         //no html in comments(for now)
105         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
106             String k=(String)i.next();
107             String v=(String)withValues.get(k);
108             
109             withValues.put(k,StringUtil.removeHTMLTags(v));
110         }
111         withValues.put("is_published","1");
112
113         // inserting into database
114         String id = mainModule.add(withValues);
115         theLog.printDebugInfo("id: "+id);
116         //insert was not successfull
117         if(id==null){
118           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
119         }
120         
121         // producing new page
122         new ProducerContent().handle(null, null, true, false, aid);
123
124         // sync the server
125         int exitValue = Helper.rsync();
126         theLog.printDebugInfo("rsync:"+exitValue);
127
128         // redirecting to url
129         // should implement back to article
130         SimpleHash mergeData = new SimpleHash();
131         deliver(req, res, mergeData, commentFormDoneTemplate);
132       }
133       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
134       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
135
136     }
137     else throw new ServletModuleException("aid not set!");
138
139   }
140
141   /**
142    *  Method for delivering the form-Page for open posting
143    */
144
145   public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
146   {
147     SimpleHash mergeData = new SimpleHash();
148     String numOfMedia = req.getParameter("medianum");
149     if(numOfMedia==null||numOfMedia.equals("")){
150       numOfMedia="1";
151     }
152     
153     int mediaNum = Integer.parseInt(numOfMedia);
154     SimpleList mediaFields = new SimpleList();
155     for(int i =0; i<mediaNum;i++){
156       Integer mNum = new Integer(i+1);
157       mediaFields.add(mNum.toString());
158     }
159     mergeData.put("medianum",numOfMedia);
160     mergeData.put("mediafields",mediaFields);
161     mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
162     
163     
164     /** @todo popups missing */
165     try{
166       mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
167     } catch (Exception e) {
168       theLog.printError("languagePopUpData failed");
169     }
170     deliver(req, res, mergeData, postingFormTemplate);
171   }
172
173   /**
174    *  Method for inserting an open posting into the Database and delivering
175    *  the postingDone Page
176    */
177
178   public void insposting(HttpServletRequest req, HttpServletResponse res)
179     throws ServletModuleException, ServletModuleUserException
180   {
181     SimpleHash mergeData = new SimpleHash();
182     boolean setMedia=false;
183
184     try {
185       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
186           
187       HashMap withValues = mp.getParameters();
188
189       if ((((String)withValues.get("title")).length() == 0) ||
190           (((String)withValues.get("description")).length() == 0) ||
191           (((String)withValues.get("content_data")).length() == 0))
192             throw new ServletModuleUserException("Missing field");
193       
194       // call the routines that escape html
195
196       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
197         String k=(String)i.next();
198         String v=(String)withValues.get(k);
199         
200         if (k.equals("content_data")){
201           //this doesn't quite work yet, so for now, all html goes
202           //withValues.put(k,StringUtil.approveHTMLTags(v));
203           //withValues.put(k,StringUtil.removeHTMLTags(v));
204         } else {
205           withValues.put(k,StringUtil.removeHTMLTags(v));
206         }
207         
208       }
209
210       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
211       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
212       withValues.put("is_produced", "0");
213       // op-articles are not immediatly published
214       // we don't know that all is good yet (media, title is present, etc..)
215       withValues.put("is_published","0");
216       // if op direct article-type == newswire
217       if (directOp.equals("yes")) withValues.put("to_article_type","1");
218       
219       // owner is openposting user
220       withValues.put("to_publisher","1");
221       if (withValues.get("creator").toString().equals(""))
222         withValues.put("creator","Anonym");
223
224       // inserting  content into database
225       String cid = contentModule.add(withValues);
226       theLog.printDebugInfo("id: "+cid);
227       //insert was not successfull
228       if(cid==null){
229         //How do we know that it was not succesful cause of a 
230         //dupe, what if it failed cause of "No space left on device"?
231         //Or is there something I am missing? Wouldn't it be better
232         //to have an explicit dupe check and then insert? I have no
233         //idea what I am talking about. this comment is in case
234         //I forget to explicitely ask. -mh
235         deliver(req, res, mergeData, postingFormDupeTemplate);
236       }
237
238       String[] to_topicsArr = mp.getParameterValues("to_topic");
239       if (to_topicsArr != null && to_topicsArr.length > 0) {
240         try{
241           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
242           theLog.printError("setting content_x_topic success");
243         } catch (Exception e) {
244           theLog.printError("setting content_x_topic failed");
245         } //end try
246       } //end if
247         
248       // if op contains uploaddata
249       String mediaId=null;
250       int i=1;
251       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
252         MpRequest mpReq = (MpRequest)it.next();
253         String fileName = mpReq.getFilename();
254
255         //get the content-type from what the client browser
256         //sends us. (the "Oreilly method")
257         String contentType = mpReq.getContentType();
258
259         theLog.printError("FROM BROWSER: "+contentType);
260
261         //if the client browser sent us unknown (text/plain is default)
262         //or if we got application/octet-stream, it's possible that
263         //the browser is in error, better check against the file extension
264         if (contentType.equals("text/plain") || 
265             contentType.equals("application/octet-stream")) {
266             /** 
267              * This is just a temporary way to get the content-type via
268              * the .extension , we could maybe use a magic method, by looking
269              * at the header (first few bytes) of the file. (like the file(1)
270              * command).
271              * The Oreilly method  relies on the content-type that the client 
272              * browser sends and that sometimes is application-octet stream with
273              * broken/mis-configured browsers.
274              * 
275              * The map file should be Mir/content-types.properties, it's the 
276              * default Sun Java file with some additional entries that it did 
277              * not have. So if you support a new media type you have to make 
278              * sure that it is in this file -mh
279              */
280             contentType = FileUtil.guessContentTypeFromName(fileName);
281             theLog.printError("tYPE: "+contentType);
282             if (contentType==null)
283                 contentType = "text/plain"; // rfc1867 says this is the default
284         }
285         HashMap mediaValues = new HashMap();
286
287         theLog.printError("CONTENT TYPE IS: "+contentType);
288         
289         if (contentType.equals("text/plain") || 
290             contentType.equals("application/octet-stream")) {
291           throw new ServletModuleUserException("One or more files of unrecognized types");
292         }
293
294         String mediaTitle=(String)withValues.get("media_title"+i);
295         i++;
296
297         if (mediaTitle==null)
298             mediaTitle = (String)withValues.get("title");
299
300         mediaValues.put("title", mediaTitle);
301         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
302         mediaValues.put("to_publisher", "1"); // op user
303         mediaValues.put("to_media_folder", "7"); // op media_folder
304         mediaValues.put("is_produced", "0");
305         mediaValues.put("is_published","0");
306
307         //the where clause to find the media_type entry
308         //from the content-type.
309         //we use the media type entry to lookup the 
310         //media Handler/Storage classes
311         String wc = " mime_type='"+contentType+"'";
312
313         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
314
315         String mediaTypeId = null;
316         String mediaStorageName = null;
317         String mediaHandlerName = null;
318  
319         //if we found an entry matching the
320         //content-type int the table.
321         if (mediaTypesList.size() > 0) {
322           //get the class names from the media_type table.
323           mediaTypeId = mediaTypesList.elementAt(0).getId();
324           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
325           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
326           mediaValues.put("to_media_type",mediaTypeId);
327          
328           //load the classes via reflection
329           String MediaId;
330           Entity mediaEnt = null;
331           try {
332                 Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
333                 Method m = mediaStorageClass.getMethod("getInstance", null);
334                 Database mediaStorage = (Database)m.invoke(null, null);
335                 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
336                 mediaEnt.setStorage(mediaStorage);
337                 mediaEnt.setValues(mediaValues);
338                 mediaId = mediaEnt.insert();
339
340                 Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
341                 MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
342                 //save and store the media data/metadata
343                 mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
344
345                 //were done with mpReq at this point, dereference it.
346                 //as it contains mucho mem. -mh 01.10.2001
347                 mpReq=null;
348               
349           } catch (Exception e) {
350                 theLog.printError("setting uploaded_media failed: "+e.toString());
351           } //end try-catch
352               
353           //we got this far, associate the media to the article
354           try{
355               theLog.printError("ID"+mediaId);
356               DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
357               mediaEnt.setValueForProperty("is_published","1");
358               mediaEnt.update();
359               new ProducerMedia().handle(null,null,false,false,mediaId);
360               theLog.printError("setting content_x_media success");
361           } catch (Exception e) {
362               theLog.printError("setting content_x_media failed");
363           }
364
365         } else {
366           contentModule.deleteById(cid);
367           theLog.printDebugInfo("Wrong file uploaded!: " + fileName);
368           throw new ServletModuleUserException("One or more files of unrecognized types");
369         } // end if-else mediaTypesList.size() > 0
370           
371       } //end for Iterator...
372
373       //if we're here all is ok...
374       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
375       contentEnt.setValueForProperty("is_published","1");
376       contentEnt.update();
377
378       //dereference mp. -mh
379       mp=null;
380
381       // producing openpostinglist
382       new ProducerOpenPosting().handle(null,null,false,false);
383       // producing new page
384       new ProducerContent().handle(null, null, false, false,cid);
385       //if direct op producing startpage
386       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
387       
388       // sync the server
389       //should be configureable
390       int exitValue = Helper.rsync();
391       theLog.printDebugInfo("rsync: "+exitValue);
392
393     }
394     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
395     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
396     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
397
398     deliver(req, res, mergeData, postingFormDoneTemplate);
399   }
400
401 }
402
403