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