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