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.3 $ $Date: 2002/11/26 01:52:55 $
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 System.out.println(passwd);
135 HttpSession session = req.getSession(false);
136 session.setAttribute("passwd",passwd);
137 mergeData.put("passwd", passwd);
140 mergeData.put("aid", aid);
141 deliver(req, res, mergeData, commentFormTemplate);
143 else throw new ServletModuleException("aid not set!");
147 * Method for inserting a comment into the Database and delivering
148 * the commentDone Page
151 public void inscomment(HttpServletRequest req, HttpServletResponse res)
152 throws ServletModuleException,ServletModuleUserException
154 String aid = req.getParameter("to_media"); // the article id the comment will belong to
155 if (aid!=null && !aid.equals(""))
157 // ok, collecting data from form
159 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
161 //no html in comments(for now)
162 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
163 String k=(String)i.next();
164 String v=(String)withValues.get(k);
166 withValues.put(k,StringUtil.removeHTMLTags(v));
168 withValues.put("is_published","1");
170 //checking the onetimepasswd
171 if(passwdProtection.equals("yes")){
172 HttpSession session = req.getSession(false);
173 String sessionPasswd = (String)session.getAttribute("passwd");
174 if ( sessionPasswd == null){
175 throw new ServletModuleUserException("Lost password");
177 String passwd = req.getParameter("passwd");
178 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
179 throw new ServletModuleUserException("Missing password");
181 session.invalidate();
184 // inserting into database
185 String id = mainModule.add(withValues);
186 theLog.printDebugInfo("id: "+id);
187 //insert was not successfull
189 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
192 // producing new page
193 new ProducerContent().handle(null, null, true, false, aid);
196 int exitValue = Helper.rsync();
197 theLog.printDebugInfo("rsync:"+exitValue);
199 // redirecting to url
200 // should implement back to article
201 SimpleHash mergeData = new SimpleHash();
202 deliver(req, res, mergeData, commentFormDoneTemplate);
204 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
205 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
208 else throw new ServletModuleException("aid not set!");
213 * Method for delivering the form-Page for open posting
216 public void addposting(HttpServletRequest req, HttpServletResponse res)
217 throws ServletModuleException {
218 SimpleHash mergeData = new SimpleHash();
221 if(passwdProtection.equals("yes")){
222 String passwd = this.createOneTimePasswd();
223 System.out.println(passwd);
224 HttpSession session = req.getSession(false);
225 session.setAttribute("passwd",passwd);
226 mergeData.put("passwd", passwd);
229 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
230 String numOfMedia = req.getParameter("medianum");
231 if(numOfMedia==null||numOfMedia.equals("")){
233 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
234 numOfMedia = maxMedia;
237 int mediaNum = Integer.parseInt(numOfMedia);
238 SimpleList mediaFields = new SimpleList();
239 for(int i =0; i<mediaNum;i++){
240 Integer mNum = new Integer(i+1);
241 mediaFields.add(mNum.toString());
243 mergeData.put("medianum",numOfMedia);
244 mergeData.put("mediafields",mediaFields);
247 SimpleHash extraInfo = new SimpleHash();
249 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
250 extraInfo.put("languagePopUpData", popUpData );
251 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
252 } catch (Exception e) {
253 theLog.printError("languagePopUpData or getTopicslist failed "
255 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
258 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
262 * Method for inserting an open posting into the Database and delivering
263 * the postingDone Page
266 public void insposting(HttpServletRequest req, HttpServletResponse res)
267 throws ServletModuleException, ServletModuleUserException
269 SimpleHash mergeData = new SimpleHash();
270 boolean setMedia=false;
271 boolean setTopic = false;
275 WebdbMultipartRequest mp = null;
276 EntityList mediaList = null;
278 // new MediaRequest, "1" is the id for the openPosting user
279 MediaRequest mediaReq = new MediaRequest("1", true, true);
280 mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
281 mediaList = mediaReq.getEntityList();
282 } catch (FileHandlerUserException e) {
283 throw new ServletModuleUserException(e.getMsg());
286 HashMap withValues = mp.getParameters();
288 //checking the onetimepasswd
289 if(passwdProtection.equals("yes")){
290 HttpSession session = req.getSession(false);
291 String sessionPasswd = (String)session.getAttribute("passwd");
292 if ( sessionPasswd == null){
293 throw new ServletModuleUserException("Lost password");
295 String passwd = (String)withValues.get("passwd");
296 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
297 throw new ServletModuleUserException("Missing password");
299 session.invalidate();
302 if ((((String)withValues.get("title")).length() == 0) ||
303 (((String)withValues.get("description")).length() == 0) ||
304 (((String)withValues.get("content_data")).length() == 0))
305 throw new ServletModuleUserException("Missing field");
307 // call the routines that escape html
309 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
310 String k=(String)i.next();
311 String v=(String)withValues.get(k);
313 if (k.equals("content_data")){
314 //this doesn't quite work yet, so for now, all html goes
315 //withValues.put(k,StringUtil.approveHTMLTags(v));
316 //withValues.put(k,StringUtil.removeHTMLTags(v));
318 withValues.put(k,StringUtil.removeHTMLTags(v));
323 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
324 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
325 withValues.put("is_produced", "0");
326 // by default stuff is published, they can be un-published through the
328 withValues.put("is_published","1");
329 // if op direct article-type == newswire
330 if (directOp.equals("yes")) withValues.put("to_article_type","1");
332 // owner is openposting user
333 withValues.put("to_publisher","1");
334 if (withValues.get("creator").toString().equals(""))
335 withValues.put("creator","Anonym");
337 // inserting content into database
338 String cid = contentModule.add(withValues);
339 theLog.printDebugInfo("id: "+cid);
340 //insert was not successfull
342 //How do we know that it was not succesful cause of a
343 //dupe, what if it failed cause of "No space left on device"?
344 //Or is there something I am missing? Wouldn't it be better
345 //to have an explicit dupe check and then insert? I have no
346 //idea what I am talking about. this comment is in case
347 //I forget to explicitely ask. -mh
348 deliver(req, res, mergeData, postingFormDupeTemplate);
351 String[] to_topicsArr = mp.getParameterValues("to_topic");
353 if (to_topicsArr != null && to_topicsArr.length > 0) {
355 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
357 } catch (Exception e) {
358 theLog.printError("setting content_x_topic failed");
359 contentModule.deleteById(cid);
360 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
364 //if we're here all is ok... associate the media to the article
365 for(int i=0;i<mediaList.size();i++) {
366 Entity mediaEnt = (Entity)mediaList.elementAt(i);
367 DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
370 // producing openpostinglist
371 new ProducerOpenPosting().handle(null,null,false,false);
372 // producing new page
373 new ProducerContent().handle(null, null, false, false,cid);
374 //if direct op producing startpage
375 if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
377 //produce the topicPages if set
378 //should be more intelligent
379 //if(setTopic==true) new ProducerTopics().handle(null,null);
382 //should be configureable
383 int exitValue = Helper.rsync();
384 theLog.printDebugInfo("rsync: "+exitValue);
387 catch (FileHandlerException e) { throw new ServletModuleException("MediaException: "+ e.toString());}
388 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
389 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
390 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
392 deliver(req, res, mergeData, postingFormDoneTemplate);
396 * Method for dynamically generating a pdf from a fo file
398 public void getpdf(HttpServletRequest req, HttpServletResponse res)
399 throws ServletModuleException, ServletModuleUserException {
400 String ID_REQUEST_PARAM = "id";
402 String generateFO=MirConfig.getProp("GenerateFO");
403 String generatePDF=MirConfig.getProp("GeneratePDF");
405 //don't do anything if we are not making FO files, or if we are
406 //pregenerating PDF's
407 if (generateFO.equals("yes") && generatePDF.equals("no")){
408 //fop complains unless you do the logging this way
410 Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
411 log = hierarchy.getLoggerFor("fop");
412 log.setPriority(Priority.WARN);
414 String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
415 String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
416 String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
417 String xslSheet=templateDir + "/"
418 + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
420 String idParam = req.getParameter(ID_REQUEST_PARAM);
421 if (idParam != null) {
422 EntityContent contentEnt =
423 (EntityContent)contentModule.getById(idParam);
424 String publishPath = contentEnt.getValue("publish_path");
425 String foFile = producerStorageRoot + producerDocRoot + "/"
426 + publishPath + "/" + idParam + ".fo";
427 XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
430 ByteArrayOutputStream out = new ByteArrayOutputStream();
431 res.setContentType("application/pdf");
433 Driver driver = new Driver();
434 driver.setLogger(log);
435 driver.setRenderer(Driver.RENDER_PDF);
436 driver.setOutputStream(out);
437 driver.render(input.getParser(), input.getInputSource());
439 byte[] content = out.toByteArray();
440 res.setContentLength(content.length);
441 res.getOutputStream().write(content);
442 res.getOutputStream().flush();
444 throw new ServletModuleUserException("Missing id parameter.");
446 } catch (Exception ex) {
447 throw new ServletModuleException(ex.toString());
450 throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
454 private void _throwBadContentType (String fileName, String contentType)
455 throws ServletModuleUserException {
457 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
459 throw new ServletModuleUserException("The file you uploaded is of the "
460 +"following mime-type: "+contentType
461 +", we do not support this mime-type. "
462 +"Error One or more files of unrecognized type. Sorry");
465 protected String createOneTimePasswd(){
466 Random r = new Random();
467 int random = r.nextInt();
468 long l = System.currentTimeMillis();
469 l = (l*l*l*l)/random;
471 String returnString = ""+l;
472 return returnString.substring(5);