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.*;
23 import mircoders.entity.*;
24 import mircoders.storage.*;
25 import mircoders.module.*;
26 import mircoders.producer.*;
27 import mircoders.global.*;
28 import mircoders.localizer.*;
31 * ServletModuleOpenIndy -
32 * is the open-access-servlet, which is responsible for
33 * adding comments to articles &
34 * open-postings to the newswire
39 public class ServletModuleOpenIndy extends ServletModule
42 private String commentFormTemplate, commentFormDoneTemplate,
43 commentFormDupeTemplate;
44 private String postingFormTemplate, postingFormDoneTemplate,
45 postingFormDupeTemplate;
46 private ModuleContent contentModule;
47 private ModuleComment commentModule;
48 private ModuleImages imageModule;
49 private ModuleTopics themenModule;
50 private String directOp ="yes";
51 private String passwdProtection ="yes";
52 // Singelton / Kontruktor
53 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
54 public static ServletModule getInstance() { return instance; }
56 private ServletModuleOpenIndy() {
58 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
59 commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
60 commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
61 commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
62 postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
63 postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
64 postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
65 directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
66 passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
67 mainModule = new ModuleComment(DatabaseComment.getInstance());
68 contentModule = new ModuleContent(DatabaseContent.getInstance());
69 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
70 imageModule = new ModuleImages(DatabaseImages.getInstance());
71 defaultAction="addposting";
74 catch (StorageObjectException e) {
75 theLog.printError("servletmoduleopenindy could not be initialized");
81 * Method for making a comment
84 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
86 String aid = req.getParameter("aid"); // the article id the comment will belong to
87 String language = req.getParameter("language");
89 if (aid!=null && !aid.equals(""))
91 SimpleHash mergeData = new SimpleHash();
94 if(passwdProtection.equals("yes")){
95 String passwd = this.createOneTimePasswd();
96 System.out.println(passwd);
97 HttpSession session = req.getSession(false);
98 session.setAttribute("passwd",passwd);
99 mergeData.put("passwd", passwd);
102 if (language!=null) {
103 HttpSession session = req.getSession(false);
104 session.setAttribute("Locale", new Locale(language, ""));
105 session.setAttribute("passwd",language);
108 mergeData.put("aid", aid);
109 deliver(req, res, mergeData, commentFormTemplate);
111 else throw new ServletModuleException("aid not set!");
115 * Method for inserting a comment into the Database and delivering
116 * the commentDone Page
119 public void inscomment(HttpServletRequest req, HttpServletResponse res)
120 throws ServletModuleException,ServletModuleUserException
122 String aid = req.getParameter("to_media"); // the article id the comment will belong to
123 if (aid!=null && !aid.equals(""))
125 // ok, collecting data from form
127 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
129 //no html in comments(for now)
130 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
131 String k=(String)i.next();
132 String v=(String)withValues.get(k);
134 withValues.put(k,StringUtil.removeHTMLTags(v));
136 withValues.put("is_published","1");
138 //checking the onetimepasswd
139 if(passwdProtection.equals("yes")){
140 HttpSession session = req.getSession(false);
141 String sessionPasswd = (String)session.getAttribute("passwd");
142 if ( sessionPasswd == null){
143 throw new ServletModuleUserException("Lost password");
145 String passwd = req.getParameter("passwd");
146 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
147 throw new ServletModuleUserException("Missing password");
149 session.invalidate();
152 // inserting into database
153 String id = mainModule.add(withValues);
154 theLog.printDebugInfo("id: "+id);
155 //insert was not successfull
157 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
160 DatabaseContent.getInstance().setUnproduced("id="+aid);
162 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
164 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
168 // redirecting to url
169 // should implement back to article
170 SimpleHash mergeData = new SimpleHash();
171 deliver(req, res, mergeData, commentFormDoneTemplate);
173 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
174 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
177 else throw new ServletModuleException("aid not set!");
182 * Method for delivering the form-Page for open posting
185 public void addposting(HttpServletRequest req, HttpServletResponse res)
186 throws ServletModuleException {
187 SimpleHash mergeData = new SimpleHash();
190 if(passwdProtection.equals("yes")){
191 String passwd = this.createOneTimePasswd();
192 System.out.println(passwd);
193 HttpSession session = req.getSession(false);
194 session.setAttribute("passwd",passwd);
195 mergeData.put("passwd", passwd);
198 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
199 String numOfMedia = req.getParameter("medianum");
200 if(numOfMedia==null||numOfMedia.equals("")){
202 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
203 numOfMedia = maxMedia;
206 int mediaNum = Integer.parseInt(numOfMedia);
207 SimpleList mediaFields = new SimpleList();
208 for(int i =0; i<mediaNum;i++){
209 Integer mNum = new Integer(i+1);
210 mediaFields.add(mNum.toString());
212 mergeData.put("medianum",numOfMedia);
213 mergeData.put("mediafields",mediaFields);
216 SimpleHash extraInfo = new SimpleHash();
218 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
219 extraInfo.put("languagePopUpData", popUpData );
220 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
222 // ML: Bolivia specific, will move it towards localization
223 extraInfo.put("topics", themenModule.getTopicsList());
224 String defaultCity = req.getParameter("city");
225 if(defaultCity!=null && !defaultCity.equals("")){
226 extraInfo.put("city", defaultCity);
229 } catch (Exception e) {
230 theLog.printError("languagePopUpData or getTopicslist failed "
232 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
237 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
241 * Method for inserting an open posting into the Database and delivering
242 * the postingDone Page
245 public void insposting(HttpServletRequest req, HttpServletResponse res)
246 throws ServletModuleException, ServletModuleUserException
248 SimpleHash mergeData = new SimpleHash();
249 boolean setMedia=false;
250 boolean setTopic = false;
253 WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
255 HashMap withValues = mp.getParameters();
257 //checking the onetimepasswd
258 if(passwdProtection.equals("yes")){
259 HttpSession session = req.getSession(false);
260 String sessionPasswd = (String)session.getAttribute("passwd");
261 if ( sessionPasswd == null){
262 throw new ServletModuleUserException("Lost password");
264 String passwd = (String)withValues.get("passwd");
265 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
266 throw new ServletModuleUserException("Missing password");
268 session.invalidate();
271 if ((((String)withValues.get("title")).length() == 0) ||
272 (((String)withValues.get("description")).length() == 0) ||
273 (((String)withValues.get("content_data")).length() == 0))
274 throw new ServletModuleUserException("Missing field");
276 // call the routines that escape html
278 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
279 String k=(String)i.next();
280 String v=(String)withValues.get(k);
282 if (k.equals("content_data")){
283 //this doesn't quite work yet, so for now, all html goes
284 //withValues.put(k,StringUtil.approveHTMLTags(v));
285 //withValues.put(k,StringUtil.removeHTMLTags(v));
287 withValues.put(k,StringUtil.removeHTMLTags(v));
292 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
293 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
294 withValues.put("is_produced", "0");
295 // op-articles are not immediatly published
296 // we don't know that all is good yet (media, title is present, etc..)
297 withValues.put("is_published","0");
298 // if op direct article-type == newswire
299 if (directOp.equals("yes")) withValues.put("to_article_type","1");
301 withValues.put("to_publisher","1");
303 // owner is openposting user
304 // ML: this is not multi-language friendly and this can be done in a template
305 // if (withValues.get("creator").toString().equals(""))
306 // withValues.put("creator","Anonym");
308 // inserting content into database
309 String cid = contentModule.add(withValues);
310 theLog.printDebugInfo("id: "+cid);
311 //insert was not successfull
313 //How do we know that it was not succesful cause of a
314 //dupe, what if it failed cause of "No space left on device"?
315 //Or is there something I am missing? Wouldn't it be better
316 //to have an explicit dupe check and then insert? I have no
317 //idea what I am talking about. this comment is in case
318 //I forget to explicitely ask. -mh
319 deliver(req, res, mergeData, postingFormDupeTemplate);
322 String[] to_topicsArr = mp.getParameterValues("to_topic");
324 if (to_topicsArr != null && to_topicsArr.length > 0) {
326 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
328 } catch (Exception e) {
329 theLog.printError("setting content_x_topic failed");
330 contentModule.deleteById(cid);
331 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
335 // if op contains uploaddata
338 for(Iterator it = mp.requestList.iterator(); it.hasNext();){
339 MpRequest mpReq = (MpRequest)it.next();
340 String fileName = mpReq.getFilename();
342 //get the content-type from what the client browser
343 //sends us. (the "Oreilly method")
344 String contentType = mpReq.getContentType();
346 theLog.printInfo("FROM BROWSER: "+contentType);
348 //if the client browser sent us unknown (text/plain is default)
349 //or if we got application/octet-stream, it's possible that
350 //the browser is in error, better check against the file extension
351 if (contentType.equals("text/plain") ||
352 contentType.equals("application/octet-stream")) {
354 * Fallback to finding the mime-type through the standard ServletApi
355 * ServletContext getMimeType() method.
357 * This is a way to get the content-type via the .extension,
358 * we could maybe use a magic method as an additional method of
359 * figuring out the content-type, by looking at the header (first
360 * few bytes) of the file. (like the file(1) command). We could
361 * also call the "file" command through Runtime. This is an
362 * option that I almost prefer as it is already implemented and
363 * exists with an up-to-date map on most modern Unix like systems.
364 * I haven't found a really nice implementation of the magic method
367 * The first method we try thought is the "Oreilly method". It
368 * relies on the content-type that the client browser sends and
369 * that sometimes is application-octet stream with
370 * broken/mis-configured browsers.
372 * The map file we use for the extensions is the standard web-app
373 * deployment descriptor file (web.xml). See Mir's web.xml or see
374 * your Servlet containers (most likely Tomcat) documentation.
375 * So if you support a new media type you have to make sure that
376 * it is in this file -mh
379 (ServletContext)MirConfig.getPropAsObject("ServletContext");
380 contentType = ctx.getMimeType(fileName);
381 if (contentType==null)
382 contentType = "text/plain"; // rfc1867 says this is the default
384 HashMap mediaValues = new HashMap();
386 theLog.printInfo("CONTENT TYPE IS: "+contentType);
388 if (contentType.equals("text/plain") ||
389 contentType.equals("application/octet-stream")) {
390 contentModule.deleteById(cid);
391 _throwBadContentType(fileName, contentType);
394 String mediaTitle=(String)withValues.get("media_title"+i);
397 if (mediaTitle==null)
398 mediaTitle = (String)withValues.get("title");
400 mediaValues.put("title", mediaTitle);
401 mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
402 mediaValues.put("to_publisher", "1"); // op user
403 mediaValues.put("to_media_folder", "7"); // op media_folder
404 mediaValues.put("is_produced", "0");
405 mediaValues.put("is_published","0");
407 // @todo this should probably be moved to DatabaseMediaType -mh
408 String[] cTypeSplit = StringUtil.split(contentType, "/");
409 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
411 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
412 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
414 String mediaTypeId = null;
415 MirMedia mediaHandler;
416 Database mediaStorage;
417 // ProducerMedia mediaProducer;
419 //if we didn't find an entry matching the
420 //content-type int the table.
421 if (mediaTypesList.size() == 0) {
422 contentModule.deleteById(cid);
423 _throwBadContentType(fileName, contentType);
426 Entity mediaType = null;
427 Entity mediaType2 = null;
429 // find out if we an exact content-type match if so take it.
430 // otherwise try to match majortype/*
431 // @todo this should probably be moved to DatabaseMediaType -mh
432 for(int j=0;j<mediaTypesList.size();j++) {
433 if(contentType.equals(
434 mediaTypesList.elementAt(j).getValue("mime_type")))
435 mediaType = mediaTypesList.elementAt(j);
436 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
437 cTypeSplit[0]+"/*") )
438 mediaType2= mediaTypesList.elementAt(j);
441 if ( (mediaType == null) && (mediaType2 == null) ) {
442 contentModule.deleteById(cid);
443 _throwBadContentType(fileName, contentType);
445 else if( (mediaType == null) && (mediaType2 != null) )
446 mediaType = mediaType2;
448 //get the class names from the media_type table.
449 mediaTypeId = mediaType.getId();
451 // ############### @todo: merge these and the getURL call into one
452 // getURL helper call that just takes the Entity as a parameter
453 // along with media_type
454 mediaHandler = MediaHelper.getHandler(mediaType);
455 mediaStorage = MediaHelper.getStorage(mediaType,
456 "mircoders.storage.Database");
457 // Class prodCls = Class.forName("mircoders.producer.Producer"
458 // +mediaType.getValue("tablename"));
459 // mediaProducer = (ProducerMedia)prodCls.newInstance();
460 } catch (Exception e) {
461 theLog.printError("getting media handler failed: "+e.toString());
462 contentModule.deleteById(cid);
463 throw new ServletModuleException("getting media handler failed: "
467 mediaValues.put("to_media_type",mediaTypeId);
469 //load the classes via reflection
471 Entity mediaEnt = null;
473 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
474 mediaEnt.setStorage(mediaStorage);
475 mediaEnt.setValues(mediaValues);
476 mediaId = mediaEnt.insert();
478 //save and store the media data/metadata
479 mediaHandler.set(mpReq.getMedia(), mediaEnt,
482 //were done with mpReq at this point, dereference it.
483 //as it contains mucho mem. -mh 01.10.2001
486 //we got this far, associate the media to the article
487 mediaEnt.setValueForProperty("is_published","1");
490 // mediaProducer.handle(null, null, false, false, mediaId);
491 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
492 } catch (Exception e) {
493 theLog.printError("setting media failed: "+e.toString());
494 contentModule.deleteById(cid);
495 throw new ServletModuleException("setting media failed: "
499 } //end for Iterator...
501 //if we're here all is ok...
502 EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
503 contentEnt.setValueForProperty("is_published","1");
506 MirGlobal.localizer().openPostings().afterContentPosting(contentEnt);
509 //dereference mp. -mh
514 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
515 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
516 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
518 deliver(req, res, mergeData, postingFormDoneTemplate);
521 private void _throwBadContentType (String fileName, String contentType)
522 throws ServletModuleUserException {
524 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
526 throw new ServletModuleUserException("The file you uploaded is of the "
527 +"following mime-type: "+contentType
528 +", we do not support this mime-type. "
529 +"Error One or more files of unrecognized type. Sorry");
532 protected String createOneTimePasswd(){
533 Random r = new Random();
534 int random = r.nextInt();
535 long l = System.currentTimeMillis();
536 l = (l*l*l*l)/random;
538 String returnString = ""+l;
539 return returnString.substring(5);