2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
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.
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.
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
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.
32 package mircoders.servlet;
39 import java.lang.reflect.*;
40 import javax.servlet.*;
41 import javax.servlet.http.*;
43 import freemarker.template.*;
44 import com.oreilly.servlet.multipart.*;
45 import com.oreilly.servlet.*;
47 import org.xml.sax.InputSource;
48 import org.xml.sax.XMLReader;
50 import org.apache.fop.apps.Driver;
51 import org.apache.fop.apps.Version;
52 import org.apache.fop.apps.XSLTInputHandler;
54 import org.apache.log.*;
63 import mircoders.entity.*;
64 import mircoders.storage.*;
65 import mircoders.module.*;
66 import mircoders.producer.*;
67 import mircoders.media.MediaRequest;
70 * ServletModuleOpenIndy -
71 * is the open-access-servlet, which is responsible for
72 * adding comments to articles &
73 * open-postings to the newswire
75 * @author $Author: mh $
76 * @version $Revision: 1.38.2.6 $ $Date: 2002/12/13 05:50:52 $
80 public class ServletModuleOpenIndy extends ServletModule
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; }
96 private ServletModuleOpenIndy() {
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";
114 catch (StorageObjectException e) {
115 theLog.printError("servletmoduleopenindy could not be initialized");
121 * Method for making a comment
124 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
126 String aid = req.getParameter("aid"); // the article id the comment will belong to
127 if (aid!=null && !aid.equals(""))
129 SimpleHash mergeData = new SimpleHash();
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);
139 mergeData.put("aid", aid);
140 deliver(req, res, mergeData, commentFormTemplate);
142 else throw new ServletModuleException("aid not set!");
146 * Method for inserting a comment into the Database and delivering
147 * the commentDone Page
150 public void inscomment(HttpServletRequest req, HttpServletResponse res)
151 throws ServletModuleException,ServletModuleUserException
153 String aid = req.getParameter("to_media"); // the article id the comment will belong to
154 if (aid!=null && !aid.equals(""))
156 // ok, collecting data from form
158 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
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);
165 withValues.put(k,StringUtil.removeHTMLTags(v));
167 withValues.put("is_published","1");
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");
176 String passwd = req.getParameter("passwd");
177 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
178 throw new ServletModuleUserException("Missing password");
180 session.invalidate();
183 // inserting into database
184 String id = mainModule.add(withValues);
185 theLog.printDebugInfo("id: "+id);
186 //insert was not successfull
188 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
191 // producing new page
192 new ProducerContent().handle(null, null, true, false, aid);
195 int exitValue = Helper.rsync();
196 theLog.printDebugInfo("rsync:"+exitValue);
198 // redirecting to url
199 // should implement back to article
200 SimpleHash mergeData = new SimpleHash();
201 deliver(req, res, mergeData, commentFormDoneTemplate);
203 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
204 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
207 else throw new ServletModuleException("aid not set!");
212 * Method for delivering the form-Page for open posting
215 public void addposting(HttpServletRequest req, HttpServletResponse res)
216 throws ServletModuleException {
217 SimpleHash mergeData = new SimpleHash();
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);
227 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
228 String numOfMedia = req.getParameter("medianum");
229 if(numOfMedia==null||numOfMedia.equals("")){
231 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
232 numOfMedia = maxMedia;
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());
241 mergeData.put("medianum",numOfMedia);
242 mergeData.put("mediafields",mediaFields);
245 SimpleHash extraInfo = new SimpleHash();
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 "
253 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
256 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
260 * Method for inserting an open posting into the Database and delivering
261 * the postingDone Page
264 public void insposting(HttpServletRequest req, HttpServletResponse res)
265 throws ServletModuleException, ServletModuleUserException
267 SimpleHash mergeData = new SimpleHash();
268 boolean setMedia=false;
269 boolean setTopic = false;
273 WebdbMultipartRequest mp = null;
274 EntityList mediaList = null;
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());
284 HashMap withValues = mp.getParameters();
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");
293 String passwd = (String)withValues.get("passwd");
294 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
295 throw new ServletModuleUserException("Missing password");
297 session.invalidate();
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");
305 // call the routines that escape html
307 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
308 String k=(String)i.next();
309 String v=(String)withValues.get(k);
311 if (k.equals("content_data")){
312 //this doesn't quite work yet, so for now, just delete the really
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));
320 //we don't want people fucking with the author/title, etc..
321 withValues.put(k,StringUtil.removeHTMLTags(v));
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
332 withValues.put("is_published","1");
333 // if op direct article-type == newswire
334 if (directOp.equals("yes")) withValues.put("to_article_type","1");
336 // owner is openposting user
337 withValues.put("to_publisher","1");
338 if (withValues.get("creator").toString().equals(""))
339 withValues.put("creator","Anonym");
341 // inserting content into database
342 String cid = contentModule.add(withValues);
343 theLog.printDebugInfo("id: "+cid);
344 //insert was not successfull
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);
355 String[] to_topicsArr = mp.getParameterValues("to_topic");
357 if (to_topicsArr != null && to_topicsArr.length > 0) {
359 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
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());
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());
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);
381 //produce the topicPages if set
382 //should be more intelligent
383 //if(setTopic==true) new ProducerTopics().handle(null,null);
386 //should be configureable
387 int exitValue = Helper.rsync();
388 theLog.printDebugInfo("rsync: "+exitValue);
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());}
396 deliver(req, res, mergeData, postingFormDoneTemplate);
400 * Method for dynamically generating a pdf from a fo file
402 public void getpdf(HttpServletRequest req, HttpServletResponse res)
403 throws ServletModuleException, ServletModuleUserException {
404 String ID_REQUEST_PARAM = "id";
406 String generateFO=MirConfig.getProp("GenerateFO");
407 String generatePDF=MirConfig.getProp("GeneratePDF");
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
414 Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
415 log = hierarchy.getLoggerFor("fop");
416 log.setPriority(Priority.WARN);
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");
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),
434 ByteArrayOutputStream out = new ByteArrayOutputStream();
435 res.setContentType("application/pdf");
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());
443 byte[] content = out.toByteArray();
444 res.setContentLength(content.length);
445 res.getOutputStream().write(content);
446 res.getOutputStream().flush();
448 throw new ServletModuleUserException("Missing id parameter.");
450 } catch (Exception ex) {
451 throw new ServletModuleException(ex.toString());
454 throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
458 private void _throwBadContentType (String fileName, String contentType)
459 throws ServletModuleUserException {
461 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
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");
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;
475 String returnString = ""+l;
476 return returnString.substring(5);