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