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);
164 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
165 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
167 catch (Throwable t) {
168 throw new ServletModuleException(t.getMessage());
175 // redirecting to url
176 // should implement back to article
177 SimpleHash mergeData = new SimpleHash();
178 deliver(req, res, mergeData, commentFormDoneTemplate);
180 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
181 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
184 else throw new ServletModuleException("aid not set!");
189 * Method for delivering the form-Page for open posting
192 public void addposting(HttpServletRequest req, HttpServletResponse res)
193 throws ServletModuleException {
194 SimpleHash mergeData = new SimpleHash();
197 if(passwdProtection.equals("yes")){
198 String passwd = this.createOneTimePasswd();
199 System.out.println(passwd);
200 HttpSession session = req.getSession(false);
201 session.setAttribute("passwd",passwd);
202 mergeData.put("passwd", passwd);
205 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
206 String numOfMedia = req.getParameter("medianum");
207 if(numOfMedia==null||numOfMedia.equals("")){
209 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
210 numOfMedia = maxMedia;
213 int mediaNum = Integer.parseInt(numOfMedia);
214 SimpleList mediaFields = new SimpleList();
215 for(int i =0; i<mediaNum;i++){
216 Integer mNum = new Integer(i+1);
217 mediaFields.add(mNum.toString());
219 mergeData.put("medianum",numOfMedia);
220 mergeData.put("mediafields",mediaFields);
223 SimpleHash extraInfo = new SimpleHash();
225 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
226 extraInfo.put("languagePopUpData", popUpData );
227 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
229 // ML: Bolivia specific, will move it towards localization
230 extraInfo.put("topics", themenModule.getTopicsList());
231 String defaultCity = req.getParameter("city");
232 if(defaultCity!=null && !defaultCity.equals("")){
233 extraInfo.put("city", defaultCity);
236 } catch (Exception e) {
237 theLog.printError("languagePopUpData or getTopicslist failed "
239 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
244 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
248 * Method for inserting an open posting into the Database and delivering
249 * the postingDone Page
252 public void insposting(HttpServletRequest req, HttpServletResponse res)
253 throws ServletModuleException, ServletModuleUserException
255 SimpleHash mergeData = new SimpleHash();
256 boolean setMedia=false;
257 boolean setTopic = false;
260 WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
262 HashMap withValues = mp.getParameters();
264 //checking the onetimepasswd
265 if(passwdProtection.equals("yes")){
266 HttpSession session = req.getSession(false);
267 String sessionPasswd = (String)session.getAttribute("passwd");
268 if ( sessionPasswd == null){
269 throw new ServletModuleUserException("Lost password");
271 String passwd = (String)withValues.get("passwd");
272 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
273 throw new ServletModuleUserException("Missing password");
275 session.invalidate();
278 if ((((String)withValues.get("title")).length() == 0) ||
279 (((String)withValues.get("description")).length() == 0) ||
280 (((String)withValues.get("content_data")).length() == 0))
281 throw new ServletModuleUserException("Missing field");
283 // call the routines that escape html
285 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
286 String k=(String)i.next();
287 String v=(String)withValues.get(k);
289 if (k.equals("content_data")){
290 //this doesn't quite work yet, so for now, all html goes
291 //withValues.put(k,StringUtil.approveHTMLTags(v));
292 //withValues.put(k,StringUtil.removeHTMLTags(v));
294 withValues.put(k,StringUtil.removeHTMLTags(v));
299 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
300 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
301 withValues.put("is_produced", "0");
302 // op-articles are not immediatly published
303 // we don't know that all is good yet (media, title is present, etc..)
304 withValues.put("is_published","0");
305 // if op direct article-type == newswire
306 if (directOp.equals("yes")) withValues.put("to_article_type","1");
308 withValues.put("to_publisher","1");
310 // owner is openposting user
311 // ML: this is not multi-language friendly and this can be done in a template
312 // if (withValues.get("creator").toString().equals(""))
313 // withValues.put("creator","Anonym");
315 // inserting content into database
316 String cid = contentModule.add(withValues);
317 theLog.printDebugInfo("id: "+cid);
318 //insert was not successfull
320 //How do we know that it was not succesful cause of a
321 //dupe, what if it failed cause of "No space left on device"?
322 //Or is there something I am missing? Wouldn't it be better
323 //to have an explicit dupe check and then insert? I have no
324 //idea what I am talking about. this comment is in case
325 //I forget to explicitely ask. -mh
326 deliver(req, res, mergeData, postingFormDupeTemplate);
329 String[] to_topicsArr = mp.getParameterValues("to_topic");
331 if (to_topicsArr != null && to_topicsArr.length > 0) {
333 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
335 } catch (Exception e) {
336 theLog.printError("setting content_x_topic failed");
337 contentModule.deleteById(cid);
338 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
342 // if op contains uploaddata
345 for(Iterator it = mp.requestList.iterator(); it.hasNext();){
346 MpRequest mpReq = (MpRequest)it.next();
347 String fileName = mpReq.getFilename();
349 //get the content-type from what the client browser
350 //sends us. (the "Oreilly method")
351 String contentType = mpReq.getContentType();
353 theLog.printInfo("FROM BROWSER: "+contentType);
355 //if the client browser sent us unknown (text/plain is default)
356 //or if we got application/octet-stream, it's possible that
357 //the browser is in error, better check against the file extension
358 if (contentType.equals("text/plain") ||
359 contentType.equals("application/octet-stream")) {
361 * Fallback to finding the mime-type through the standard ServletApi
362 * ServletContext getMimeType() method.
364 * This is a way to get the content-type via the .extension,
365 * we could maybe use a magic method as an additional method of
366 * figuring out the content-type, by looking at the header (first
367 * few bytes) of the file. (like the file(1) command). We could
368 * also call the "file" command through Runtime. This is an
369 * option that I almost prefer as it is already implemented and
370 * exists with an up-to-date map on most modern Unix like systems.
371 * I haven't found a really nice implementation of the magic method
374 * The first method we try thought is the "Oreilly method". It
375 * relies on the content-type that the client browser sends and
376 * that sometimes is application-octet stream with
377 * broken/mis-configured browsers.
379 * The map file we use for the extensions is the standard web-app
380 * deployment descriptor file (web.xml). See Mir's web.xml or see
381 * your Servlet containers (most likely Tomcat) documentation.
382 * So if you support a new media type you have to make sure that
383 * it is in this file -mh
386 (ServletContext)MirConfig.getPropAsObject("ServletContext");
387 contentType = ctx.getMimeType(fileName);
388 if (contentType==null)
389 contentType = "text/plain"; // rfc1867 says this is the default
391 HashMap mediaValues = new HashMap();
393 theLog.printInfo("CONTENT TYPE IS: "+contentType);
395 if (contentType.equals("text/plain") ||
396 contentType.equals("application/octet-stream")) {
397 contentModule.deleteById(cid);
398 _throwBadContentType(fileName, contentType);
401 String mediaTitle=(String)withValues.get("media_title"+i);
404 if (mediaTitle==null)
405 mediaTitle = (String)withValues.get("title");
407 mediaValues.put("title", mediaTitle);
408 mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
409 mediaValues.put("to_publisher", "1"); // op user
410 mediaValues.put("to_media_folder", "7"); // op media_folder
411 mediaValues.put("is_produced", "0");
412 mediaValues.put("is_published","0");
414 // @todo this should probably be moved to DatabaseMediaType -mh
415 String[] cTypeSplit = StringUtil.split(contentType, "/");
416 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
418 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
419 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
421 String mediaTypeId = null;
422 MirMedia mediaHandler;
423 Database mediaStorage;
424 // ProducerMedia mediaProducer;
426 //if we didn't find an entry matching the
427 //content-type int the table.
428 if (mediaTypesList.size() == 0) {
429 contentModule.deleteById(cid);
430 _throwBadContentType(fileName, contentType);
433 Entity mediaType = null;
434 Entity mediaType2 = null;
436 // find out if we an exact content-type match if so take it.
437 // otherwise try to match majortype/*
438 // @todo this should probably be moved to DatabaseMediaType -mh
439 for(int j=0;j<mediaTypesList.size();j++) {
440 if(contentType.equals(
441 mediaTypesList.elementAt(j).getValue("mime_type")))
442 mediaType = mediaTypesList.elementAt(j);
443 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
444 cTypeSplit[0]+"/*") )
445 mediaType2= mediaTypesList.elementAt(j);
448 if ( (mediaType == null) && (mediaType2 == null) ) {
449 contentModule.deleteById(cid);
450 _throwBadContentType(fileName, contentType);
452 else if( (mediaType == null) && (mediaType2 != null) )
453 mediaType = mediaType2;
455 //get the class names from the media_type table.
456 mediaTypeId = mediaType.getId();
458 // ############### @todo: merge these and the getURL call into one
459 // getURL helper call that just takes the Entity as a parameter
460 // along with media_type
461 mediaHandler = MediaHelper.getHandler(mediaType);
462 mediaStorage = MediaHelper.getStorage(mediaType,
463 "mircoders.storage.Database");
464 // Class prodCls = Class.forName("mircoders.producer.Producer"
465 // +mediaType.getValue("tablename"));
466 // mediaProducer = (ProducerMedia)prodCls.newInstance();
467 } catch (Exception e) {
468 theLog.printError("getting media handler failed: "+e.toString());
469 contentModule.deleteById(cid);
470 throw new ServletModuleException("getting media handler failed: "
474 mediaValues.put("to_media_type",mediaTypeId);
476 //load the classes via reflection
478 Entity mediaEnt = null;
480 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
481 mediaEnt.setStorage(mediaStorage);
482 mediaEnt.setValues(mediaValues);
483 mediaId = mediaEnt.insert();
485 //save and store the media data/metadata
486 mediaHandler.set(mpReq.getMedia(), mediaEnt,
489 //were done with mpReq at this point, dereference it.
490 //as it contains mucho mem. -mh 01.10.2001
493 //we got this far, associate the media to the article
494 mediaEnt.setValueForProperty("is_published","1");
497 // mediaProducer.handle(null, null, false, false, mediaId);
498 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
499 } catch (Exception e) {
500 theLog.printError("setting media failed: "+e.toString());
501 contentModule.deleteById(cid);
502 throw new ServletModuleException("setting media failed: "
506 } //end for Iterator...
508 //if we're here all is ok...
509 EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
510 contentEnt.setValueForProperty("is_published","1");
515 //dereference mp. -mh
519 MirGlobal.localizer().openPostings().afterContentPosting(contentEnt);
521 catch (Throwable t) {
522 throw new ServletModuleException(t.getMessage());
525 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
526 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
527 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
529 deliver(req, res, mergeData, postingFormDoneTemplate);
532 private void _throwBadContentType (String fileName, String contentType)
533 throws ServletModuleUserException {
535 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
537 throw new ServletModuleUserException("The file you uploaded is of the "
538 +"following mime-type: "+contentType
539 +", we do not support this mime-type. "
540 +"Error One or more files of unrecognized type. Sorry");
543 protected String createOneTimePasswd(){
544 Random r = new Random();
545 int random = r.nextInt();
546 long l = System.currentTimeMillis();
547 l = (l*l*l*l)/random;
549 String returnString = ""+l;
550 return returnString.substring(5);