important bugfix: new article produced a form without values for the various
[mir.git] / source / mircoders / servlet / ServletModuleContent.java
1 package mircoders.servlet;
2
3 import java.io.*;
4 import java.sql.*;
5 import java.util.*;
6 import java.net.*;
7 import javax.servlet.*;
8 import javax.servlet.http.*;
9
10
11 import freemarker.template.*;
12
13 import mir.servlet.*;
14 import mir.media.*;
15 import mir.module.*;
16 import mir.misc.*;
17 import mir.storage.*;
18 import mir.entity.*;
19
20 import mircoders.storage.*;
21 import mircoders.module.*;
22 import mircoders.entity.*;
23
24
25 /*
26  *  ServletModuleContent -
27  *  liefert HTML fuer Content
28  *
29  *
30  * @author RK
31  */
32
33 public class ServletModuleContent extends ServletModule
34 {
35
36   static ModuleTopics         themenModule;
37   static ModuleSchwerpunkt    schwerpunktModule;
38   static ModuleImages         imageModule;
39
40   static String templateOpString;
41
42   // Singelton / Kontruktor
43
44   private static ServletModuleContent instance = new ServletModuleContent();
45   public static ServletModule getInstance() { return instance; }
46
47   private ServletModuleContent() {
48     try {
49                 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Content.Logfile"));
50       templateListString = MirConfig.getProp("ServletModule.Content.ListTemplate");
51       //templateOpString = MirConfig.getProp("ServletModule.Content.OpTemplate");
52       templateObjektString = MirConfig.getProp("ServletModule.Content.ObjektTemplate");
53       templateConfirmString = MirConfig.getProp("ServletModule.Content.ConfirmTemplate");
54       mainModule = new ModuleContent(DatabaseContent.getInstance());
55       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
56       schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance());
57       imageModule = new ModuleImages(DatabaseImages.getInstance());
58     } catch (StorageObjectException e) {
59       theLog.printDebugInfo("servletmodulecontent konnte nicht initialisiert werden");
60     }
61   }
62
63   // Methoden
64
65   public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
66   {
67     try {
68       EntityUsers user = _getUser(req);
69       EntityList   theList;
70       String       offsetParam = req.getParameter("offset");
71       int          offset =0;
72
73       // hier offsetcode bearbeiteb
74       if (offsetParam != null && !offsetParam.equals(""))
75           offset = Integer.parseInt(offsetParam);
76
77       if (req.getParameter("next") != null)
78           offset=Integer.parseInt(req.getParameter("nextoffset"));
79       else
80           if (req.getParameter("prev") != null)
81             offset = Integer.parseInt(req.getParameter("prevoffset"));
82
83       String        whereParam = req.getParameter("where");
84       String        orderParam = req.getParameter("order");
85
86       theList = ((ModuleContent)mainModule).getContent(whereParam, orderParam, offset, user);
87       _list(theList, req, res);
88     } catch (ModuleException e) {
89       throw new ServletModuleException(e.toString());
90     }
91   }
92
93   public void listop(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
94   {
95     try {
96       EntityUsers user = _getUser(req);
97       EntityList   theList;
98       String       offsetParam = req.getParameter("offset");
99       int          offset =0;
100
101       String whereParam = req.getParameter("where");
102
103       if (whereParam==null) whereParam = "to_article_type='0'";
104
105       // hier offsetcode bearbeiteb
106       if (offsetParam != null && !offsetParam.equals(""))
107           offset = Integer.parseInt(offsetParam);
108
109       if (req.getParameter("next") != null)
110           offset=Integer.parseInt(req.getParameter("nextoffset"));
111       else
112           if (req.getParameter("prev") != null)
113             offset = Integer.parseInt(req.getParameter("prevoffset"));
114
115       String orderParam = req.getParameter("order");
116
117       theList = ((ModuleContent)mainModule).getContent(whereParam, orderParam, offset, user);
118       _list(theList, req, res);
119     } catch (ModuleException e) {
120       throw new ServletModuleException(e.toString());
121     }
122   }
123
124
125   public void search(HttpServletRequest req, HttpServletResponse res)
126     throws ServletModuleException {
127     try {
128       EntityUsers   user = _getUser(req);
129       EntityList    theList;
130       String        fieldParam = req.getParameter("field");
131       String        fieldValueParam = req.getParameter("fieldvalue");
132       String        orderParam = req.getParameter("order");
133
134       theList = ((ModuleContent)mainModule).getContentByField(fieldParam, fieldValueParam, orderParam, 0, user);
135       _list(theList, req, res);
136     } catch (ModuleException e) {
137       throw new ServletModuleException(e.toString());
138     }
139   }
140
141   public void add(HttpServletRequest req, HttpServletResponse res)
142     throws ServletModuleException {
143
144     EntityUsers   user = _getUser(req);
145     SimpleHash mergeData = new SimpleHash();
146     SimpleHash extraInfo = new SimpleHash();
147
148     mergeData.put("new", "1");
149     mergeData.put("is_published", "1");
150     String now = StringUtil.date2webdbDate(new GregorianCalendar());
151     mergeData.put("date", new SimpleScalar(now));
152     try {
153     extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
154     } catch (ModuleException e) {
155       theLog.printError("themenPopupData could not be fetched.");
156     }
157     try {
158       extraInfo.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
159     } catch (Exception e) {
160       theLog.printError("articletype could not be fetched.");
161     }
162     try {
163       extraInfo.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
164     } catch (Exception e) {
165       theLog.printError("language-popup could not be fetched.");
166     }
167     try {
168       extraInfo.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
169     } catch (ModuleException e) {
170       theLog.printError("schwerpunktPopupData could not be fetched.");
171     }
172     extraInfo.put("login_user", user);
173     deliver(req, res, mergeData, extraInfo, templateObjektString);
174   }
175
176
177   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
178   {
179     //theLog.printDebugInfo(":: content :: trying to insert");
180     try {
181       EntityUsers   user = _getUser(req);
182       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
183       //theLog.printDebugInfo(":: content :: got intersecting values");
184       String now = StringUtil.date2webdbDate(new GregorianCalendar());
185       withValues.put("date", now);
186       withValues.put("publish_path", StringUtil.webdbDate2path(now));
187       withValues.put("to_publisher", user.getId());
188       withValues.put("is_produced", "0");
189       if (!withValues.containsKey("is_published"))
190         withValues.put("is_published","0");
191       if (!withValues.containsKey("is_html"))
192         withValues.put("is_html","0");
193
194 //      ML: this is not multi-language friendly and this can be done in a template
195 //      if (withValues.get("creator").toString().equals(""))
196 //        withValues.put("creator","Anonym");
197
198
199       String id = mainModule.add(withValues);
200       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
201       //theLog.printDebugInfo(":: content :: inserted");
202       _showObject(id, req, res);
203     }
204     catch (StorageObjectException e) {
205       throw new ServletModuleException(e.toString());
206     }
207     catch (ModuleException e) {
208       throw new ServletModuleException(e.toString());
209     }
210   }
211
212   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
213   {
214
215     EntityUsers   user = _getUser(req);
216     // hier pruefen ob dem akt. user loeschen erlaubt ist...
217     String idParam = req.getParameter("id");
218     if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
219
220     String confirmParam = req.getParameter("confirm");
221     String cancelParam = req.getParameter("cancel");
222
223     if (confirmParam == null && cancelParam == null) {
224       // HTML Ausgabe zum Confirmen!
225       SimpleHash mergeData = new SimpleHash();
226       mergeData.put("module", "Content");
227       mergeData.put("infoString", "Content: " + idParam);
228       mergeData.put("id", idParam);
229       mergeData.put("where", req.getParameter("where"));
230       mergeData.put("order", req.getParameter("order"));
231       mergeData.put("offset", req.getParameter("offset"));
232       deliver(req, res, mergeData, templateConfirmString);
233     }
234     else {
235       if (confirmParam!= null && !confirmParam.equals("")) {
236         try {
237           mainModule.deleteById(idParam);
238
239           /** @todo the following two should be imlied in
240            *  DatabaseContent */
241
242           //delete rows in the content_x_topic-table
243           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
244           //delete rows in the comment-table
245           DatabaseComment.getInstance().deleteByContentId(idParam);
246         } catch (ModuleException e) {
247           throw new ServletModuleException(e.toString());
248         } catch (StorageObjectException e) {
249           throw new ServletModuleException(e.toString());
250         }
251         list(req,res);
252       }
253       else {
254         // Datensatz anzeigen
255         _showObject(idParam, req, res);
256       }
257     }
258   }
259
260   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
261   {
262     String        idParam = req.getParameter("id");
263     if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
264     _showObject(idParam, req, res);
265   }
266
267   // methods for attaching media file
268   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
269   {
270     String  mediaIdParam = req.getParameter("mid");
271     String  idParam = req.getParameter("cid");
272     if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing");
273
274     try {
275       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
276       entContent.attach(mediaIdParam);
277     }
278     catch(ModuleException e) {
279       theLog.printError("smod content :: attach :: could not get entityContent");
280     }
281     catch(StorageObjectException e) {
282       theLog.printError("smod content :: attach :: could not get entityContent");
283     }
284
285     _showObject(idParam, req, res);
286   }
287
288   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
289   {
290     String  cidParam = req.getParameter("cid");
291                 String  midParam = req.getParameter("mid");
292     if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing");
293     if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing");
294
295     try {
296       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
297       entContent.dettach(cidParam,midParam);
298     }
299     catch(ModuleException e) {
300       theLog.printError("smod content :: dettach :: could not get entityContent");
301     }
302     catch(StorageObjectException e) {
303       theLog.printError("smod content :: dettach :: could not get entityContent");
304     }
305
306     _showObject(cidParam, req, res);
307   }
308
309   public void newswire(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
310   {
311     String  idParam = req.getParameter("id");
312     if (idParam == null) throw new ServletModuleException("smod content :: newswire :: id missing");
313     try {
314       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
315       entContent.newswire();
316     }
317     catch(ModuleException e) {
318       theLog.printError("smod content :: newswire :: could not get entityContent");
319     }
320     catch(StorageObjectException e) {
321       theLog.printError("smod content :: dettach :: could not get entityContent");
322     }
323
324     list(req, res);
325   }
326
327
328   public void update(HttpServletRequest req, HttpServletResponse res)
329     throws ServletModuleException
330   {
331     try {
332
333       EntityUsers   user = _getUser(req);
334       if (user==null) theLog.printDebugInfo("user null!");
335       String idParam = req.getParameter("id");
336       if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing");
337
338       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
339       String[] topic_id = req.getParameterValues("to_topic");
340       String content_id = req.getParameter("id");
341       // withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
342       if(user != null) withValues.put("user_id", user.getId());
343       withValues.put("is_produced", "0");
344       if (!withValues.containsKey("is_published"))
345         withValues.put("is_published","0");
346       if (!withValues.containsKey("is_html"))
347         withValues.put("is_html","0");
348
349 //      ML: this is not multi-language friendly and this can be done in a template
350 //      if (withValues.get("creator").toString().equals(""))
351 //        withValues.put("creator","Anonym");
352
353       //theLog.printDebugInfo("updating. ");
354       String id = mainModule.set(withValues);
355       DatabaseContentToTopics.getInstance().setTopics(req.getParameter("id"),topic_id);
356       //theLog.printDebugInfo("update done. ");
357       String whereParam = req.getParameter("where");
358       String orderParam = req.getParameter("order");
359       if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){
360         //theLog.printDebugInfo("update to list");
361         list(req,res);
362       }
363       else
364         _showObject(idParam, req, res);
365     }
366     catch (StorageObjectException e) {
367       throw new ServletModuleException(e.toString());
368     }
369     catch (ModuleException e) {
370       throw new ServletModuleException(e.toString());
371     }
372   }
373
374   //
375   // Hilfsmethoden
376
377   private void _showObject(String id, HttpServletRequest req, HttpServletResponse res)
378     throws ServletModuleException {
379
380     SimpleHash extraInfo = new SimpleHash();
381     try {
382       EntityContent entContent=(EntityContent)mainModule.getById(id);
383
384       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
385       try {
386         extraInfo.put("articletypePopupData",
387                         DatabaseArticleType.getInstance().getPopupData());
388       } catch (Exception e) {
389         theLog.printError("articletype could not be fetched.");
390       }
391       try {
392         extraInfo.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
393       } catch (Exception e) {
394         theLog.printError("language-popup could not be fetched.");
395       }
396
397       extraInfo.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
398       // hier code um zur liste zurueckzukommen
399       String offsetParam, whereParam, orderParam;
400       if ((offsetParam = req.getParameter("offset"))!=null) extraInfo.put("offset", offsetParam);
401       if ((whereParam = req.getParameter("where"))!=null) extraInfo.put("where", whereParam);
402       if ((orderParam = req.getParameter("order"))!=null) extraInfo.put("order", orderParam);
403       extraInfo.put("login_user", _getUser(req));
404       deliver(req, res, entContent, extraInfo, templateObjektString);
405     } catch (Exception e) {
406       throw new ServletModuleException(e.toString());
407     }
408   }
409
410
411   public void _list(EntityList theList, HttpServletRequest req, HttpServletResponse res)
412     throws ServletModuleException {
413
414     try {
415       // hier dann htmlcode rausschreiben
416       if (theList == null || theList.getCount() == 0 || theList.getCount()>1) {
417         SimpleHash modelRoot = HTMLTemplateProcessor.makeSimpleHashWithEntitylistInfos(theList);
418         modelRoot.put("themenHashData", themenModule.getHashData());
419         modelRoot.put("schwerpunktHashData", schwerpunktModule.getHashData());
420         modelRoot.put("articletypeHash", DatabaseArticleType.getInstance().getHashData());
421         deliver(req, res, modelRoot, templateListString);
422       } else  { // count = 1
423         _showObject(theList.elementAt(0).getId(),req,res);
424       }
425     } catch (StorageObjectException e) {
426       throw new ServletModuleException(e.toString());
427     }
428   }
429
430   public void _listop(EntityList theList, HttpServletRequest req, HttpServletResponse res)
431     throws ServletModuleException {
432
433     try {
434       // delivering html
435       if (theList == null || theList.getCount() == 0 || theList.getCount()>1) {
436         SimpleHash modelRoot = HTMLTemplateProcessor.makeSimpleHashWithEntitylistInfos(theList);
437         modelRoot.put("articletypeHash", DatabaseArticleType.getInstance().getHashData());
438
439     EntityContent       currentContent;
440     EntityList          upMediaEntityList;
441     EntityList          imageEntityList;
442     EntityList          currentMediaList;
443     Entity              mediaType;
444     EntityMedia         uploadedMedia;
445     SimpleList          opList;
446       String imageRoot = MirConfig.getProp("Producer.ImageRoot");
447
448     SimpleHash          contentHash;
449     Class               mediaHandlerClass=null;
450     MirMedia            mediaHandler=null;
451     String              mediaHandlerName=null;
452     Database            mediaStorage=null;
453     String              tinyIcon;
454     String              iconAlt;
455
456       for (int i=0; i < theList.size();i++) {
457         currentContent = (EntityContent)theList.elementAt(i);
458         //fetching/setting the images
459         upMediaEntityList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
460         if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
461           tinyIcon = null;
462           iconAlt = null;
463           mediaHandler = null;
464           mediaHandlerName = null;
465           for (int n=0; n < upMediaEntityList.size();n++) {
466             uploadedMedia = (EntityMedia)upMediaEntityList.elementAt(n);
467             mediaType = uploadedMedia.getMediaType();
468
469             //must of had a non-existant to_media_type entry..
470             //let's save our ass.
471             if (mediaType != null) {
472                 try {
473                   mediaHandlerName = mediaType.getValue("classname");
474                   mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
475                   mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
476                 } catch (Exception e) {
477                   theLog.printError("ProducerStartpage:problem in reflection: "+mediaHandlerName);
478                 }
479
480                 //the "best" media type to show
481                 if (mediaHandler.isVideo()) {
482                   tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
483                   iconAlt = "Video";
484                   break;
485                 } else if (mediaHandler.isAudio()) {
486                   tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
487                   iconAlt = "Audio";
488                 } else if (tinyIcon == null && !mediaHandler.isImage()) {
489                   tinyIcon = mediaHandler.getTinyIcon();
490                   iconAlt = mediaHandler.getIconAlt();
491                 }
492             }
493           }
494           //it only has image(s)
495           if (tinyIcon == null) {
496             tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
497             iconAlt = "Image";
498           }
499
500         // uploadedMedia Entity list is empty.
501         // we only have text
502         } else {
503           tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
504           iconAlt = "Text";
505         }
506
507         try{
508           //mediaList = HTMLTemplateProcessor.makeSimpleList(upMediaEntityList);
509           contentHash = (SimpleHash)theList.get(i);
510           contentHash.put("tiny_icon", imageRoot+"/"+tinyIcon);
511           contentHash.put("icon_alt", iconAlt);
512         } catch (Exception e){}
513       }
514
515
516         deliver(req, res, modelRoot, templateListString);
517       } else  { // count = 1
518         _showObject(theList.elementAt(0).getId(), req, res);
519       }
520     } catch (StorageObjectException e) {
521       throw new ServletModuleException(e.toString());
522     }
523   }
524
525   private EntityUsers _getUser(HttpServletRequest req)
526   {
527     HttpSession session=req.getSession(false);
528     return (EntityUsers)session.getAttribute("login.uid");
529   }
530 }
531