oops call deleteForbiddenTags, deleteTable on the proper data
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.servlet;
33
34 import java.io.*;
35 import java.lang.*;
36 import java.sql.*;
37 import java.util.*;
38 import java.net.*;
39 import java.lang.reflect.*;
40 import javax.servlet.*;
41 import javax.servlet.http.*;
42
43 import freemarker.template.*;
44 import com.oreilly.servlet.multipart.*;
45 import com.oreilly.servlet.*;
46
47 import org.xml.sax.InputSource;
48 import org.xml.sax.XMLReader;
49
50 import org.apache.fop.apps.Driver;
51 import org.apache.fop.apps.Version;
52 import org.apache.fop.apps.XSLTInputHandler;
53
54 import org.apache.log.*;
55
56 import mir.servlet.*;
57 import mir.module.*;
58 import mir.misc.*;
59 import mir.entity.*;
60 import mir.storage.*;
61 import mir.media.*;
62
63 import mircoders.entity.*;
64 import mircoders.storage.*;
65 import mircoders.module.*;
66 import mircoders.producer.*;
67 import mircoders.media.MediaRequest;
68
69 /*
70  *  ServletModuleOpenIndy -
71  *   is the open-access-servlet, which is responsible for
72  *    adding comments to articles &
73  *    open-postings to the newswire
74  *
75  * @author $Author: mh $
76  * @version $Revision: 1.38.2.6 $ $Date: 2002/12/13 05:50:52 $
77  *
78  */
79
80 public class ServletModuleOpenIndy extends ServletModule
81 {
82
83   private String        commentFormTemplate, commentFormDoneTemplate,
84                         commentFormDupeTemplate;
85   private String        postingFormTemplate, postingFormDoneTemplate,
86                         postingFormDupeTemplate;
87   private ModuleContent contentModule;
88   private ModuleImages  imageModule;
89   private ModuleTopics  themenModule;
90   private String        directOp ="yes";
91   private String        passwdProtection ="yes";
92   // Singelton / Kontruktor
93   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
94   public static ServletModule getInstance() { return instance; }
95
96   private ServletModuleOpenIndy() {
97     try {
98       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
99       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
100       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
101       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
102       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
103       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
104       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
105       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
106                         passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
107       mainModule = new ModuleComment(DatabaseComment.getInstance());
108       contentModule = new ModuleContent(DatabaseContent.getInstance());
109       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
110       imageModule = new ModuleImages(DatabaseImages.getInstance());
111       defaultAction="addposting";
112                         
113     }
114     catch (StorageObjectException e) {
115         theLog.printError("servletmoduleopenindy could not be initialized");
116     }
117   }
118
119
120   /**
121    *  Method for making a comment
122    */
123
124   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
125   {
126     String aid = req.getParameter("aid"); // the article id the comment will belong to
127     if (aid!=null && !aid.equals(""))
128     {
129                         SimpleHash mergeData = new SimpleHash();
130
131                         // onetimepasswd
132                         if(passwdProtection.equals("yes")){
133                                 String passwd = this.createOneTimePasswd();
134                                 HttpSession session = req.getSession(false);
135                                 session.setAttribute("passwd",passwd);
136                                 mergeData.put("passwd", passwd);
137                         }
138                         
139       mergeData.put("aid", aid);
140       deliver(req, res, mergeData, commentFormTemplate);
141     }
142     else throw new ServletModuleException("aid not set!");
143   }
144
145   /**
146    *  Method for inserting a comment into the Database and delivering
147    *  the commentDone Page
148    */
149
150   public void inscomment(HttpServletRequest req, HttpServletResponse res)
151         throws ServletModuleException,ServletModuleUserException
152   {
153     String aid = req.getParameter("to_media"); // the article id the comment will belong to
154     if (aid!=null && !aid.equals(""))
155     {
156       // ok, collecting data from form
157       try {
158         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
159        
160         //no html in comments(for now)
161         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
162             String k=(String)i.next();
163             String v=(String)withValues.get(k);
164             
165             withValues.put(k,StringUtil.removeHTMLTags(v));
166         }
167         withValues.put("is_published","1");
168                                 
169                                 //checking the onetimepasswd
170                                 if(passwdProtection.equals("yes")){
171                                         HttpSession session = req.getSession(false);
172                                         String sessionPasswd = (String)session.getAttribute("passwd");
173                                         if ( sessionPasswd == null){
174                                                 throw new ServletModuleUserException("Lost password");
175                                         }
176                                         String passwd = req.getParameter("passwd");
177                                         if ( passwd == null || (!sessionPasswd.equals(passwd))) {
178                                                 throw new ServletModuleUserException("Missing password");
179                                         }
180                                         session.invalidate();
181                                 }
182                                 
183         // inserting into database
184         String id = mainModule.add(withValues);
185         theLog.printDebugInfo("id: "+id);
186         //insert was not successfull
187         if(id==null){
188           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
189         }
190         
191         // producing new page
192         new ProducerContent().handle(null, null, true, false, aid);
193
194         // sync the server
195         int exitValue = Helper.rsync();
196         theLog.printDebugInfo("rsync:"+exitValue);
197
198         // redirecting to url
199         // should implement back to article
200         SimpleHash mergeData = new SimpleHash();
201         deliver(req, res, mergeData, commentFormDoneTemplate);
202       }
203       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
204       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
205
206     }
207     else throw new ServletModuleException("aid not set!");
208
209   }
210
211   /**
212    *  Method for delivering the form-Page for open posting
213    */
214
215   public void addposting(HttpServletRequest req, HttpServletResponse res)
216     throws ServletModuleException {
217     SimpleHash mergeData = new SimpleHash();
218                 
219                 // onetimepasswd
220                 if(passwdProtection.equals("yes")){
221                         String passwd = this.createOneTimePasswd();
222                         HttpSession session = req.getSession(false);
223                         session.setAttribute("passwd",passwd);
224                         mergeData.put("passwd", passwd);
225                 }
226                         
227     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
228     String numOfMedia = req.getParameter("medianum");
229     if(numOfMedia==null||numOfMedia.equals("")){
230       numOfMedia="1";
231     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
232       numOfMedia = maxMedia;
233     }
234     
235     int mediaNum = Integer.parseInt(numOfMedia);
236     SimpleList mediaFields = new SimpleList();
237     for(int i =0; i<mediaNum;i++){
238       Integer mNum = new Integer(i+1);
239       mediaFields.add(mNum.toString());
240     }
241     mergeData.put("medianum",numOfMedia);
242     mergeData.put("mediafields",mediaFields);
243     
244     
245     SimpleHash extraInfo = new SimpleHash();
246     try{
247       SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
248       extraInfo.put("languagePopUpData", popUpData );
249       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
250     } catch (Exception e) {
251       theLog.printError("languagePopUpData or getTopicslist failed "
252                         +e.toString());
253       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
254     }
255       
256     deliver(req, res, mergeData, extraInfo, postingFormTemplate);
257   }
258
259   /**
260    *  Method for inserting an open posting into the Database and delivering
261    *  the postingDone Page
262    */
263
264   public void insposting(HttpServletRequest req, HttpServletResponse res)
265     throws ServletModuleException, ServletModuleUserException
266   {
267     SimpleHash mergeData = new SimpleHash();
268     boolean setMedia=false;
269                 boolean setTopic = false;
270
271     try {
272
273       WebdbMultipartRequest mp = null;
274       EntityList mediaList = null;
275       try {
276         // new MediaRequest, "1" is the id for the openPosting user
277         MediaRequest mediaReq = new MediaRequest("1", true, true);
278         mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
279         mediaList = mediaReq.getEntityList();
280       } catch (FileHandlerUserException e) {
281         throw new ServletModuleUserException(e.getMsg());
282       }
283           
284       HashMap withValues = mp.getParameters();
285                                                         
286                         //checking the onetimepasswd
287                         if(passwdProtection.equals("yes")){
288                                 HttpSession session = req.getSession(false);
289                                 String sessionPasswd = (String)session.getAttribute("passwd");
290                                 if ( sessionPasswd == null){
291                                         throw new ServletModuleUserException("Lost password");
292                                 }
293                                 String passwd = (String)withValues.get("passwd");
294                                 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
295                                         throw new ServletModuleUserException("Missing password");
296                                 }
297                                 session.invalidate();
298                         }
299
300       if ((((String)withValues.get("title")).length() == 0) ||
301           (((String)withValues.get("description")).length() == 0) ||
302           (((String)withValues.get("content_data")).length() == 0))
303             throw new ServletModuleUserException("Missing field");
304       
305       // call the routines that escape html
306
307       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
308         String k=(String)i.next();
309         String v=(String)withValues.get(k);
310         
311         if (k.equals("content_data")){
312           //this doesn't quite work yet, so for now, just delete the really
313           //bad ones.
314           //withValues.put(k,StringUtil.approveHTMLTags(v));
315           withValues.put(k,StringUtil.deleteForbiddenTags(v));
316         } else if (k.equals("description")) {
317           String tmp = StringUtil.deleteForbiddenTags(v);
318           withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
319         } else {
320           //we don't want people fucking with the author/title, etc..
321           withValues.put(k,StringUtil.removeHTMLTags(v));
322         }
323
324         
325       }
326
327       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
328       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
329       withValues.put("is_produced", "0");
330       // by default stuff is published, they can be un-published through the
331       // admin interface.
332       withValues.put("is_published","1");
333       // if op direct article-type == newswire
334       if (directOp.equals("yes")) withValues.put("to_article_type","1");
335       
336       // owner is openposting user
337       withValues.put("to_publisher","1");
338       if (withValues.get("creator").toString().equals(""))
339         withValues.put("creator","Anonym");
340
341       // inserting  content into database
342       String cid = contentModule.add(withValues);
343       theLog.printDebugInfo("id: "+cid);
344       //insert was not successfull
345       if(cid==null){
346         //How do we know that it was not succesful cause of a
347         //dupe, what if it failed cause of "No space left on device"?
348         //Or is there something I am missing? Wouldn't it be better
349         //to have an explicit dupe check and then insert? I have no
350         //idea what I am talking about. this comment is in case
351         //I forget to explicitely ask. -mh
352         deliver(req, res, mergeData, postingFormDupeTemplate);
353       }
354
355       String[] to_topicsArr = mp.getParameterValues("to_topic");
356       
357                         if (to_topicsArr != null && to_topicsArr.length > 0) {
358         try{
359           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
360           setTopic = true;
361         } catch (Exception e) {
362           theLog.printError("setting content_x_topic failed");
363           contentModule.deleteById(cid);
364           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
365         } //end try
366       } //end if
367        
368       //if we're here all is ok... associate the media to the article
369       for(int i=0;i<mediaList.size();i++) {
370         Entity mediaEnt = (Entity)mediaList.elementAt(i);
371         DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
372       }
373
374       // producing openpostinglist
375       new ProducerOpenPosting().handle(null,null,false,false);
376       // producing new page
377       new ProducerContent().handle(null, null, false, false,cid);
378       //if direct op producing startpage
379       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
380       
381                         //produce the topicPages if set
382                         //should be more intelligent
383                         //if(setTopic==true) new ProducerTopics().handle(null,null);
384                         
385       // sync the server
386       //should be configureable
387       int exitValue = Helper.rsync();
388       theLog.printDebugInfo("rsync: "+exitValue);
389
390     }
391     catch (FileHandlerException e) { throw new ServletModuleException("MediaException: "+ e.toString());}
392     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
393     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
394     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
395
396     deliver(req, res, mergeData, postingFormDoneTemplate);
397   }
398
399   /*
400    * Method for dynamically generating a pdf from a fo file
401    */
402   public void getpdf(HttpServletRequest req, HttpServletResponse res)
403     throws ServletModuleException, ServletModuleUserException {
404     String ID_REQUEST_PARAM = "id";
405     
406     String generateFO=MirConfig.getProp("GenerateFO");
407     String generatePDF=MirConfig.getProp("GeneratePDF");
408
409     //don't do anything if we are not making FO files, or if we are
410     //pregenerating PDF's
411     if (generateFO.equals("yes") && generatePDF.equals("no")){
412       //fop complains unless you do the logging this way
413       Logger log = null;
414       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
415       log = hierarchy.getLoggerFor("fop");
416       log.setPriority(Priority.WARN);
417     
418       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
419       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
420       String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
421       String xslSheet=templateDir + "/" 
422         + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
423       try {
424         String idParam = req.getParameter(ID_REQUEST_PARAM);
425         if (idParam != null) {
426           EntityContent contentEnt =
427             (EntityContent)contentModule.getById(idParam);
428           String publishPath = contentEnt.getValue("publish_path");
429           String foFile = producerStorageRoot + producerDocRoot + "/" 
430                           + publishPath + "/" + idParam + ".fo";
431           XSLTInputHandler input = new XSLTInputHandler(new File(foFile), 
432                                                        new File(xslSheet));
433           
434           ByteArrayOutputStream out = new ByteArrayOutputStream();
435           res.setContentType("application/pdf");
436
437           Driver driver = new Driver();
438           driver.setLogger(log);
439           driver.setRenderer(Driver.RENDER_PDF);
440           driver.setOutputStream(out);
441           driver.render(input.getParser(), input.getInputSource());
442
443           byte[] content = out.toByteArray();
444           res.setContentLength(content.length);
445           res.getOutputStream().write(content);
446           res.getOutputStream().flush();
447         } else {
448           throw new ServletModuleUserException("Missing id parameter.");
449         }
450       } catch (Exception ex) {
451         throw new ServletModuleException(ex.toString());
452       }
453     } else {
454       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
455     }
456   }
457   
458   private void _throwBadContentType (String fileName, String contentType)
459     throws ServletModuleUserException {
460
461     theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
462                           +contentType);
463     throw new ServletModuleUserException("The file you uploaded is of the "
464         +"following mime-type: "+contentType
465         +", we do not support this mime-type. "
466         +"Error One or more files of unrecognized type. Sorry");
467   }
468         
469         protected String createOneTimePasswd(){
470                 Random r = new Random();
471                 int random = r.nextInt();
472                 long l = System.currentTimeMillis();
473                 l = (l*l*l*l)/random;
474                 if(l<0) l = l * -1;
475                 String returnString = ""+l;
476                 return returnString.substring(5);
477         }
478       
479 }
480
481
482