no message
[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(this.getClass().getName());
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     mergeData.put("new", "1");
147     mergeData.put("is_published", "1");
148     String now = StringUtil.date2webdbDate(new GregorianCalendar());
149     mergeData.put("date", new SimpleScalar(now));
150     mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
151     try {
152       mergeData.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
153     } catch (Exception e) {
154       theLog.printError("articletype could not be fetched.");
155     }
156     try {
157       mergeData.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
158     } catch (Exception e) {
159       theLog.printError("language-popup could not be fetched.");
160     }
161     mergeData.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
162     mergeData.put("login_user", user);
163     deliver(req, res, mergeData, templateObjektString);
164   }
165
166
167   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
168   {
169     //theLog.printDebugInfo(":: content :: trying to insert");
170     try {
171       EntityUsers   user = _getUser(req);
172       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
173       //theLog.printDebugInfo(":: content :: got intersecting values");
174       String now = StringUtil.date2webdbDate(new GregorianCalendar());
175       withValues.put("date", now);
176       withValues.put("publish_path", StringUtil.webdbDate2path(now));
177       withValues.put("to_publisher", user.getId());
178       withValues.put("is_produced", "0");
179       if (!withValues.containsKey("is_published"))
180         withValues.put("is_published","0");
181       if (!withValues.containsKey("is_html"))
182         withValues.put("is_html","0");
183       if (withValues.get("creator").toString().equals(""))
184         withValues.put("creator","Anonym");
185       String id = mainModule.add(withValues);
186       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
187       //theLog.printDebugInfo(":: content :: inserted");
188       _showObject(id, req, res);
189     }
190     catch (StorageObjectException e) {
191       throw new ServletModuleException(e.toString());
192     }
193     catch (ModuleException e) {
194       throw new ServletModuleException(e.toString());
195     }
196   }
197
198   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
199   {
200
201     EntityUsers   user = _getUser(req);
202     // hier pruefen ob dem akt. user loeschen erlaubt ist...
203     String idParam = req.getParameter("id");
204     if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
205
206     String confirmParam = req.getParameter("confirm");
207     String cancelParam = req.getParameter("cancel");
208
209     if (confirmParam == null && cancelParam == null) {
210       // HTML Ausgabe zum Confirmen!
211       SimpleHash mergeData = new SimpleHash();
212       mergeData.put("module", "Content");
213       mergeData.put("infoString", "Content: " + idParam);
214       mergeData.put("id", idParam);
215       mergeData.put("where", req.getParameter("where"));
216       mergeData.put("order", req.getParameter("order"));
217       mergeData.put("offset", req.getParameter("offset"));
218       deliver(req, res, mergeData, templateConfirmString);
219     }
220     else {
221       if (confirmParam!= null && !confirmParam.equals("")) {
222         try {
223           mainModule.deleteById(idParam);
224
225           /** @todo the following two should be imlied in
226            *  DatabaseContent */
227
228           //delete rows in the content_x_topic-table
229           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
230           //delete rows in the comment-table
231           DatabaseComment.getInstance().deleteByContentId(idParam);
232         } catch (ModuleException e) {
233           throw new ServletModuleException(e.toString());
234         } catch (StorageObjectException e) {
235           throw new ServletModuleException(e.toString());
236         }
237         list(req,res);
238       }
239       else {
240         // Datensatz anzeigen
241         _showObject(idParam, req, res);
242       }
243     }
244   }
245
246   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
247   {
248     String        idParam = req.getParameter("id");
249     if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
250     _showObject(idParam, req, res);
251   }
252
253   // methods for attaching media file
254   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
255   {
256     String  mediaIdParam = req.getParameter("mid");
257     String  idParam = req.getParameter("cid");
258     if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing");
259
260     try {
261       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
262       entContent.attach(mediaIdParam);
263     }
264     catch(ModuleException e) {
265       theLog.printError("smod content :: attach :: could not get entityContent");
266     }
267     _showObject(idParam, req, res);
268   }
269
270   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
271   {
272     String  cidParam = req.getParameter("cid");
273                 String  midParam = req.getParameter("mid");
274     if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing");
275     if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing");
276
277     try {
278       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
279       entContent.dettach(cidParam,midParam);
280     }
281     catch(ModuleException e) {
282       theLog.printError("smod content :: dettach :: could not get entityContent");
283     }
284     _showObject(cidParam, req, res);
285   }
286
287   public void newswire(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
288   {
289     String  idParam = req.getParameter("id");
290     if (idParam == null) throw new ServletModuleException("smod content :: newswire :: id missing");
291     try {
292       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
293       entContent.newswire();
294     }
295     catch(ModuleException e) {
296       theLog.printError("smod content :: newswire :: could not get entityContent");
297     }
298     list(req, res);
299   }
300
301
302   public void update(HttpServletRequest req, HttpServletResponse res)
303     throws ServletModuleException
304   {
305     try {
306
307       EntityUsers   user = _getUser(req);
308       if (user==null) theLog.printDebugInfo("user null!");
309       String idParam = req.getParameter("id");
310       if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing");
311
312       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
313       String[] topic_id = req.getParameterValues("to_topic");
314       String content_id = req.getParameter("id");
315       // withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
316       if(user != null) withValues.put("user_id", user.getId());
317       withValues.put("is_produced", "0");
318       if (!withValues.containsKey("is_published"))
319         withValues.put("is_published","0");
320       if (!withValues.containsKey("is_html"))
321         withValues.put("is_html","0");
322       if (withValues.get("creator").toString().equals(""))
323         withValues.put("creator","Anonym");
324       //theLog.printDebugInfo("updating. ");
325       String id = mainModule.set(withValues);
326       DatabaseContentToTopics.getInstance().setTopics(req.getParameter("id"),topic_id);
327       //theLog.printDebugInfo("update done. ");
328       String whereParam = req.getParameter("where");
329       String orderParam = req.getParameter("order");
330       if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){
331         //theLog.printDebugInfo("update to list");
332         list(req,res);
333       }
334       else
335         _showObject(idParam, req, res);
336     }
337     catch (StorageObjectException e) {
338       throw new ServletModuleException(e.toString());
339     }
340     catch (ModuleException e) {
341       throw new ServletModuleException(e.toString());
342     }
343   }
344
345   //
346   // Hilfsmethoden
347
348   private void _showObject(String id, HttpServletRequest req, HttpServletResponse res)
349     throws ServletModuleException {
350
351     try {
352       EntityContent entContent=(EntityContent)mainModule.getById(id);
353       SimpleHash mergeData =  HTMLTemplateProcessor.makeSimpleHash(entContent);
354       EntityList topicToContent = DatabaseContentToTopics.getInstance().getTopics(entContent);
355       if (topicToContent!=null && topicToContent.size()>0){
356         theLog.printDebugInfo("topicanzahl: "+topicToContent.size());
357         Entity topics = null;
358         SimpleList topicList = new SimpleList();
359         for(int i=0;i<topicToContent.size();i++){
360           topics = (EntityTopics)topicToContent.elementAt(i);
361           topicList.add(topics.getId());
362         }
363         mergeData.put("to_topic",topicList);
364       }
365       //obsolete, because of psqgl 7.1.x
366       //mergeData.put("content_data", entContent.getContentData());
367       mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
368       try {
369         mergeData.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
370       } catch (Exception e) {
371         theLog.printError("articletype could not be fetched.");
372       }
373       try {
374         mergeData.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
375       } catch (Exception e) {
376         theLog.printError("language-popup could not be fetched.");
377       }
378       // get the images
379       EntityList currentMedia = DatabaseContentToMedia.getInstance().getMedia(entContent);
380       if (currentMedia!=null && currentMedia.getCount()>=1) {
381         SimpleList mediaList = HTMLTemplateProcessor.makeSimpleList(currentMedia);
382                                 mergeData.put("to_media", mediaList);
383       }
384
385
386       mergeData.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
387       // hier code um zur liste zurueckzukommen
388       String offsetParam, whereParam, orderParam;
389       if ((offsetParam = req.getParameter("offset"))!=null) mergeData.put("offset", offsetParam);
390       if ((whereParam = req.getParameter("where"))!=null) mergeData.put("where", whereParam);
391       if ((orderParam = req.getParameter("order"))!=null) mergeData.put("order", orderParam);
392       mergeData.put("login_user", _getUser(req));
393       deliver(req, res, mergeData, templateObjektString);
394     } catch (Exception e) {
395       throw new ServletModuleException(e.toString());
396     }
397   }
398
399
400   public void _list(EntityList theList, HttpServletRequest req, HttpServletResponse res)
401     throws ServletModuleException {
402
403     try {
404       // hier dann htmlcode rausschreiben
405       if (theList == null || theList.getCount() == 0 || theList.getCount()>1) {
406         SimpleHash modelRoot = HTMLTemplateProcessor.makeSimpleHashWithEntitylistInfos(theList);
407         modelRoot.put("themenHashData", themenModule.getHashData());
408         modelRoot.put("schwerpunktHashData", schwerpunktModule.getHashData());
409         modelRoot.put("articletypeHash", DatabaseArticleType.getInstance().getHashData());
410         deliver(req, res, modelRoot, templateListString);
411       } else  { // count = 1
412         _showObject(theList.elementAt(0).getId(),req,res);
413       }
414     } catch (StorageObjectException e) {
415       throw new ServletModuleException(e.toString());
416     }
417   }
418
419   public void _listop(EntityList theList, HttpServletRequest req, HttpServletResponse res)
420     throws ServletModuleException {
421
422     try {
423       // delivering html
424       if (theList == null || theList.getCount() == 0 || theList.getCount()>1) {
425         SimpleHash modelRoot = HTMLTemplateProcessor.makeSimpleHashWithEntitylistInfos(theList);
426         modelRoot.put("articletypeHash", DatabaseArticleType.getInstance().getHashData());
427
428     EntityContent       currentContent;
429     EntityList          upMediaEntityList;
430     EntityList          imageEntityList;
431     EntityList          currentMediaList;
432     Entity              mediaType;
433     EntityMedia         uploadedMedia;
434     SimpleList          opList;
435       String imageRoot = MirConfig.getProp("Producer.ImageRoot");
436
437     SimpleHash          contentHash;
438     Class               mediaHandlerClass=null;
439     MirMedia            mediaHandler=null;
440     String              mediaHandlerName=null;
441     Database            mediaStorage=null;
442     String              tinyIcon;
443     String              iconAlt;
444
445     opList = HTMLTemplateProcessor.makeSimpleList(theList);
446
447       for (int i=0; i < theList.size();i++) {
448         currentContent = (EntityContent)theList.elementAt(i);
449         //fetching/setting the images
450         upMediaEntityList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
451         if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
452           tinyIcon = null;
453           iconAlt = null;
454           mediaHandler = null;
455           mediaHandlerName = null;
456           for (int n=0; n < upMediaEntityList.size();n++) {
457             uploadedMedia = (EntityMedia)upMediaEntityList.elementAt(n);
458             mediaType = uploadedMedia.getMediaType();
459
460             //must of had a non-existant to_media_type entry..
461             //let's save our ass.
462             if (mediaType != null) {
463                 /*
464                  * grrr. why doesn't getId return an int! if It
465                  * did I could just compare the value of getId and
466                  * pick the biggest one. or is there
467                  * another way around this that I am missing?
468                  * can we make getIdasInt() or can we just have
469                  * another getId() that returns an Int and the VM
470                  * will handle it transparantly? -mh
471                  */
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)opList.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