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