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