some indy.nl related updates
[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 import mircoders.global.*;
28 import mircoders.localizer.*;
29
30 /*
31  *  ServletModuleOpenIndy -
32  *   is the open-access-servlet, which is responsible for
33  *    adding comments to articles &
34  *    open-postings to the newswire
35  *
36  * @author RK
37  */
38
39 public class ServletModuleOpenIndy extends ServletModule
40 {
41
42   private String        commentFormTemplate, commentFormDoneTemplate,
43                         commentFormDupeTemplate;
44   private String        postingFormTemplate, postingFormDoneTemplate,
45                         postingFormDupeTemplate;
46   private ModuleContent contentModule;
47   private ModuleImages  imageModule;
48   private ModuleTopics  themenModule;
49   private String        directOp ="yes";
50   private String        passwdProtection ="yes";
51   // Singelton / Kontruktor
52   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
53   public static ServletModule getInstance() { return instance; }
54
55   private ServletModuleOpenIndy() {
56     try {
57       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
58       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
59       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
60       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
61       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
62       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
63       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
64       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
65                         passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
66       mainModule = new ModuleComment(DatabaseComment.getInstance());
67       contentModule = new ModuleContent(DatabaseContent.getInstance());
68       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
69       imageModule = new ModuleImages(DatabaseImages.getInstance());
70       defaultAction="addposting";
71
72     }
73     catch (StorageObjectException e) {
74         theLog.printError("servletmoduleopenindy could not be initialized");
75     }
76   }
77
78
79   /**
80    *  Method for making a comment
81    */
82
83   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
84   {
85     String aid = req.getParameter("aid"); // the article id the comment will belong to
86     if (aid!=null && !aid.equals(""))
87     {
88                         SimpleHash mergeData = new SimpleHash();
89
90                         // onetimepasswd
91                         if(passwdProtection.equals("yes")){
92                                 String passwd = this.createOneTimePasswd();
93                                 System.out.println(passwd);
94                                 HttpSession session = req.getSession(false);
95                                 session.setAttribute("passwd",passwd);
96                                 mergeData.put("passwd", passwd);
97                         }
98
99       mergeData.put("aid", aid);
100       deliver(req, res, mergeData, commentFormTemplate);
101     }
102     else throw new ServletModuleException("aid not set!");
103   }
104
105   /**
106    *  Method for inserting a comment into the Database and delivering
107    *  the commentDone Page
108    */
109
110   public void inscomment(HttpServletRequest req, HttpServletResponse res)
111         throws ServletModuleException,ServletModuleUserException
112   {
113     String aid = req.getParameter("to_media"); // the article id the comment will belong to
114     if (aid!=null && !aid.equals(""))
115     {
116       // ok, collecting data from form
117       try {
118         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
119
120         //no html in comments(for now)
121         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
122             String k=(String)i.next();
123             String v=(String)withValues.get(k);
124
125             withValues.put(k,StringUtil.removeHTMLTags(v));
126         }
127         withValues.put("is_published","1");
128
129                                 //checking the onetimepasswd
130                                 if(passwdProtection.equals("yes")){
131                                         HttpSession session = req.getSession(false);
132                                         String sessionPasswd = (String)session.getAttribute("passwd");
133                                         if ( sessionPasswd == null){
134                                                 throw new ServletModuleUserException("Lost password");
135                                         }
136                                         String passwd = req.getParameter("passwd");
137                                         if ( passwd == null || (!sessionPasswd.equals(passwd))) {
138                                                 throw new ServletModuleUserException("Missing password");
139                                         }
140                                         session.invalidate();
141                                 }
142
143         // inserting into database
144         String id = mainModule.add(withValues);
145         theLog.printDebugInfo("id: "+id);
146         //insert was not successfull
147         if(id==null){
148           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
149         }
150         else {
151           DatabaseContent.getInstance().setUnproduced("id="+aid);
152           MirGlobal.localizer().openPostings().afterCommentPosting();
153
154         }
155
156         // redirecting to url
157         // should implement back to article
158         SimpleHash mergeData = new SimpleHash();
159         deliver(req, res, mergeData, commentFormDoneTemplate);
160       }
161       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
162       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
163
164     }
165     else throw new ServletModuleException("aid not set!");
166
167   }
168
169   /**
170    *  Method for delivering the form-Page for open posting
171    */
172
173   public void addposting(HttpServletRequest req, HttpServletResponse res)
174     throws ServletModuleException {
175     SimpleHash mergeData = new SimpleHash();
176
177                 // onetimepasswd
178                 if(passwdProtection.equals("yes")){
179                         String passwd = this.createOneTimePasswd();
180                         System.out.println(passwd);
181                         HttpSession session = req.getSession(false);
182                         session.setAttribute("passwd",passwd);
183                         mergeData.put("passwd", passwd);
184                 }
185
186     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
187     String numOfMedia = req.getParameter("medianum");
188     if(numOfMedia==null||numOfMedia.equals("")){
189       numOfMedia="1";
190     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
191       numOfMedia = maxMedia;
192     }
193
194     int mediaNum = Integer.parseInt(numOfMedia);
195     SimpleList mediaFields = new SimpleList();
196     for(int i =0; i<mediaNum;i++){
197       Integer mNum = new Integer(i+1);
198       mediaFields.add(mNum.toString());
199     }
200     mergeData.put("medianum",numOfMedia);
201     mergeData.put("mediafields",mediaFields);
202
203
204     SimpleHash extraInfo = new SimpleHash();
205     try{
206       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
207       extraInfo.put("languagePopUpData", popUpData );
208       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
209
210 // ML: Bolivia specific, will move it towards localization
211       extraInfo.put("topics", themenModule.getTopicsList());
212       String defaultCity = req.getParameter("city");
213       if(defaultCity!=null && !defaultCity.equals("")){
214         extraInfo.put("city", defaultCity);
215       }
216
217     } catch (Exception e) {
218       theLog.printError("languagePopUpData or getTopicslist failed "
219                         +e.toString());
220       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
221     }
222
223
224
225     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
226   }
227
228   /**
229    *  Method for inserting an open posting into the Database and delivering
230    *  the postingDone Page
231    */
232
233   public void insposting(HttpServletRequest req, HttpServletResponse res)
234     throws ServletModuleException, ServletModuleUserException
235   {
236     SimpleHash mergeData = new SimpleHash();
237     boolean setMedia=false;
238                 boolean setTopic = false;
239
240     try {
241       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
242
243       HashMap withValues = mp.getParameters();
244
245                         //checking the onetimepasswd
246                         if(passwdProtection.equals("yes")){
247                                 HttpSession session = req.getSession(false);
248                                 String sessionPasswd = (String)session.getAttribute("passwd");
249                                 if ( sessionPasswd == null){
250                                         throw new ServletModuleUserException("Lost password");
251                                 }
252                                 String passwd = (String)withValues.get("passwd");
253                                 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
254                                         throw new ServletModuleUserException("Missing password");
255                                 }
256                                 session.invalidate();
257                         }
258
259       if ((((String)withValues.get("title")).length() == 0) ||
260           (((String)withValues.get("description")).length() == 0) ||
261           (((String)withValues.get("content_data")).length() == 0))
262             throw new ServletModuleUserException("Missing field");
263
264       // call the routines that escape html
265
266       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
267         String k=(String)i.next();
268         String v=(String)withValues.get(k);
269
270         if (k.equals("content_data")){
271           //this doesn't quite work yet, so for now, all html goes
272           //withValues.put(k,StringUtil.approveHTMLTags(v));
273           //withValues.put(k,StringUtil.removeHTMLTags(v));
274         } else {
275           withValues.put(k,StringUtil.removeHTMLTags(v));
276         }
277
278       }
279
280       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
281       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
282       withValues.put("is_produced", "0");
283       // op-articles are not immediatly published
284       // we don't know that all is good yet (media, title is present, etc..)
285       withValues.put("is_published","0");
286       // if op direct article-type == newswire
287       if (directOp.equals("yes")) withValues.put("to_article_type","1");
288
289       withValues.put("to_publisher","1");
290
291       // owner is openposting user
292 //      ML: this is not multi-language friendly and this can be done in a template
293 //      if (withValues.get("creator").toString().equals(""))
294 //        withValues.put("creator","Anonym");
295
296       // inserting  content into database
297       String cid = contentModule.add(withValues);
298       theLog.printDebugInfo("id: "+cid);
299       //insert was not successfull
300       if(cid==null){
301         //How do we know that it was not succesful cause of a
302         //dupe, what if it failed cause of "No space left on device"?
303         //Or is there something I am missing? Wouldn't it be better
304         //to have an explicit dupe check and then insert? I have no
305         //idea what I am talking about. this comment is in case
306         //I forget to explicitely ask. -mh
307         deliver(req, res, mergeData, postingFormDupeTemplate);
308       }
309
310       String[] to_topicsArr = mp.getParameterValues("to_topic");
311
312                         if (to_topicsArr != null && to_topicsArr.length > 0) {
313         try{
314           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
315           setTopic = true;
316         } catch (Exception e) {
317           theLog.printError("setting content_x_topic failed");
318           contentModule.deleteById(cid);
319           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
320         } //end try
321       } //end if
322
323       // if op contains uploaddata
324       String mediaId=null;
325       int i=1;
326       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
327         MpRequest mpReq = (MpRequest)it.next();
328         String fileName = mpReq.getFilename();
329
330         //get the content-type from what the client browser
331         //sends us. (the "Oreilly method")
332         String contentType = mpReq.getContentType();
333
334         theLog.printInfo("FROM BROWSER: "+contentType);
335
336         //if the client browser sent us unknown (text/plain is default)
337         //or if we got application/octet-stream, it's possible that
338         //the browser is in error, better check against the file extension
339         if (contentType.equals("text/plain") ||
340             contentType.equals("application/octet-stream")) {
341           /**
342            * Fallback to finding the mime-type through the standard ServletApi
343            * ServletContext getMimeType() method.
344            *
345            * This is a way to get the content-type via the .extension,
346            * we could maybe use a magic method as an additional method of
347            * figuring out the content-type, by looking at the header (first
348            * few bytes) of the file. (like the file(1) command). We could
349            * also call the "file" command through Runtime. This is an
350            * option that I almost prefer as it is already implemented and
351            * exists with an up-to-date map on most modern Unix like systems.
352            * I haven't found a really nice implementation of the magic method
353            * in pure java yet.
354            *
355            * The first method we try thought is the "Oreilly method". It
356            * relies on the content-type that the client browser sends and
357            * that sometimes is application-octet stream with
358            * broken/mis-configured browsers.
359            *
360            * The map file we use for the extensions is the standard web-app
361            * deployment descriptor file (web.xml). See Mir's web.xml or see
362            * your Servlet containers (most likely Tomcat) documentation.
363            * So if you support a new media type you have to make sure that
364            * it is in this file -mh
365            */
366           ServletContext ctx =
367             (ServletContext)MirConfig.getPropAsObject("ServletContext");
368           contentType = ctx.getMimeType(fileName);
369           if (contentType==null)
370             contentType = "text/plain"; // rfc1867 says this is the default
371         }
372         HashMap mediaValues = new HashMap();
373
374         theLog.printInfo("CONTENT TYPE IS: "+contentType);
375
376         if (contentType.equals("text/plain") ||
377             contentType.equals("application/octet-stream")) {
378           contentModule.deleteById(cid);
379           _throwBadContentType(fileName, contentType);
380         }
381
382         String mediaTitle=(String)withValues.get("media_title"+i);
383         i++;
384
385         if (mediaTitle==null)
386             mediaTitle = (String)withValues.get("title");
387
388         mediaValues.put("title", mediaTitle);
389         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
390         mediaValues.put("to_publisher", "1"); // op user
391         mediaValues.put("to_media_folder", "7"); // op media_folder
392         mediaValues.put("is_produced", "0");
393         mediaValues.put("is_published","0");
394
395         // @todo this should probably be moved to DatabaseMediaType -mh
396         String[] cTypeSplit = StringUtil.split(contentType, "/");
397         String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
398
399         DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
400         EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
401
402         String mediaTypeId = null;
403         MirMedia mediaHandler;
404         Database mediaStorage;
405 //        ProducerMedia mediaProducer;
406
407         //if we didn't find an entry matching the
408         //content-type int the table.
409         if (mediaTypesList.size() == 0) {
410           contentModule.deleteById(cid);
411           _throwBadContentType(fileName, contentType);
412         }
413
414         Entity mediaType = null;
415         Entity mediaType2 = null;
416
417         // find out if we an exact content-type match if so take it.
418         // otherwise try to match majortype/*
419         // @todo this should probably be moved to DatabaseMediaType -mh
420         for(int j=0;j<mediaTypesList.size();j++) {
421           if(contentType.equals(
422                 mediaTypesList.elementAt(j).getValue("mime_type")))
423             mediaType = mediaTypesList.elementAt(j);
424           else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
425                     cTypeSplit[0]+"/*") )
426             mediaType2= mediaTypesList.elementAt(j);
427         }
428
429         if ( (mediaType == null) && (mediaType2 == null) ) {
430           contentModule.deleteById(cid);
431           _throwBadContentType(fileName, contentType);
432         }
433         else if( (mediaType == null) && (mediaType2 != null) )
434           mediaType = mediaType2;
435
436         //get the class names from the media_type table.
437         mediaTypeId = mediaType.getId();
438         try {
439           // ############### @todo: merge these and the getURL call into one
440           // getURL helper call that just takes the Entity as a parameter
441           // along with media_type
442           mediaHandler = MediaHelper.getHandler(mediaType);
443           mediaStorage = MediaHelper.getStorage(mediaType,
444                                               "mircoders.storage.Database");
445 //          Class prodCls = Class.forName("mircoders.producer.Producer"
446 //                                            +mediaType.getValue("tablename"));
447 //          mediaProducer = (ProducerMedia)prodCls.newInstance();
448         } catch (Exception e) {
449           theLog.printError("getting media handler failed: "+e.toString());
450           contentModule.deleteById(cid);
451           throw new ServletModuleException("getting media handler failed: "
452                                           +e.toString());
453         }
454
455         mediaValues.put("to_media_type",mediaTypeId);
456
457         //load the classes via reflection
458         String MediaId;
459         Entity mediaEnt = null;
460         try {
461           mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
462           mediaEnt.setStorage(mediaStorage);
463           mediaEnt.setValues(mediaValues);
464           mediaId = mediaEnt.insert();
465
466           //save and store the media data/metadata
467           mediaHandler.set(mpReq.getMedia(), mediaEnt,
468                           mediaType);
469
470           //were done with mpReq at this point, dereference it.
471           //as it contains mucho mem. -mh 01.10.2001
472           mpReq=null;
473
474           //we got this far, associate the media to the article
475           mediaEnt.setValueForProperty("is_published","1");
476           mediaEnt.update();
477           //produce it
478 //          mediaProducer.handle(null, null, false, false, mediaId);
479           DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
480         } catch (Exception e) {
481           theLog.printError("setting media failed: "+e.toString());
482           contentModule.deleteById(cid);
483           throw new ServletModuleException("setting media failed: "
484                                             +e.toString());
485         }
486
487       } //end for Iterator...
488
489       //if we're here all is ok...
490       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
491       contentEnt.setValueForProperty("is_published","1");
492       contentEnt.update();
493
494
495       //dereference mp. -mh
496       mp=null;
497
498
499       MirGlobal.localizer().openPostings().afterContentPosting();
500     }
501     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
502     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
503     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
504
505     deliver(req, res, mergeData, postingFormDoneTemplate);
506   }
507
508   private void _throwBadContentType (String fileName, String contentType)
509     throws ServletModuleUserException {
510
511     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
512                           +contentType);
513     throw new ServletModuleUserException("The file you uploaded is of the "
514         +"following mime-type: "+contentType
515         +", we do not support this mime-type. "
516         +"Error One or more files of unrecognized type. Sorry");
517   }
518
519         protected String createOneTimePasswd(){
520                 Random r = new Random();
521                 int random = r.nextInt();
522                 long l = System.currentTimeMillis();
523                 l = (l*l*l*l)/random;
524                 if(l<0) l = l * -1;
525                 String returnString = ""+l;
526                 return returnString.substring(5);
527         }
528
529 }
530
531