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