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 ModuleImages imageModule;
48 private ModuleTopics themenModule;
49 private String directOp ="yes";
50 private String passwdProtection ="yes";
51 // Singelton / Kontruktor
52 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
53 public static ServletModule getInstance() { return instance; }
55 private ServletModuleOpenIndy() {
57 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
58 commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
59 commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
60 commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
61 postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
62 postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
63 postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
64 directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
65 passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
66 mainModule = new ModuleComment(DatabaseComment.getInstance());
67 contentModule = new ModuleContent(DatabaseContent.getInstance());
68 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
69 imageModule = new ModuleImages(DatabaseImages.getInstance());
70 defaultAction="addposting";
73 catch (StorageObjectException e) {
74 theLog.printError("servletmoduleopenindy could not be initialized");
80 * Method for making a comment
83 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
85 String aid = req.getParameter("aid"); // the article id the comment will belong to
86 if (aid!=null && !aid.equals(""))
88 SimpleHash mergeData = new SimpleHash();
91 if(passwdProtection.equals("yes")){
92 String passwd = this.createOneTimePasswd();
93 System.out.println(passwd);
94 HttpSession session = req.getSession(false);
95 session.setAttribute("passwd",passwd);
96 mergeData.put("passwd", passwd);
99 mergeData.put("aid", aid);
100 deliver(req, res, mergeData, commentFormTemplate);
102 else throw new ServletModuleException("aid not set!");
106 * Method for inserting a comment into the Database and delivering
107 * the commentDone Page
110 public void inscomment(HttpServletRequest req, HttpServletResponse res)
111 throws ServletModuleException,ServletModuleUserException
113 String aid = req.getParameter("to_media"); // the article id the comment will belong to
114 if (aid!=null && !aid.equals(""))
116 // ok, collecting data from form
118 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
120 //no html in comments(for now)
121 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
122 String k=(String)i.next();
123 String v=(String)withValues.get(k);
125 withValues.put(k,StringUtil.removeHTMLTags(v));
127 withValues.put("is_published","1");
129 //checking the onetimepasswd
130 if(passwdProtection.equals("yes")){
131 HttpSession session = req.getSession(false);
132 String sessionPasswd = (String)session.getAttribute("passwd");
133 if ( sessionPasswd == null){
134 throw new ServletModuleUserException("Lost password");
136 String passwd = req.getParameter("passwd");
137 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
138 throw new ServletModuleUserException("Missing password");
140 session.invalidate();
143 // inserting into database
144 String id = mainModule.add(withValues);
145 theLog.printDebugInfo("id: "+id);
146 //insert was not successfull
148 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
151 MirGlobal.localizer().openPostings().afterCommentPosting();
153 // redirecting to url
154 // should implement back to article
155 SimpleHash mergeData = new SimpleHash();
156 deliver(req, res, mergeData, commentFormDoneTemplate);
158 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
159 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
162 else throw new ServletModuleException("aid not set!");
167 * Method for delivering the form-Page for open posting
170 public void addposting(HttpServletRequest req, HttpServletResponse res)
171 throws ServletModuleException {
172 SimpleHash mergeData = new SimpleHash();
175 if(passwdProtection.equals("yes")){
176 String passwd = this.createOneTimePasswd();
177 System.out.println(passwd);
178 HttpSession session = req.getSession(false);
179 session.setAttribute("passwd",passwd);
180 mergeData.put("passwd", passwd);
183 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
184 String numOfMedia = req.getParameter("medianum");
185 if(numOfMedia==null||numOfMedia.equals("")){
187 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
188 numOfMedia = maxMedia;
191 int mediaNum = Integer.parseInt(numOfMedia);
192 SimpleList mediaFields = new SimpleList();
193 for(int i =0; i<mediaNum;i++){
194 Integer mNum = new Integer(i+1);
195 mediaFields.add(mNum.toString());
197 mergeData.put("medianum",numOfMedia);
198 mergeData.put("mediafields",mediaFields);
201 SimpleHash extraInfo = new SimpleHash();
203 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
204 extraInfo.put("languagePopUpData", popUpData );
205 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
206 } catch (Exception e) {
207 theLog.printError("languagePopUpData or getTopicslist failed "
209 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
212 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
216 * Method for inserting an open posting into the Database and delivering
217 * the postingDone Page
220 public void insposting(HttpServletRequest req, HttpServletResponse res)
221 throws ServletModuleException, ServletModuleUserException
223 SimpleHash mergeData = new SimpleHash();
224 boolean setMedia=false;
225 boolean setTopic = false;
228 WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
230 HashMap withValues = mp.getParameters();
232 //checking the onetimepasswd
233 if(passwdProtection.equals("yes")){
234 HttpSession session = req.getSession(false);
235 String sessionPasswd = (String)session.getAttribute("passwd");
236 if ( sessionPasswd == null){
237 throw new ServletModuleUserException("Lost password");
239 String passwd = (String)withValues.get("passwd");
240 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
241 throw new ServletModuleUserException("Missing password");
243 session.invalidate();
246 if ((((String)withValues.get("title")).length() == 0) ||
247 (((String)withValues.get("description")).length() == 0) ||
248 (((String)withValues.get("content_data")).length() == 0))
249 throw new ServletModuleUserException("Missing field");
251 // call the routines that escape html
253 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
254 String k=(String)i.next();
255 String v=(String)withValues.get(k);
257 if (k.equals("content_data")){
258 //this doesn't quite work yet, so for now, all html goes
259 //withValues.put(k,StringUtil.approveHTMLTags(v));
260 //withValues.put(k,StringUtil.removeHTMLTags(v));
262 withValues.put(k,StringUtil.removeHTMLTags(v));
267 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
268 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
269 withValues.put("is_produced", "0");
270 // op-articles are not immediatly published
271 // we don't know that all is good yet (media, title is present, etc..)
272 withValues.put("is_published","0");
273 // if op direct article-type == newswire
274 if (directOp.equals("yes")) withValues.put("to_article_type","1");
276 // owner is openposting user
277 withValues.put("to_publisher","1");
278 if (withValues.get("creator").toString().equals(""))
279 withValues.put("creator","Anonym");
281 // inserting content into database
282 String cid = contentModule.add(withValues);
283 theLog.printDebugInfo("id: "+cid);
284 //insert was not successfull
286 //How do we know that it was not succesful cause of a
287 //dupe, what if it failed cause of "No space left on device"?
288 //Or is there something I am missing? Wouldn't it be better
289 //to have an explicit dupe check and then insert? I have no
290 //idea what I am talking about. this comment is in case
291 //I forget to explicitely ask. -mh
292 deliver(req, res, mergeData, postingFormDupeTemplate);
295 String[] to_topicsArr = mp.getParameterValues("to_topic");
297 if (to_topicsArr != null && to_topicsArr.length > 0) {
299 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
301 } catch (Exception e) {
302 theLog.printError("setting content_x_topic failed");
303 contentModule.deleteById(cid);
304 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
308 // if op contains uploaddata
311 for(Iterator it = mp.requestList.iterator(); it.hasNext();){
312 MpRequest mpReq = (MpRequest)it.next();
313 String fileName = mpReq.getFilename();
315 //get the content-type from what the client browser
316 //sends us. (the "Oreilly method")
317 String contentType = mpReq.getContentType();
319 theLog.printInfo("FROM BROWSER: "+contentType);
321 //if the client browser sent us unknown (text/plain is default)
322 //or if we got application/octet-stream, it's possible that
323 //the browser is in error, better check against the file extension
324 if (contentType.equals("text/plain") ||
325 contentType.equals("application/octet-stream")) {
327 * Fallback to finding the mime-type through the standard ServletApi
328 * ServletContext getMimeType() method.
330 * This is a way to get the content-type via the .extension,
331 * we could maybe use a magic method as an additional method of
332 * figuring out the content-type, by looking at the header (first
333 * few bytes) of the file. (like the file(1) command). We could
334 * also call the "file" command through Runtime. This is an
335 * option that I almost prefer as it is already implemented and
336 * exists with an up-to-date map on most modern Unix like systems.
337 * I haven't found a really nice implementation of the magic method
340 * The first method we try thought is the "Oreilly method". It
341 * relies on the content-type that the client browser sends and
342 * that sometimes is application-octet stream with
343 * broken/mis-configured browsers.
345 * The map file we use for the extensions is the standard web-app
346 * deployment descriptor file (web.xml). See Mir's web.xml or see
347 * your Servlet containers (most likely Tomcat) documentation.
348 * So if you support a new media type you have to make sure that
349 * it is in this file -mh
352 (ServletContext)MirConfig.getPropAsObject("ServletContext");
353 contentType = ctx.getMimeType(fileName);
354 if (contentType==null)
355 contentType = "text/plain"; // rfc1867 says this is the default
357 HashMap mediaValues = new HashMap();
359 theLog.printInfo("CONTENT TYPE IS: "+contentType);
361 if (contentType.equals("text/plain") ||
362 contentType.equals("application/octet-stream")) {
363 contentModule.deleteById(cid);
364 _throwBadContentType(fileName, contentType);
367 String mediaTitle=(String)withValues.get("media_title"+i);
370 if (mediaTitle==null)
371 mediaTitle = (String)withValues.get("title");
373 mediaValues.put("title", mediaTitle);
374 mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
375 mediaValues.put("to_publisher", "1"); // op user
376 mediaValues.put("to_media_folder", "7"); // op media_folder
377 mediaValues.put("is_produced", "0");
378 mediaValues.put("is_published","0");
380 // @todo this should probably be moved to DatabaseMediaType -mh
381 String[] cTypeSplit = StringUtil.split(contentType, "/");
382 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
384 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
385 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
387 String mediaTypeId = null;
388 MirMedia mediaHandler;
389 Database mediaStorage;
390 // ProducerMedia mediaProducer;
392 //if we didn't find an entry matching the
393 //content-type int the table.
394 if (mediaTypesList.size() == 0) {
395 contentModule.deleteById(cid);
396 _throwBadContentType(fileName, contentType);
399 Entity mediaType = null;
400 Entity mediaType2 = null;
402 // find out if we an exact content-type match if so take it.
403 // otherwise try to match majortype/*
404 // @todo this should probably be moved to DatabaseMediaType -mh
405 for(int j=0;j<mediaTypesList.size();j++) {
406 if(contentType.equals(
407 mediaTypesList.elementAt(j).getValue("mime_type")))
408 mediaType = mediaTypesList.elementAt(j);
409 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
410 cTypeSplit[0]+"/*") )
411 mediaType2= mediaTypesList.elementAt(j);
414 if ( (mediaType == null) && (mediaType2 == null) ) {
415 contentModule.deleteById(cid);
416 _throwBadContentType(fileName, contentType);
418 else if( (mediaType == null) && (mediaType2 != null) )
419 mediaType = mediaType2;
421 //get the class names from the media_type table.
422 mediaTypeId = mediaType.getId();
424 // ############### @todo: merge these and the getURL call into one
425 // getURL helper call that just takes the Entity as a parameter
426 // along with media_type
427 mediaHandler = MediaHelper.getHandler(mediaType);
428 mediaStorage = MediaHelper.getStorage(mediaType,
429 "mircoders.storage.Database");
430 // Class prodCls = Class.forName("mircoders.producer.Producer"
431 // +mediaType.getValue("tablename"));
432 // mediaProducer = (ProducerMedia)prodCls.newInstance();
433 } catch (Exception e) {
434 theLog.printError("getting media handler failed: "+e.toString());
435 contentModule.deleteById(cid);
436 throw new ServletModuleException("getting media handler failed: "
440 mediaValues.put("to_media_type",mediaTypeId);
442 //load the classes via reflection
444 Entity mediaEnt = null;
446 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
447 mediaEnt.setStorage(mediaStorage);
448 mediaEnt.setValues(mediaValues);
449 mediaId = mediaEnt.insert();
451 //save and store the media data/metadata
452 mediaHandler.set(mpReq.getMedia(), mediaEnt,
455 //were done with mpReq at this point, dereference it.
456 //as it contains mucho mem. -mh 01.10.2001
459 //we got this far, associate the media to the article
460 mediaEnt.setValueForProperty("is_published","1");
463 // mediaProducer.handle(null, null, false, false, mediaId);
464 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
465 } catch (Exception e) {
466 theLog.printError("setting media failed: "+e.toString());
467 contentModule.deleteById(cid);
468 throw new ServletModuleException("setting media failed: "
472 } //end for Iterator...
474 //if we're here all is ok...
475 EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
476 contentEnt.setValueForProperty("is_published","1");
480 //dereference mp. -mh
484 MirGlobal.localizer().openPostings().afterContentPosting();
486 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
487 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
488 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
490 deliver(req, res, mergeData, postingFormDoneTemplate);
493 private void _throwBadContentType (String fileName, String contentType)
494 throws ServletModuleUserException {
496 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
498 throw new ServletModuleUserException("The file you uploaded is of the "
499 +"following mime-type: "+contentType
500 +", we do not support this mime-type. "
501 +"Error One or more files of unrecognized type. Sorry");
504 protected String createOneTimePasswd(){
505 Random r = new Random();
506 int random = r.nextInt();
507 long l = System.currentTimeMillis();
508 l = (l*l*l*l)/random;
510 String returnString = ""+l;
511 return returnString.substring(5);