support for managing users/article types/languages/comment statusses
[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 import org.apache.struts.util.MessageResources;
42
43 import freemarker.template.*;
44
45 import mir.servlet.*;
46 import mir.media.*;
47 import mir.module.*;
48 import mir.misc.*;
49 import mir.storage.*;
50 import mir.entity.*;
51 import mir.util.*;
52 import mir.entity.adapter.*;
53 import mir.log.*;
54
55 import mircoders.global.*;
56 import mircoders.storage.*;
57 import mircoders.module.*;
58 import mircoders.entity.*;
59 import mircoders.localizer.*;
60
61 /*
62  *  ServletModuleContent -
63  *  deliver html for the article admin form.
64  *
65  * @version $Id: ServletModuleContent.java,v 1.27 2002/12/13 17:57:31 zapata Exp $
66  * @author rk, mir-coders
67  *
68  */
69
70 public class ServletModuleContent extends ServletModule
71 {
72   static ModuleTopics         themenModule;
73   static ModuleSchwerpunkt    schwerpunktModule;
74   static ModuleImages         imageModule;
75
76   static String templateOpString;
77
78 // Singelton / Kontruktor
79
80   private static ServletModuleContent instance = new ServletModuleContent();
81   public static ServletModule getInstance() { return instance; }
82
83   private ServletModuleContent() {
84     logger = new LoggerWrapper("ServletModule.Content");
85     try {
86       templateListString = MirConfig.getProp("ServletModule.Content.ListTemplate");
87       templateObjektString = MirConfig.getProp("ServletModule.Content.ObjektTemplate");
88       templateConfirmString = MirConfig.getProp("ServletModule.Content.ConfirmTemplate");
89
90       mainModule = new ModuleContent(DatabaseContent.getInstance());
91       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
92       schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance());
93       imageModule = new ModuleImages(DatabaseImages.getInstance());
94     }
95     catch (StorageObjectException e) {
96       logger.error("servletmodulecontent konnte nicht initialisiert werden");
97     }
98   }
99
100 // Methoden
101
102   public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
103   {
104     EntityUsers user = _getUser(req);
105     String offsetParam = req.getParameter("offset");
106     String whereParam = req.getParameter("where");
107     String orderParam = req.getParameter("order");
108
109     int offset =0;
110
111     if (offsetParam != null && !offsetParam.equals(""))
112       offset = Integer.parseInt(offsetParam);
113
114     if (req.getParameter("next") != null)
115       offset=Integer.parseInt(req.getParameter("nextoffset"));
116     else
117       if (req.getParameter("prev") != null)
118         offset = Integer.parseInt(req.getParameter("prevoffset"));
119
120     returnArticleList(req, res, whereParam, orderParam, offset);
121   }
122
123   public void listop(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
124   {
125     EntityUsers user = _getUser(req);
126     String       offsetParam = req.getParameter("offset");
127     int          offset =0;
128
129     String whereParam = req.getParameter("where");
130
131     if (whereParam==null) whereParam = "to_article_type='0'";
132
133 // hier offsetcode bearbeiteb
134     if (offsetParam != null && !offsetParam.equals(""))
135       offset = Integer.parseInt(offsetParam);
136
137     if (req.getParameter("next") != null)
138       offset=Integer.parseInt(req.getParameter("nextoffset"));
139     else
140       if (req.getParameter("prev") != null)
141         offset = Integer.parseInt(req.getParameter("prevoffset"));
142
143     String orderParam = req.getParameter("order");
144
145     returnArticleList(req, res, whereParam, orderParam, offset);
146   }
147
148
149   public void search(HttpServletRequest req, HttpServletResponse res)
150       throws ServletModuleException {
151     try {
152       EntityUsers   user = _getUser(req);
153       EntityList    theList;
154       String        fieldParam = req.getParameter("field");
155       String        fieldValueParam = req.getParameter("fieldvalue");
156       String        orderParam = req.getParameter("order");
157
158       theList = ((ModuleContent)mainModule).getContentByField(fieldParam, fieldValueParam, orderParam, 0, user);
159       returnArticleList(req, res, "lower("+ fieldParam + ") like lower('%" + StringUtil.quote(fieldValueParam) + "%')", orderParam, 0);
160     } catch (ModuleException e) {
161       throw new ServletModuleException(e.toString());
162     }
163   }
164
165   public void add(HttpServletRequest req, HttpServletResponse res)
166       throws ServletModuleException {
167     _showObject(null, req, res);
168   }
169
170
171   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
172   {
173 //theLog.printDebugInfo(":: content :: trying to insert");
174     try {
175       EntityUsers   user = _getUser(req);
176       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
177
178       String now = StringUtil.date2webdbDate(new GregorianCalendar());
179       withValues.put("date", now);
180       withValues.put("publish_path", StringUtil.webdbDate2path(now));
181       withValues.put("to_publisher", user.getId());
182       withValues.put("is_produced", "0");
183       if (!withValues.containsKey("is_published"))
184         withValues.put("is_published","0");
185       if (!withValues.containsKey("is_html"))
186         withValues.put("is_html","0");
187
188       String id = mainModule.add(withValues);
189       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
190
191       _showObject(id, req, res);
192     }
193     catch (StorageObjectException e) {
194       throw new ServletModuleException(e.toString());
195     }
196     catch (ModuleException e) {
197       throw new ServletModuleException(e.toString());
198     }
199   }
200
201   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
202   {
203     EntityUsers   user = _getUser(req);
204
205     String idParam = req.getParameter("id");
206     if (idParam == null) throw new ServletModuleException("Invalid call: id missing");
207
208     String confirmParam = req.getParameter("confirm");
209     String cancelParam = req.getParameter("cancel");
210
211     logger.info("where = " + req.getParameter("where"));
212
213     if (confirmParam == null && cancelParam == null) {
214
215       SimpleHash mergeData = new SimpleHash();
216       mergeData.put("module", "Content");
217       mergeData.put("infoString", "Content: " + idParam);
218       mergeData.put("id", idParam);
219       mergeData.put("where", req.getParameter("where"));
220       mergeData.put("order", req.getParameter("order"));
221       mergeData.put("offset", req.getParameter("offset"));
222       deliver(req, res, mergeData, templateConfirmString);
223     }
224     else {
225       if (confirmParam!= null && !confirmParam.equals("")) {
226         try {
227           mainModule.deleteById(idParam);
228
229           /** @todo the following two should be implied in
230            *  DatabaseContent */
231
232           //delete rows in the content_x_topic-table
233           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
234           //delete rows in the comment-table
235           DatabaseComment.getInstance().deleteByContentId(idParam);
236         } catch (ModuleException e) {
237           throw new ServletModuleException(e.toString());
238         } catch (StorageObjectException e) {
239           throw new ServletModuleException(e.toString());
240         }
241         list(req,res);
242       }
243       else {
244         // Datensatz anzeigen
245         _showObject(idParam, req, res);
246       }
247     }
248   }
249
250   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
251   {
252     String        idParam = req.getParameter("id");
253     if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
254     _showObject(idParam, req, res);
255   }
256
257 // methods for attaching media file
258   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
259   {
260     String  mediaIdParam = req.getParameter("mid");
261     String  idParam = req.getParameter("cid");
262     if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing");
263
264     try {
265       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
266       entContent.attach(mediaIdParam);
267     }
268     catch(ModuleException e) {
269       logger.error("smod content :: attach :: could not get entityContent");
270     }
271     catch(StorageObjectException e) {
272       logger.error("smod content :: attach :: could not get entityContent");
273     }
274
275     _showObject(idParam, req, res);
276   }
277
278   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
279   {
280     String  cidParam = req.getParameter("cid");
281     String  midParam = req.getParameter("mid");
282     if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing");
283     if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing");
284
285     try {
286       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
287       entContent.dettach(cidParam,midParam);
288     }
289     catch(ModuleException e) {
290       logger.error("smod content :: dettach :: could not get entityContent");
291     }
292     catch(StorageObjectException e) {
293       logger.error("smod content :: dettach :: could not get entityContent");
294     }
295
296     _showObject(cidParam, req, res);
297   }
298
299   public void newswire(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
300   {
301     String  idParam = req.getParameter("id");
302     if (idParam == null) throw new ServletModuleException("smod content :: newswire :: id missing");
303     try {
304       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
305       entContent.newswire();
306     }
307     catch(ModuleException e) {
308       logger.error("smod content :: newswire :: could not get entityContent");
309     }
310     catch(StorageObjectException e) {
311       logger.error("smod content :: dettach :: could not get entityContent");
312     }
313
314     list(req, res);
315   }
316
317
318   public void update(HttpServletRequest req, HttpServletResponse res)
319       throws ServletModuleException
320   {
321     try {
322
323       EntityUsers   user = _getUser(req);
324       if (user==null) logger.debug("user null!");
325       String idParam = req.getParameter("id");
326       if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing");
327
328       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
329       String[] topic_id = req.getParameterValues("to_topic");
330       String content_id = req.getParameter("id");
331
332       if(user != null) withValues.put("user_id", user.getId());
333       withValues.put("is_produced", "0");
334       if (!withValues.containsKey("is_published"))
335         withValues.put("is_published","0");
336       if (!withValues.containsKey("is_html"))
337         withValues.put("is_html","0");
338
339       String id = mainModule.set(withValues);
340       DatabaseContentToTopics.getInstance().setTopics(req.getParameter("id"),topic_id);
341
342       String whereParam = req.getParameter("where");
343       String orderParam = req.getParameter("order");
344
345       if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){
346         list(req,res);
347       }
348       else
349         _showObject(idParam, req, res);
350     }
351     catch (StorageObjectException e) {
352       throw new ServletModuleException(e.toString());
353     }
354     catch (ModuleException e) {
355       throw new ServletModuleException(e.toString());
356     }
357   }
358
359 /*
360   * HelperMethod shows the basic article editing form.
361   *
362   * if the "id" parameter is null, it means show an empty form to add a new
363   * article.
364 */
365   private void _showObject(String id, HttpServletRequest req, HttpServletResponse res)
366       throws ServletModuleException {
367
368     SimpleHash extraInfo = new SimpleHash();
369     try {
370       TemplateModelRoot entContent;
371       if (id != null) {
372         entContent = (TemplateModelRoot)mainModule.getById(id);
373       } else {
374         SimpleHash withValues = new SimpleHash();
375         withValues.put("new", "1");
376         withValues.put("is_published", "0");
377         String now = StringUtil.date2webdbDate(new GregorianCalendar());
378         withValues.put("date", new SimpleScalar(now));
379         EntityUsers   user = _getUser(req);
380         withValues.put("login_user", user);
381         entContent = withValues;
382       }
383
384       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
385       try {
386         extraInfo.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
387       }
388       catch (Exception e) {
389         logger.error("articletype could not be fetched.");
390       }
391       try {
392         extraInfo.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
393       }
394       catch (Exception e) {
395         logger.error("language-popup could not be fetched.");
396       }
397
398       extraInfo.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
399
400       // code to be able to return to the list:
401       String offsetParam, whereParam, orderParam;
402       if ((offsetParam = req.getParameter("offset"))!=null) extraInfo.put("offset", offsetParam);
403       if ((whereParam = req.getParameter("where"))!=null) extraInfo.put("where", whereParam);
404       if ((orderParam = req.getParameter("order"))!=null) extraInfo.put("order", orderParam);
405
406       extraInfo.put("login_user", _getUser(req));
407       deliver(req, res, entContent, extraInfo, templateObjektString);
408     }
409     catch (Exception e) {
410       throw new ServletModuleException(e.toString());
411     }
412   }
413
414   public void returnArticleList(HttpServletRequest aRequest, HttpServletResponse aResponse,
415                                 String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleException {
416     // ML: experiment in using the producer's generation system instead of the
417     //     old one...
418
419     EntityAdapterModel model;
420     int nrArticlesPerPage = 20;
421     int count;
422
423     try {
424       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
425       model = MirGlobal.localizer().dataModel().adapterModel();
426
427       Object contentList =
428           new CachingRewindableIterator(
429           new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
430           MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
431       );
432
433       responseData.put("nexturl", null);
434       responseData.put("prevurl", null);
435
436       count=mainModule.getSize(aWhereClause);
437
438       if (count>=anOffset+nrArticlesPerPage) {
439         responseData.put("nexturl" ,
440                          "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) +
441                          "&order=" + HTMLRoutines.encodeURL(anOrderByClause) +
442                          "&offset=" + anOffset + nrArticlesPerPage);
443       }
444       if (anOffset>0) {
445         responseData.put("prevurl" ,
446                          "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) +
447                          "&order=" + HTMLRoutines.encodeURL(anOrderByClause) +
448                          "&offset=" + Math.max(anOffset - nrArticlesPerPage, 0));
449       }
450
451       responseData.put("articles", contentList);
452
453       responseData.put("thisurl" ,
454                        "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) +
455                        "&order=" + HTMLRoutines.encodeURL(anOrderByClause) +
456                        "&offset=" + anOffset);
457
458       responseData.put("from" , Integer.toString(anOffset+1));
459       responseData.put("count", Integer.toString(count));
460       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
461       responseData.put("offset" , Integer.toString(anOffset));
462       responseData.put("order", anOrderByClause);
463       responseData.put("where" , aWhereClause);
464
465       ServletHelper.generateResponse(aResponse.getWriter(), responseData, "contentlist.template");
466     }
467     catch (Throwable e) {
468       throw new ServletModuleException(e.toString());
469     }
470   }
471
472   private EntityUsers _getUser(HttpServletRequest req)
473   {
474     HttpSession session=req.getSession(false);
475     return (EntityUsers)session.getAttribute("login.uid");
476   }
477 }