deindex content when you delete it.
[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 import org.apache.lucene.index.*;
43
44 import freemarker.template.*;
45
46 import mir.servlet.*;
47 import mir.media.*;
48 import mir.module.*;
49 import mir.misc.*;
50 import mir.storage.*;
51 import mir.entity.*;
52 import mir.util.*;
53 import mir.entity.adapter.*;
54 import mir.log.*;
55
56 import mircoders.global.*;
57 import mircoders.storage.*;
58 import mircoders.module.*;
59 import mircoders.entity.*;
60 import mircoders.localizer.*;
61 import mircoders.search.IndexUtil;
62
63 /*
64  *  ServletModuleContent -
65  *  deliver html for the article admin form.
66  *
67  * @version $Id: ServletModuleContent.java,v 1.31 2003/01/18 15:55:14 john Exp $
68  * @author rk, mir-coders
69  *
70  */
71
72 public class ServletModuleContent extends ServletModule
73 {
74   static ModuleTopics         themenModule;
75   static ModuleSchwerpunkt    schwerpunktModule;
76   static ModuleImages         imageModule;
77
78   static String templateOpString;
79
80 // Singelton / Kontruktor
81
82   private static ServletModuleContent instance = new ServletModuleContent();
83   public static ServletModule getInstance() { return instance; }
84
85   private ServletModuleContent() {
86     logger = new LoggerWrapper("ServletModule.Content");
87     try {
88       templateListString = MirConfig.getProp("ServletModule.Content.ListTemplate");
89       templateObjektString = MirConfig.getProp("ServletModule.Content.ObjektTemplate");
90       templateConfirmString = MirConfig.getProp("ServletModule.Content.ConfirmTemplate");
91
92       mainModule = new ModuleContent(DatabaseContent.getInstance());
93       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
94       schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance());
95       imageModule = new ModuleImages(DatabaseImages.getInstance());
96     }
97     catch (StorageObjectException e) {
98       logger.error("servletmodulecontent konnte nicht initialisiert werden");
99     }
100   }
101
102 // Methoden
103
104   public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
105   {
106     EntityUsers user = _getUser(req);
107     String offsetParam = req.getParameter("offset");
108     String whereParam = req.getParameter("where");
109     String orderParam = req.getParameter("order");
110
111     int offset =0;
112
113     if (offsetParam != null && !offsetParam.equals(""))
114       offset = Integer.parseInt(offsetParam);
115
116     if (req.getParameter("next") != null)
117       offset=Integer.parseInt(req.getParameter("nextoffset"));
118     else
119       if (req.getParameter("prev") != null)
120         offset = Integer.parseInt(req.getParameter("prevoffset"));
121
122     returnArticleList(req, res, whereParam, orderParam, offset);
123   }
124
125   public void listop(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
126   {
127     EntityUsers user = _getUser(req);
128     String       offsetParam = req.getParameter("offset");
129     int          offset =0;
130
131     String whereParam = req.getParameter("where");
132
133     if (whereParam==null) whereParam = "to_article_type='0'";
134
135 // hier offsetcode bearbeiteb
136     if (offsetParam != null && !offsetParam.equals(""))
137       offset = Integer.parseInt(offsetParam);
138
139     if (req.getParameter("next") != null)
140       offset=Integer.parseInt(req.getParameter("nextoffset"));
141     else
142       if (req.getParameter("prev") != null)
143         offset = Integer.parseInt(req.getParameter("prevoffset"));
144
145     String orderParam = req.getParameter("order");
146
147     returnArticleList(req, res, whereParam, orderParam, offset);
148   }
149
150
151   public void search(HttpServletRequest req, HttpServletResponse res)
152       throws ServletModuleException {
153     try {
154       EntityUsers   user = _getUser(req);
155       EntityList    theList;
156       String        fieldParam = req.getParameter("field");
157       String        fieldValueParam = req.getParameter("fieldvalue");
158       String        orderParam = req.getParameter("order");
159
160       theList = ((ModuleContent)mainModule).getContentByField(fieldParam, fieldValueParam, orderParam, 0, user);
161       returnArticleList(req, res, "lower("+ fieldParam + ") like lower('%" + JDBCStringRoutines.escapeStringLiteral(fieldValueParam) + "%')", orderParam, 0);
162     } catch (ModuleException e) {
163       throw new ServletModuleException(e.toString());
164     }
165   }
166
167   public void add(HttpServletRequest req, HttpServletResponse res)
168       throws ServletModuleException {
169     _showObject(null, req, res);
170   }
171
172
173   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
174   {
175 //theLog.printDebugInfo(":: content :: trying to insert");
176     try {
177       EntityUsers   user = _getUser(req);
178       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
179
180       String now = StringUtil.date2webdbDate(new GregorianCalendar());
181       withValues.put("date", now);
182       withValues.put("publish_path", StringUtil.webdbDate2path(now));
183       withValues.put("to_publisher", user.getId());
184       withValues.put("is_produced", "0");
185       if (!withValues.containsKey("is_published"))
186         withValues.put("is_published","0");
187       if (!withValues.containsKey("is_html"))
188         withValues.put("is_html","0");
189
190       String id = mainModule.add(withValues);
191       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
192
193       _showObject(id, req, res);
194     }
195     catch (StorageObjectException e) {
196       throw new ServletModuleException(e.toString());
197     }
198     catch (ModuleException e) {
199       throw new ServletModuleException(e.toString());
200     }
201   }
202
203   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
204   {
205     EntityUsers   user = _getUser(req);
206
207     String idParam = req.getParameter("id");
208     if (idParam == null) throw new ServletModuleException("Invalid call: id missing");
209
210     String confirmParam = req.getParameter("confirm");
211     String cancelParam = req.getParameter("cancel");
212
213     logger.info("where = " + req.getParameter("where"));
214
215     if (confirmParam == null && cancelParam == null) {
216
217       SimpleHash mergeData = new SimpleHash();
218       mergeData.put("module", "Content");
219       mergeData.put("infoString", "Content: " + idParam);
220       mergeData.put("id", idParam);
221       mergeData.put("where", req.getParameter("where"));
222       mergeData.put("order", req.getParameter("order"));
223       mergeData.put("offset", req.getParameter("offset"));
224       deliver(req, res, mergeData, templateConfirmString);
225     }
226     else {
227       if (confirmParam!= null && !confirmParam.equals("")) {
228         try {
229           mainModule.deleteById(idParam);
230
231           /** @todo the following two should be implied in
232            *  DatabaseContent */
233
234           //delete rows in the content_x_topic-table
235           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
236           //delete rows in the comment-table
237           DatabaseComment.getInstance().deleteByContentId(idParam);
238           //delete from lucene index, if any
239           String index=MirConfig.getProp("IndexPath");
240           if (IndexReader.indexExists(index)){
241             IndexUtil.unindexID(idParam,index);
242           }
243           
244         } catch (ModuleException e) {
245           throw new ServletModuleException(e.toString());
246         } catch (StorageObjectException e) {
247           throw new ServletModuleException(e.toString());
248         } catch (IOException e) {
249           throw new ServletModuleException(e.toString());
250         }
251         list(req,res);
252       }
253       else {
254         // Datensatz anzeigen
255         _showObject(idParam, req, res);
256       }
257     }
258   }
259
260   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
261   {
262     String        idParam = req.getParameter("id");
263     if (idParam == null) throw new ServletModuleException("Invalid call: id not supplied ");
264     _showObject(idParam, req, res);
265   }
266
267 // methods for attaching media file
268   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
269   {
270     String  mediaIdParam = req.getParameter("mid");
271     String  idParam = req.getParameter("cid");
272     if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing");
273
274     try {
275       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
276       entContent.attach(mediaIdParam);
277     }
278     catch(ModuleException e) {
279       logger.error("smod content :: attach :: could not get entityContent");
280     }
281     catch(StorageObjectException e) {
282       logger.error("smod content :: attach :: could not get entityContent");
283     }
284
285     _showObject(idParam, req, res);
286   }
287
288   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
289   {
290     String  cidParam = req.getParameter("cid");
291     String  midParam = req.getParameter("mid");
292     if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing");
293     if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing");
294
295     try {
296       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
297       entContent.dettach(cidParam,midParam);
298     }
299     catch(ModuleException e) {
300       logger.error("smod content :: dettach :: could not get entityContent");
301     }
302     catch(StorageObjectException e) {
303       logger.error("smod content :: dettach :: could not get entityContent");
304     }
305
306     _showObject(cidParam, req, res);
307   }
308
309   public void newswire(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
310   {
311     String  idParam = req.getParameter("id");
312     if (idParam == null) throw new ServletModuleException("smod content :: newswire :: id missing");
313     try {
314       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
315       entContent.newswire();
316     }
317     catch(ModuleException e) {
318       logger.error("smod content :: newswire :: could not get entityContent");
319     }
320     catch(StorageObjectException e) {
321       logger.error("smod content :: dettach :: could not get entityContent");
322     }
323
324     list(req, res);
325   }
326
327
328   public void update(HttpServletRequest req, HttpServletResponse res)
329       throws ServletModuleException
330   {
331     try {
332
333       EntityUsers   user = _getUser(req);
334       if (user==null) logger.debug("user null!");
335       String idParam = req.getParameter("id");
336       if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing");
337
338       HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());
339       String[] topic_id = req.getParameterValues("to_topic");
340       String content_id = req.getParameter("id");
341
342       if(user != null) withValues.put("user_id", user.getId());
343       withValues.put("is_produced", "0");
344       if (!withValues.containsKey("is_published"))
345         withValues.put("is_published","0");
346       if (!withValues.containsKey("is_html"))
347         withValues.put("is_html","0");
348
349       String id = mainModule.set(withValues);
350       DatabaseContentToTopics.getInstance().setTopics(req.getParameter("id"),topic_id);
351
352       String whereParam = req.getParameter("where");
353       String orderParam = req.getParameter("order");
354
355       if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){
356         list(req,res);
357       }
358       else
359         _showObject(idParam, req, res);
360     }
361     catch (StorageObjectException e) {
362       throw new ServletModuleException(e.toString());
363     }
364     catch (ModuleException e) {
365       throw new ServletModuleException(e.toString());
366     }
367   }
368
369 /*
370   * HelperMethod shows the basic article editing form.
371   *
372   * if the "id" parameter is null, it means show an empty form to add a new
373   * article.
374 */
375   private void _showObject(String id, HttpServletRequest req, HttpServletResponse res)
376       throws ServletModuleException {
377
378     SimpleHash extraInfo = new SimpleHash();
379     try {
380       TemplateModelRoot entContent;
381
382       if (id != null) {
383         entContent = (TemplateModelRoot)mainModule.getById(id);
384       }
385       else {
386         SimpleHash withValues = new SimpleHash();
387         withValues.put("new", "1");
388         withValues.put("is_published", "0");
389         String now = StringUtil.date2webdbDate(new GregorianCalendar());
390         withValues.put("date", new SimpleScalar(now));
391         EntityUsers   user = _getUser(req);
392         withValues.put("login_user", user);
393         entContent = withValues;
394       }
395
396       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
397       extraInfo.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
398       extraInfo.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData());
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 }