big media merge ~75% done.. still needs some tweaks, more docs later.
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 package mircoders.servlet;
2
3 import java.io.*;
4 import java.sql.*;
5 import java.util.*;
6 import java.net.*;
7 import java.lang.reflect.*;
8 import javax.servlet.*;
9 import javax.servlet.http.*;
10
11 import freemarker.template.*;
12 import com.oreilly.servlet.multipart.*;
13 import com.oreilly.servlet.*;
14
15 import mir.servlet.*;
16 import mir.module.*;
17 import mir.misc.*;
18 import mir.entity.*;
19 import mir.storage.*;
20 import mir.media.*;
21
22 import mircoders.entity.*;
23 import mircoders.storage.*;
24 import mircoders.module.*;
25 import mircoders.producer.*;
26
27 /*
28  *  ServletModuleOpenIndy -
29  *   is the open-access-servlet, which is responsible for
30  *    adding comments to articles &
31  *    open-postings to the newswire
32  *
33  * @author RK
34  */
35
36 public class ServletModuleOpenIndy extends ServletModule
37 {
38
39   private String          commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
40   private String          postingFormTemplate, postingFormDoneTemplate;
41   private ModuleContent   contentModule;
42   private ModuleImages    imageModule;
43   private ModuleTopics         themenModule;
44   private String          directOp ="yes";
45
46   // Singelton / Kontruktor
47   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
48   public static ServletModule getInstance() { return instance; }
49
50   private ServletModuleOpenIndy() {
51     try {
52       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
53       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
54       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
55       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
56       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
57       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
58       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
59       mainModule = new ModuleComment(DatabaseComment.getInstance());
60       contentModule = new ModuleContent(DatabaseContent.getInstance());
61       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
62       imageModule = new ModuleImages(DatabaseImages.getInstance());
63       defaultAction="addposting";
64     }
65     catch (StorageObjectException e) {
66         theLog.printError("servletmoduleopenindy could not be initialized");
67     }
68   }
69
70
71   /**
72    *  Method for making a comment
73    */
74
75   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
76   {
77     String aid = req.getParameter("aid"); // the article id the comment will belong to
78     if (aid!=null && !aid.equals(""))
79     {
80       SimpleHash mergeData = new SimpleHash();
81       // ok, article
82       mergeData.put("aid", aid);
83       deliver(req, res, mergeData, commentFormTemplate);
84     }
85     else throw new ServletModuleException("aid not set!");
86   }
87
88   /**
89    *  Method for inserting a comment into the Database and delivering
90    *  the commentDone Page
91    */
92
93   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
94   {
95     String aid = req.getParameter("to_media"); // the article id the comment will belong to
96     if (aid!=null && !aid.equals(""))
97     {
98       // ok, collecting data from form
99       try {
100         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
101         withValues.put("is_published","1");
102
103                 // Dupe detection
104 //              EntityList com = mainModule.getByWhereClause("description='"+req.getParameter("description")+"' AND to_media='"+aid+"' AND creator='"+req.getParameter("creator")+"'", 0);
105 //              if (com.getCount() > 0) {
106 //              theLog.printDebugInfo("Comment dupe dropped for article "+aid);
107 //              deliver(req, res, (TemplateModelRoot) null, commentFormDupeTemplate);
108 //              } else {
109
110                 // inserting into database
111                 String id = mainModule.add(withValues);
112                 
113                 // producing new page
114                 new ProducerContent().handle(null, null, true, false, aid);
115
116                 // sync the server
117                 int exitValue = Helper.rsync();
118                 theLog.printDebugInfo("rsync:"+exitValue);
119
120                 // redirecting to url
121                 // should implement back to article
122                 SimpleHash mergeData = new SimpleHash();
123                 deliver(req, res, mergeData, commentFormDoneTemplate);
124 //              }
125       }
126       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
127       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
128
129     }
130     else throw new ServletModuleException("aid not set!");
131
132   }
133
134   /**
135    *  Method for delivering the form-Page for open posting
136    */
137
138   public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
139   {
140     SimpleHash mergeData = new SimpleHash();
141     String numOfMedia = req.getParameter("medianum");
142     if(numOfMedia==null||numOfMedia.equals("")){
143       numOfMedia="1";
144     }
145     
146     int mediaNum = Integer.parseInt(numOfMedia);
147     SimpleList mediaFields = new SimpleList();
148     for(int i =0; i<mediaNum;i++){
149       Integer mNum = new Integer(i+1);
150       mediaFields.add(mNum.toString());
151     }
152     mergeData.put("medianum",numOfMedia);
153     mergeData.put("mediafields",mediaFields);
154     mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
155     
156     
157     /** @todo popups missing */
158     try{
159       mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
160     } catch (Exception e) {
161       theLog.printError("languagePopUpData failed");
162     }
163     deliver(req, res, mergeData, postingFormTemplate);
164   }
165
166   /**
167    *  Method for inserting an open posting into the Database and delivering
168    *  the postingDone Page
169    */
170
171   public void insposting(HttpServletRequest req, HttpServletResponse res)
172     throws ServletModuleException
173   {
174     SimpleHash mergeData = new SimpleHash();
175     boolean setMedia=false;
176
177     try {
178       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
179           
180       HashMap withValues = mp.getParameters();
181       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
182       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
183       withValues.put("is_produced", "0");
184       // op-articles are immediatly published
185       withValues.put("is_published","1");
186       // if op direct article-type == newswire
187       if (directOp.equals("yes")) withValues.put("to_article_type","1");
188       
189       // owner is openposting user
190       withValues.put("to_publisher","1");
191       if (withValues.get("creator").toString().equals(""))
192         withValues.put("creator","Anonym");
193
194       // inserting  content into database
195       String cid = contentModule.add(withValues);
196
197       String[] to_topicsArr = mp.getParameterValues("to_topic"); 
198       if (to_topicsArr != null && to_topicsArr.length > 0) {
199         try{
200           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
201           theLog.printError("setting content_x_topic success");
202         } catch (Exception e) {
203           theLog.printError("setting content_x_topic failed");
204         } //end try
205       } //end if
206         
207       // if op contains uploaddata
208       String mediaId=null;
209       int i=1;
210       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
211         MpRequest mpReq = (MpRequest)it.next();
212         String fileName = mpReq.getFilename();
213         String contentType = FileUtil.guessContentTypeFromName(fileName);
214         HashMap mediaValues = new HashMap();
215
216         theLog.printError("CONTENT TYPE IS: "+contentType);
217
218         if ((contentType==null) || (contentType=="application/octet-stream")) {
219           throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
220         }
221
222
223         String mediaTitle=(String)withValues.get("media_title"+i);
224         i++;
225
226         if (mediaTitle==null)
227             mediaTitle = (String)withValues.get("title");
228
229         mediaValues.put("title", mediaTitle);
230         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
231         mediaValues.put("to_publisher", "1"); // op user
232         mediaValues.put("to_media_folder", "7"); // op media_folder
233         mediaValues.put("is_produced", "0");
234         mediaValues.put("is_published","1");
235
236         String wc = " mime_type='"+contentType+"'";
237
238         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
239
240         String mediaTypeId = null;
241         String mediaStorageName = null;
242         String mediaHandlerName = null;
243   
244         if (mediaTypesList.size() > 0) {
245           mediaTypeId = mediaTypesList.elementAt(0).getId();
246           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
247           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
248           mediaValues.put("to_media_type",mediaTypeId);
249           
250           String MediaId;
251           try {
252                 Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
253                 Method m = mediaStorageClass.getMethod("getInstance", null);
254                 Database mediaStorage = (Database)m.invoke(null, null);
255                 Entity mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
256                 mediaEnt.setStorage(mediaStorage);
257                 mediaEnt.setValues(mediaValues);
258                 mediaId = mediaEnt.insert();
259
260                 Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
261                 MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
262                 mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
263               if(mediaId!=null){
264                 //new ProducerImages().handle(null, null, false, false, mediaId);
265               }
266           } catch (Exception e) {
267                 theLog.printError("setting uploaded_media failed: "+e.toString());
268           }
269               
270
271           try{
272               DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
273               theLog.printError("setting content_x_media success");
274           } catch (Exception e) {
275               theLog.printError("setting content_x_media failed");
276           }
277
278         } else {
279           theLog.printDebugInfo("Wrong file uploaded!: " + fileName);
280           throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
281         }
282           
283      
284             
285
286           
287
288         //MirUploadedMedia Media = MirUploadedMedia(mpReq, cid); 
289                 //mediaValues.put("title",mediaTitle);
290
291         //mediaId = Media.add();
292          /*   // this is video !!
293             //theLog.printDebugInfo("--GOT VIDEO");
294             EntityVideo entVideo = new EntityVideo(DatabaseVideos.getInstance());
295             //notice the discr here..... (imageModule).
296             entVideo.setValues(mediaValues);
297             mediaId = entVideo.insert();
298             entVideo.setVideoData(mediaData);
299           }
300           //try content type first then go by xtension?
301           else if (contentType.equals("image/jpeg") || contentType.equals("image/gif")) {
302             // this is image !!
303             mediaId = imageModule.add(mediaValues);
304             EntityImages entImage = (EntityImages)imageModule.getById(mediaId);
305   
306             int fileType = -1;
307
308             //replace all this with DatabaseContentMedia.getInst().getEn(contentType).set(mediaData) ??? w/ a catch for error, then return form w/ and error
309             if (contentType.equals("image/jpeg")) fileType=0;
310             if (contentType.equals("image/gif")) fileType=1;
311             if (fileType>=0) {
312               entImage.setImage(mediaData, fileType);
313               // inserting content and media id in table content_x_media
314               try{
315                 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
316                 theLog.printError("setting content_x_media success");
317               } catch (Exception e) {
318                 theLog.printError("setting content_x_media failed");
319               }
320               
321               // producing new page
322               if(mediaId!=null){
323                 new ProducerImages().handle(null, null, false, false, mediaId);
324               }
325             } else {
326               theLog.printDebugInfo("Wrong file uploaded!" + fileName);
327             }
328           }
329         }*/
330       }
331
332       // producing openpostinglist
333       new ProducerOpenPosting().handle(null,null,false,false);
334       // producing new page
335       new ProducerContent().handle(null, null, false, false,cid);
336       //if direct op producing startpage
337       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
338       
339
340       // sync the server
341       //should be configureable
342       int exitValue = Helper.rsync();
343       theLog.printDebugInfo("rsync: "+exitValue);
344
345     }
346     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
347     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
348     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
349
350     deliver(req, res, mergeData, postingFormDoneTemplate);
351   }
352
353 }
354