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