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