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