1 package mircoders.servlet;
8 import java.lang.reflect.*;
9 import javax.servlet.*;
10 import javax.servlet.http.*;
12 import freemarker.template.*;
13 import com.oreilly.servlet.multipart.*;
14 import com.oreilly.servlet.*;
16 import org.xml.sax.InputSource;
17 import org.xml.sax.XMLReader;
19 import org.apache.fop.apps.Driver;
20 import org.apache.fop.apps.Version;
21 import org.apache.fop.apps.XSLTInputHandler;
23 import org.apache.log.*;
32 import mircoders.entity.*;
33 import mircoders.storage.*;
34 import mircoders.module.*;
35 import mircoders.producer.*;
38 * ServletModuleOpenIndy -
39 * is the open-access-servlet, which is responsible for
40 * adding comments to articles &
41 * open-postings to the newswire
46 public class ServletModuleOpenIndy extends ServletModule
49 private String commentFormTemplate, commentFormDoneTemplate,
50 commentFormDupeTemplate;
51 private String postingFormTemplate, postingFormDoneTemplate,
52 postingFormDupeTemplate;
53 private ModuleContent contentModule;
54 private ModuleImages imageModule;
55 private ModuleTopics themenModule;
56 private String directOp ="yes";
57 private String passwdProtection ="yes";
58 // Singelton / Kontruktor
59 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
60 public static ServletModule getInstance() { return instance; }
62 private ServletModuleOpenIndy() {
64 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
65 commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
66 commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
67 commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
68 postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
69 postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
70 postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
71 directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
72 passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
73 mainModule = new ModuleComment(DatabaseComment.getInstance());
74 contentModule = new ModuleContent(DatabaseContent.getInstance());
75 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
76 imageModule = new ModuleImages(DatabaseImages.getInstance());
77 defaultAction="addposting";
80 catch (StorageObjectException e) {
81 theLog.printError("servletmoduleopenindy could not be initialized");
87 * Method for making a comment
90 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
92 String aid = req.getParameter("aid"); // the article id the comment will belong to
93 if (aid!=null && !aid.equals(""))
95 SimpleHash mergeData = new SimpleHash();
98 if(passwdProtection.equals("yes")){
99 String passwd = this.createOneTimePasswd();
100 System.out.println(passwd);
101 HttpSession session = req.getSession(false);
102 session.setAttribute("passwd",passwd);
103 mergeData.put("passwd", passwd);
106 mergeData.put("aid", aid);
107 deliver(req, res, mergeData, commentFormTemplate);
109 else throw new ServletModuleException("aid not set!");
113 * Method for inserting a comment into the Database and delivering
114 * the commentDone Page
117 public void inscomment(HttpServletRequest req, HttpServletResponse res)
118 throws ServletModuleException,ServletModuleUserException
120 String aid = req.getParameter("to_media"); // the article id the comment will belong to
121 if (aid!=null && !aid.equals(""))
123 // ok, collecting data from form
125 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
127 //no html in comments(for now)
128 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
129 String k=(String)i.next();
130 String v=(String)withValues.get(k);
132 withValues.put(k,StringUtil.removeHTMLTags(v));
134 withValues.put("is_published","1");
136 //checking the onetimepasswd
137 if(passwdProtection.equals("yes")){
138 HttpSession session = req.getSession(false);
139 String sessionPasswd = (String)session.getAttribute("passwd");
140 if ( sessionPasswd == null){
141 throw new ServletModuleUserException("Lost password");
143 String passwd = req.getParameter("passwd");
144 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
145 throw new ServletModuleUserException("Missing password");
147 session.invalidate();
150 // inserting into database
151 String id = mainModule.add(withValues);
152 theLog.printDebugInfo("id: "+id);
153 //insert was not successfull
155 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
158 // producing new page
159 new ProducerContent().handle(null, null, true, false, aid);
162 int exitValue = Helper.rsync();
163 theLog.printDebugInfo("rsync:"+exitValue);
165 // redirecting to url
166 // should implement back to article
167 SimpleHash mergeData = new SimpleHash();
168 deliver(req, res, mergeData, commentFormDoneTemplate);
170 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
171 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
174 else throw new ServletModuleException("aid not set!");
179 * Method for delivering the form-Page for open posting
182 public void addposting(HttpServletRequest req, HttpServletResponse res)
183 throws ServletModuleException {
184 SimpleHash mergeData = new SimpleHash();
187 if(passwdProtection.equals("yes")){
188 String passwd = this.createOneTimePasswd();
189 System.out.println(passwd);
190 HttpSession session = req.getSession(false);
191 session.setAttribute("passwd",passwd);
192 mergeData.put("passwd", passwd);
195 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
196 String numOfMedia = req.getParameter("medianum");
197 if(numOfMedia==null||numOfMedia.equals("")){
199 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
200 numOfMedia = maxMedia;
203 int mediaNum = Integer.parseInt(numOfMedia);
204 SimpleList mediaFields = new SimpleList();
205 for(int i =0; i<mediaNum;i++){
206 Integer mNum = new Integer(i+1);
207 mediaFields.add(mNum.toString());
209 mergeData.put("medianum",numOfMedia);
210 mergeData.put("mediafields",mediaFields);
213 SimpleHash extraInfo = new SimpleHash();
215 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
216 extraInfo.put("languagePopUpData", popUpData );
217 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
218 } catch (Exception e) {
219 theLog.printError("languagePopUpData or getTopicslist failed "
221 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
224 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
228 * Method for inserting an open posting into the Database and delivering
229 * the postingDone Page
232 public void insposting(HttpServletRequest req, HttpServletResponse res)
233 throws ServletModuleException, ServletModuleUserException
235 SimpleHash mergeData = new SimpleHash();
236 boolean setMedia=false;
237 boolean setTopic = false;
240 WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
242 HashMap withValues = mp.getParameters();
244 //checking the onetimepasswd
245 if(passwdProtection.equals("yes")){
246 HttpSession session = req.getSession(false);
247 String sessionPasswd = (String)session.getAttribute("passwd");
248 if ( sessionPasswd == null){
249 throw new ServletModuleUserException("Lost password");
251 String passwd = (String)withValues.get("passwd");
252 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
253 throw new ServletModuleUserException("Missing password");
255 session.invalidate();
258 if ((((String)withValues.get("title")).length() == 0) ||
259 (((String)withValues.get("description")).length() == 0) ||
260 (((String)withValues.get("content_data")).length() == 0))
261 throw new ServletModuleUserException("Missing field");
263 // call the routines that escape html
265 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
266 String k=(String)i.next();
267 String v=(String)withValues.get(k);
269 if (k.equals("content_data")){
270 //this doesn't quite work yet, so for now, all html goes
271 //withValues.put(k,StringUtil.approveHTMLTags(v));
272 //withValues.put(k,StringUtil.removeHTMLTags(v));
274 withValues.put(k,StringUtil.removeHTMLTags(v));
279 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
280 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
281 withValues.put("is_produced", "0");
282 // op-articles are not immediatly published
283 // we don't know that all is good yet (media, title is present, etc..)
284 withValues.put("is_published","0");
285 // if op direct article-type == newswire
286 if (directOp.equals("yes")) withValues.put("to_article_type","1");
288 // owner is openposting user
289 withValues.put("to_publisher","1");
290 if (withValues.get("creator").toString().equals(""))
291 withValues.put("creator","Anonym");
293 // inserting content into database
294 String cid = contentModule.add(withValues);
295 theLog.printDebugInfo("id: "+cid);
296 //insert was not successfull
298 //How do we know that it was not succesful cause of a
299 //dupe, what if it failed cause of "No space left on device"?
300 //Or is there something I am missing? Wouldn't it be better
301 //to have an explicit dupe check and then insert? I have no
302 //idea what I am talking about. this comment is in case
303 //I forget to explicitely ask. -mh
304 deliver(req, res, mergeData, postingFormDupeTemplate);
307 String[] to_topicsArr = mp.getParameterValues("to_topic");
309 if (to_topicsArr != null && to_topicsArr.length > 0) {
311 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
313 } catch (Exception e) {
314 theLog.printError("setting content_x_topic failed");
315 contentModule.deleteById(cid);
316 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
320 // if op contains uploaddata
323 for(Iterator it = mp.requestList.iterator(); it.hasNext();){
324 MpRequest mpReq = (MpRequest)it.next();
325 String fileName = mpReq.getFilename();
327 //get the content-type from what the client browser
328 //sends us. (the "Oreilly method")
329 String contentType = mpReq.getContentType();
331 theLog.printInfo("FROM BROWSER: "+contentType);
333 //if the client browser sent us unknown (text/plain is default)
334 //or if we got application/octet-stream, it's possible that
335 //the browser is in error, better check against the file extension
336 if (contentType.equals("text/plain") ||
337 contentType.equals("application/octet-stream")) {
339 * Fallback to finding the mime-type through the standard ServletApi
340 * ServletContext getMimeType() method.
342 * This is a way to get the content-type via the .extension,
343 * we could maybe use a magic method as an additional method of
344 * figuring out the content-type, by looking at the header (first
345 * few bytes) of the file. (like the file(1) command). We could
346 * also call the "file" command through Runtime. This is an
347 * option that I almost prefer as it is already implemented and
348 * exists with an up-to-date map on most modern Unix like systems.
349 * I haven't found a really nice implementation of the magic method
352 * The first method we try thought is the "Oreilly method". It
353 * relies on the content-type that the client browser sends and
354 * that sometimes is application-octet stream with
355 * broken/mis-configured browsers.
357 * The map file we use for the extensions is the standard web-app
358 * deployment descriptor file (web.xml). See Mir's web.xml or see
359 * your Servlet containers (most likely Tomcat) documentation.
360 * So if you support a new media type you have to make sure that
361 * it is in this file -mh
364 (ServletContext)MirConfig.getPropAsObject("ServletContext");
365 contentType = ctx.getMimeType(fileName);
366 if (contentType==null)
367 contentType = "text/plain"; // rfc1867 says this is the default
369 HashMap mediaValues = new HashMap();
371 theLog.printInfo("CONTENT TYPE IS: "+contentType);
373 if (contentType.equals("text/plain") ||
374 contentType.equals("application/octet-stream")) {
375 contentModule.deleteById(cid);
376 _throwBadContentType(fileName, contentType);
379 String mediaTitle=(String)withValues.get("media_title"+i);
382 if ((mediaTitle == null) || (mediaTitle.length() == 0))
383 throw new ServletModuleUserException("Missing field");
384 //mediaTitle = (String)withValues.get("title");
386 mediaValues.put("title", mediaTitle);
387 mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
388 mediaValues.put("to_publisher", "1"); // op user
389 mediaValues.put("to_media_folder", "7"); // op media_folder
390 mediaValues.put("is_produced", "0");
391 mediaValues.put("is_published","0");
393 // @todo this should probably be moved to DatabaseMediaType -mh
394 String[] cTypeSplit = StringUtil.split(contentType, "/");
395 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
397 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
398 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
400 String mediaTypeId = null;
401 MirMedia mediaHandler;
402 Database mediaStorage;
403 ProducerMedia mediaProducer;
405 //if we didn't find an entry matching the
406 //content-type int the table.
407 if (mediaTypesList.size() == 0) {
408 contentModule.deleteById(cid);
409 _throwBadContentType(fileName, contentType);
412 Entity mediaType = null;
413 Entity mediaType2 = null;
415 // find out if we an exact content-type match if so take it.
416 // otherwise try to match majortype/*
417 // @todo this should probably be moved to DatabaseMediaType -mh
418 for(int j=0;j<mediaTypesList.size();j++) {
419 if(contentType.equals(
420 mediaTypesList.elementAt(j).getValue("mime_type")))
421 mediaType = mediaTypesList.elementAt(j);
422 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
423 cTypeSplit[0]+"/*") )
424 mediaType2= mediaTypesList.elementAt(j);
427 if ( (mediaType == null) && (mediaType2 == null) ) {
428 contentModule.deleteById(cid);
429 _throwBadContentType(fileName, contentType);
431 else if( (mediaType == null) && (mediaType2 != null) )
432 mediaType = mediaType2;
434 //get the class names from the media_type table.
435 mediaTypeId = mediaType.getId();
437 // ############### @todo: merge these and the getURL call into one
438 // getURL helper call that just takes the Entity as a parameter
439 // along with media_type
440 mediaHandler = MediaHelper.getHandler(mediaType);
441 mediaStorage = MediaHelper.getStorage(mediaType,
442 "mircoders.storage.Database");
443 Class prodCls = Class.forName("mircoders.producer.Producer"
444 +mediaType.getValue("tablename"));
445 mediaProducer = (ProducerMedia)prodCls.newInstance();
446 } catch (Exception e) {
447 theLog.printError("getting media handler failed: "+e.toString());
448 contentModule.deleteById(cid);
449 throw new ServletModuleException("getting media handler failed: "
453 mediaValues.put("to_media_type",mediaTypeId);
455 //load the classes via reflection
457 Entity mediaEnt = null;
459 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
460 mediaEnt.setStorage(mediaStorage);
461 mediaEnt.setValues(mediaValues);
462 mediaId = mediaEnt.insert();
464 //save and store the media data/metadata
465 mediaHandler.set(mpReq.getMedia(), mediaEnt,
468 //were done with mpReq at this point, dereference it.
469 //as it contains mucho mem. -mh 01.10.2001
472 //we got this far, associate the media to the article
473 mediaEnt.setValueForProperty("is_published","1");
476 mediaProducer.handle(null, null, false, false, mediaId);
477 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
478 } catch (Exception e) {
479 theLog.printError("setting media failed: "+e.toString());
480 contentModule.deleteById(cid);
481 throw new ServletModuleException("setting media failed: "
485 } //end for Iterator...
487 //if we're here all is ok...
488 EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
489 contentEnt.setValueForProperty("is_published","1");
493 //dereference mp. -mh
496 // producing openpostinglist
497 new ProducerOpenPosting().handle(null,null,false,false);
498 // producing new page
499 new ProducerContent().handle(null, null, false, false,cid);
500 //if direct op producing startpage
501 if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
503 //produce the topicPages if set
504 //should be more intelligent
505 //if(setTopic==true) new ProducerTopics().handle(null,null);
508 //should be configureable
509 int exitValue = Helper.rsync();
510 theLog.printDebugInfo("rsync: "+exitValue);
513 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
514 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
515 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
517 deliver(req, res, mergeData, postingFormDoneTemplate);
521 * Method for dynamically generating a pdf from a fo file
525 public void getpdf(HttpServletRequest req, HttpServletResponse res)
526 throws ServletModuleException, ServletModuleUserException {
527 String ID_REQUEST_PARAM = "id";
529 String generateFO=MirConfig.getProp("GenerateFO");
530 String generatePDF=MirConfig.getProp("GeneratePDF");
532 //don't do anything if we are not making FO files, or if we are pregenerating PDF's
533 if (generateFO.equals("yes") && generatePDF.equals("no")){
535 //fop complains unless you do the logging this way
537 Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
538 log = hierarchy.getLoggerFor("fop");
539 log.setPriority(Priority.WARN);
541 String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
542 String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
543 String templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
544 String xslSheet=templateDir + "/"
545 + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");
547 String idParam = req.getParameter(ID_REQUEST_PARAM);
548 if (idParam != null){
549 EntityContent contentEnt = (EntityContent)contentModule.getById(idParam);
550 String publishPath = contentEnt.getValue("publish_path");
551 String foFile = producerStorageRoot + producerDocRoot + "/"
552 + publishPath + "/" + idParam + ".fo";
553 XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
556 ByteArrayOutputStream out = new ByteArrayOutputStream();
557 res.setContentType("application/pdf");
559 Driver driver = new Driver();
560 driver.setLogger(log);
561 driver.setRenderer(Driver.RENDER_PDF);
562 driver.setOutputStream(out);
563 driver.render(input.getParser(), input.getInputSource());
565 byte[] content = out.toByteArray();
566 res.setContentLength(content.length);
567 res.getOutputStream().write(content);
568 res.getOutputStream().flush();
571 throw new ServletModuleUserException("Can't generate a PDF without an id parameter.");
574 catch (Exception ex) {
575 throw new ServletModuleException(ex.toString());
579 throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
583 private void _throwBadContentType (String fileName, String contentType)
584 throws ServletModuleUserException {
586 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
588 throw new ServletModuleUserException("The file you uploaded is of the "
589 +"following mime-type: "+contentType
590 +", we do not support this mime-type. "
591 +"Error One or more files of unrecognized type. Sorry");
594 protected String createOneTimePasswd(){
595 Random r = new Random();
596 int random = r.nextInt();
597 long l = System.currentTimeMillis();
598 l = (l*l*l*l)/random;
600 String returnString = ""+l;
601 return returnString.substring(5);