2374afe7ffa9b794c093a17e5399d687e4e11e9d
[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, postingFormDupeTemplate;
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       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
59       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
60       mainModule = new ModuleComment(DatabaseComment.getInstance());
61       contentModule = new ModuleContent(DatabaseContent.getInstance());
62       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
63       imageModule = new ModuleImages(DatabaseImages.getInstance());
64       defaultAction="addposting";
65     }
66     catch (StorageObjectException e) {
67         theLog.printError("servletmoduleopenindy could not be initialized");
68     }
69   }
70
71
72   /**
73    *  Method for making a comment
74    */
75
76   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
77   {
78     String aid = req.getParameter("aid"); // the article id the comment will belong to
79     if (aid!=null && !aid.equals(""))
80     {
81       SimpleHash mergeData = new SimpleHash();
82       // ok, article
83       mergeData.put("aid", aid);
84       deliver(req, res, mergeData, commentFormTemplate);
85     }
86     else throw new ServletModuleException("aid not set!");
87   }
88
89   /**
90    *  Method for inserting a comment into the Database and delivering
91    *  the commentDone Page
92    */
93
94   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
95   {
96     String aid = req.getParameter("to_media"); // the article id the comment will belong to
97     if (aid!=null && !aid.equals(""))
98     {
99       // ok, collecting data from form
100       try {
101         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
102        
103         //no html in comments(for now)
104         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
105             String k=(String)i.next();
106             String v=(String)withValues.get(k);
107             
108             withValues.put(k,StringUtil.removeHTMLTags(v));
109         }
110         withValues.put("is_published","1");
111
112         // inserting into database
113         String id = mainModule.add(withValues);
114         theLog.printDebugInfo("id: "+id);
115         //insert was not successfull
116         if(id==null){
117           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
118         }
119         
120         // producing new page
121         new ProducerContent().handle(null, null, true, false, aid);
122
123         // sync the server
124         int exitValue = Helper.rsync();
125         theLog.printDebugInfo("rsync:"+exitValue);
126
127         // redirecting to url
128         // should implement back to article
129         SimpleHash mergeData = new SimpleHash();
130         deliver(req, res, mergeData, commentFormDoneTemplate);
131       }
132       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
133       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
134
135     }
136     else throw new ServletModuleException("aid not set!");
137
138   }
139
140   /**
141    *  Method for delivering the form-Page for open posting
142    */
143
144   public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
145   {
146     SimpleHash mergeData = new SimpleHash();
147     String numOfMedia = req.getParameter("medianum");
148     if(numOfMedia==null||numOfMedia.equals("")){
149       numOfMedia="1";
150     }
151     
152     int mediaNum = Integer.parseInt(numOfMedia);
153     SimpleList mediaFields = new SimpleList();
154     for(int i =0; i<mediaNum;i++){
155       Integer mNum = new Integer(i+1);
156       mediaFields.add(mNum.toString());
157     }
158     mergeData.put("medianum",numOfMedia);
159     mergeData.put("mediafields",mediaFields);
160     mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
161     
162     
163     /** @todo popups missing */
164     try{
165       mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
166     } catch (Exception e) {
167       theLog.printError("languagePopUpData failed");
168     }
169     deliver(req, res, mergeData, postingFormTemplate);
170   }
171
172   /**
173    *  Method for inserting an open posting into the Database and delivering
174    *  the postingDone Page
175    */
176
177   public void insposting(HttpServletRequest req, HttpServletResponse res)
178     throws ServletModuleException
179   {
180     SimpleHash mergeData = new SimpleHash();
181     boolean setMedia=false;
182
183     try {
184       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
185           
186       HashMap withValues = mp.getParameters();
187       
188       // call the routines that escape html
189
190       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
191         String k=(String)i.next();
192         String v=(String)withValues.get(k);
193         
194         if (k.equals("content_data")){
195           //this doesn't quite work yet, so for now, all html goes
196           //withValues.put(k,StringUtil.approveHTMLTags(v));
197           //withValues.put(k,StringUtil.removeHTMLTags(v));
198         } else {
199           withValues.put(k,StringUtil.removeHTMLTags(v));
200         }
201         
202       }
203
204       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
205       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
206       withValues.put("is_produced", "0");
207       // op-articles are immediatly published
208       withValues.put("is_published","1");
209       // if op direct article-type == newswire
210       if (directOp.equals("yes")) withValues.put("to_article_type","1");
211       
212       // owner is openposting user
213       withValues.put("to_publisher","1");
214       if (withValues.get("creator").toString().equals(""))
215         withValues.put("creator","Anonym");
216
217       // inserting  content into database
218       String cid = contentModule.add(withValues);
219       theLog.printDebugInfo("id: "+cid);
220       //insert was not successfull
221       if(cid==null){
222         deliver(req, res, mergeData, postingFormDupeTemplate);
223       }
224
225       String[] to_topicsArr = mp.getParameterValues("to_topic");
226       if (to_topicsArr != null && to_topicsArr.length > 0) {
227         try{
228           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
229           theLog.printError("setting content_x_topic success");
230         } catch (Exception e) {
231           theLog.printError("setting content_x_topic failed");
232         } //end try
233       } //end if
234         
235       // if op contains uploaddata
236       String mediaId=null;
237       int i=1;
238       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
239         MpRequest mpReq = (MpRequest)it.next();
240         String fileName = mpReq.getFilename();
241         String contentType = FileUtil.guessContentTypeFromName(fileName);
242         HashMap mediaValues = new HashMap();
243
244         theLog.printError("CONTENT TYPE IS: "+contentType);
245
246         if ((contentType==null) || (contentType=="application/octet-stream")) {
247           throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
248         }
249
250
251         String mediaTitle=(String)withValues.get("media_title"+i);
252         i++;
253
254         if (mediaTitle==null)
255             mediaTitle = (String)withValues.get("title");
256
257         mediaValues.put("title", mediaTitle);
258         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
259         mediaValues.put("to_publisher", "1"); // op user
260         mediaValues.put("to_media_folder", "7"); // op media_folder
261         mediaValues.put("is_produced", "0");
262         mediaValues.put("is_published","1");
263
264         String wc = " mime_type='"+contentType+"'";
265
266         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
267
268         String mediaTypeId = null;
269         String mediaStorageName = null;
270         String mediaHandlerName = null;
271   
272         if (mediaTypesList.size() > 0) {
273           mediaTypeId = mediaTypesList.elementAt(0).getId();
274           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
275           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
276           mediaValues.put("to_media_type",mediaTypeId);
277           
278           String MediaId;
279           try {
280                 Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
281                 Method m = mediaStorageClass.getMethod("getInstance", null);
282                 Database mediaStorage = (Database)m.invoke(null, null);
283                 Entity mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
284                 mediaEnt.setStorage(mediaStorage);
285                 mediaEnt.setValues(mediaValues);
286                 mediaId = mediaEnt.insert();
287
288                 theLog.printError("done inserting!!! ");
289                 Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
290                 MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
291                 mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
292                 theLog.printError("about to run ProduceMedia"+mediaId);
293               if(mediaId!=null){
294                 new ProducerMedia().handle(null, null, false, false, mediaId);
295               }
296           } catch (Exception e) {
297                 theLog.printError("setting uploaded_media failed: "+e.toString());
298           }
299               
300
301           try{
302               DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
303               theLog.printError("setting content_x_media success");
304           } catch (Exception e) {
305               theLog.printError("setting content_x_media failed");
306           }
307
308         } else {
309           theLog.printDebugInfo("Wrong file uploaded!: " + fileName);
310           throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
311         }
312           
313       }
314
315       // producing openpostinglist
316       new ProducerOpenPosting().handle(null,null,false,false);
317       // producing new page
318       new ProducerContent().handle(null, null, false, false,cid);
319       //if direct op producing startpage
320       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
321       
322       // sync the server
323       //should be configureable
324       int exitValue = Helper.rsync();
325       theLog.printDebugInfo("rsync: "+exitValue);
326
327     }
328     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
329     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
330     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
331
332     deliver(req, res, mergeData, postingFormDoneTemplate);
333   }
334
335 }
336
337