organising imports
[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.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.servlet.http.HttpSession;
43
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.ServletModuleExc;
51 import mir.servlet.ServletModuleFailure;
52 import mir.storage.StorageObjectFailure;
53 import mir.util.CachingRewindableIterator;
54 import mir.util.HTTPRequestParser;
55 import mir.util.JDBCStringRoutines;
56 import mir.util.SQLQueryBuilder;
57 import mir.util.URLBuilder;
58 import mircoders.entity.EntityContent;
59 import mircoders.entity.EntityUsers;
60 import mircoders.global.MirGlobal;
61 import mircoders.module.ModuleContent;
62 import mircoders.search.IndexUtil;
63 import mircoders.storage.DatabaseComment;
64 import mircoders.storage.DatabaseContent;
65 import mircoders.storage.DatabaseContentToTopics;
66
67 import org.apache.lucene.index.IndexReader;
68
69 import freemarker.template.SimpleHash;
70
71 /*
72  *  ServletModuleContent -
73  *  deliver html for the article admin form.
74  *
75  * @version $Id: ServletModuleContent.java,v 1.41 2003/03/08 17:18:19 idfx Exp $
76  * @author rk, mir-coders
77  *
78  */
79
80 public class ServletModuleContent extends ServletModule
81 {
82   private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;
83   private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");
84
85   private static ServletModuleContent instance = new ServletModuleContent();
86   public static ServletModule getInstance() { return instance; }
87
88   private ServletModuleContent() {
89     super();
90     logger = new LoggerWrapper("ServletModule.Content");
91     try {
92
93       templateListString = configuration.getString("ServletModule.Content.ListTemplate");
94       templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");
95       templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");
96
97       mainModule = new ModuleContent(DatabaseContent.getInstance());
98     }
99     catch (StorageObjectFailure e) {
100       logger.error("servletmodulecontent konnte nicht initialisiert werden");
101     }
102   }
103
104   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
105   {
106     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
107
108     String where = requestParser.getParameter("where");
109     String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
110     int offset = requestParser.getIntegerWithDefault("offset", 0);
111     String selectArticleUrl = requestParser.getParameter("selectarticleurl");
112
113     returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);
114   }
115
116   public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
117     try {
118       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
119       SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
120       String searchField = requestParser.getParameterWithDefault("searchfield", "");
121       String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
122       String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
123       String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
124       String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
125       String selectArticleUrl = requestParser.getParameter("selectarticleurl");
126
127       if (searchValue.length()>0) {
128         if (searchField.equals("contents"))
129           queryBuilder.appendAndCondition(
130             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
131             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
132         else
133           queryBuilder.appendAndCondition(
134             "lower("+ searchField + ") like " +
135             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
136       }
137
138       if (searchispublished.length()>0) {
139         if (searchispublished.equals("0"))
140           queryBuilder.appendAndCondition("is_published='f'");
141         else
142           queryBuilder.appendAndCondition("is_published='t'");
143       }
144
145       if (searchArticleType.length()>0) {
146         queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
147       }
148
149       if (searchOrder.length()>0) {
150         if (searchOrder.equals("datedesc"))
151           queryBuilder.appendAscendingOrder("webdb_create");
152         else if (searchOrder.equals("dateasc"))
153           queryBuilder.appendDescendingOrder("webdb_create");
154         else if (searchOrder.equals("title"))
155           queryBuilder.appendDescendingOrder("title");
156         else if (searchOrder.equals("creator"))
157           queryBuilder.appendDescendingOrder("creator");
158       }
159
160       returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
161     }
162     catch (Throwable e) {
163       throw new ServletModuleFailure(e);
164     }
165   }
166
167   public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
168     _showObject(null, req, res);
169   }
170
171
172   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
173   {
174 //theLog.printDebugInfo(":: content :: trying to insert");
175     try {
176       EntityUsers   user = _getUser(req);
177       Map 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 (Throwable e) {
195       throw new ServletModuleFailure(e);
196     }
197   }
198
199   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
200   {
201     EntityUsers   user = _getUser(req);
202
203     String idParam = req.getParameter("id");
204     if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
205
206     String confirmParam = req.getParameter("confirm");
207     String cancelParam = req.getParameter("cancel");
208
209     logger.info("where = " + req.getParameter("where"));
210
211     if (confirmParam == null && cancelParam == null) {
212
213       SimpleHash mergeData = new SimpleHash();
214       mergeData.put("module", "Content");
215       mergeData.put("infoString", "Content: " + idParam);
216       mergeData.put("id", idParam);
217       mergeData.put("where", req.getParameter("where"));
218       mergeData.put("order", req.getParameter("order"));
219       mergeData.put("offset", req.getParameter("offset"));
220       deliver(req, res, mergeData, templateConfirmString);
221     }
222     else {
223       if (confirmParam!= null && !confirmParam.equals("")) {
224         try {
225           mainModule.deleteById(idParam);
226
227           /** @todo the following two should be implied in
228            *  DatabaseContent */
229
230           //delete rows in the content_x_topic-table
231           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
232           //delete rows in the comment-table
233           DatabaseComment.getInstance().deleteByContentId(idParam);
234           //delete from lucene index, if any
235           String index = configuration.getString("IndexPath");
236           if (IndexReader.indexExists(index)){
237             IndexUtil.unindexID(idParam,index);
238           }
239
240         }
241         catch (Throwable e) {
242           throw new ServletModuleFailure(e);
243         }
244         list(req,res);
245       }
246       else {
247         // Datensatz anzeigen
248         _showObject(idParam, req, res);
249       }
250     }
251   }
252
253   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
254   {
255     String idParam = req.getParameter("id");
256     if (idParam == null)
257       throw new ServletModuleExc("Invalid call: id not supplied ");
258     _showObject(idParam, req, res);
259   }
260
261 // methods for attaching media file
262   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
263   {
264     String  mediaIdParam = req.getParameter("mid");
265     String  idParam = req.getParameter("cid");
266     if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing");
267
268     try {
269       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
270       entContent.attach(mediaIdParam);
271     }
272     catch(ModuleException e) {
273       logger.error("smod content :: attach :: could not get entityContent");
274     }
275     catch(StorageObjectFailure e) {
276       logger.error("smod content :: attach :: could not get entityContent");
277     }
278
279     _showObject(idParam, req, res);
280   }
281
282   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
283   {
284     String  cidParam = req.getParameter("cid");
285     String  midParam = req.getParameter("mid");
286     if (cidParam == null)
287       throw new ServletModuleExc("smod content :: dettach :: cid missing");
288     if (midParam == null)
289       throw new ServletModuleExc("smod content :: dettach :: mid missing");
290
291     try {
292       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
293       entContent.dettach(cidParam,midParam);
294     }
295     catch(ModuleException e) {
296       logger.error("smod content :: dettach :: could not get entityContent");
297     }
298     catch(StorageObjectFailure e) {
299       logger.error("smod content :: dettach :: could not get entityContent");
300     }
301
302     _showObject(cidParam, req, res);
303   }
304
305   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
306   {
307     try {
308       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
309
310       String returnUrl = requestParser.getParameter("returnurl");
311
312       String idParam = aRequest.getParameter("id");
313       if (idParam == null)
314         throw new ServletModuleExc("Wrong call: (id) is missing");
315
316       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
317       String[] topic_id = aRequest.getParameterValues("to_topic");
318       String content_id = aRequest.getParameter("id");
319
320       withValues.put("is_produced", "0");
321       if (!withValues.containsKey("is_published"))
322         withValues.put("is_published","0");
323       if (!withValues.containsKey("is_html"))
324         withValues.put("is_html","0");
325
326       String id = mainModule.set(withValues);
327       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);
328
329       String whereParam = aRequest.getParameter("where");
330       String orderParam = aRequest.getParameter("order");
331
332       if (returnUrl!=null){
333         redirect(aResponse, returnUrl);
334       }
335       else
336         _showObject(idParam, aRequest, aResponse);
337     }
338     catch (Throwable e) {
339       throw new ServletModuleFailure(e);
340     }
341   }
342
343 /*
344   * HelperMethod shows the basic article editing form.
345   *
346   * if the "id" parameter is null, it means show an empty form to add a new
347   * article.
348 */
349   public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
350       throws ServletModuleExc {
351     try {
352       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
353       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
354       EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
355       Map article;
356       URLBuilder urlBuilder = new URLBuilder();
357
358       urlBuilder.setValue("module", "Content");
359       urlBuilder.setValue("do", "edit");
360       urlBuilder.setValue("id", id);
361       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
362
363       if (id!=null) {
364         responseData.put("new", Boolean.FALSE);
365         article = model.makeEntityAdapter("content", mainModule.getById(id));
366       }
367       else {
368         List fields = DatabaseContent.getInstance().getFields();
369         responseData.put("new", Boolean.TRUE);
370         article = new HashMap();
371         Iterator i = fields.iterator();
372         while (i.hasNext()) {
373           article.put(i.next(), null);
374         }
375
376         article.put("to_topics", null);
377
378         MirGlobal.localizer().adminInterface().initializeArticle(article);
379       }
380       responseData.put("article", article);
381
382       responseData.put("returnurl", requestParser.getParameter("returnurl"));
383       responseData.put("thisurl", urlBuilder.getQuery());
384
385       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
386     }
387     catch (Throwable e) {
388       throw new ServletModuleFailure(e);
389     }
390   }
391
392   public void returnArticleList(
393        HttpServletRequest aRequest,
394        HttpServletResponse aResponse,
395        String aWhereClause,
396        String anOrderByClause,
397        int anOffset,
398        String aSelectArticleUrl) throws ServletModuleExc {
399
400     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
401     URLBuilder urlBuilder = new URLBuilder();
402     EntityAdapterModel model;
403     int nrArticlesPerPage = 20;
404     int count;
405
406     try {
407       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
408       model = MirGlobal.localizer().dataModel().adapterModel();
409
410       Object articleList =
411           new CachingRewindableIterator(
412             new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
413                MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
414       );
415
416       responseData.put("nexturl", null);
417       responseData.put("prevurl", null);
418
419       count=mainModule.getSize(aWhereClause);
420
421       urlBuilder.setValue("module", "Content");
422       urlBuilder.setValue("do", "list");
423       urlBuilder.setValue("where", aWhereClause);
424       urlBuilder.setValue("order", anOrderByClause);
425
426
427       urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
428       urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
429       urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
430       urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
431       urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
432       urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
433
434       responseData.put("searchfield", requestParser.getParameter("searchfield"));
435       responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
436       responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
437       responseData.put("searchorder", requestParser.getParameter("searchorder"));
438       responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
439       responseData.put("selectarticleurl", aSelectArticleUrl);
440
441       urlBuilder.setValue("offset", anOffset);
442       responseData.put("offset" , new Integer(anOffset).toString());
443       responseData.put("thisurl" , urlBuilder.getQuery());
444
445       if (count>=anOffset+nrArticlesPerPage) {
446         urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
447         responseData.put("nexturl" , urlBuilder.getQuery());
448       }
449
450       if (anOffset>0) {
451         urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
452         responseData.put("prevurl" , urlBuilder.getQuery());
453       }
454
455       responseData.put("articles", articleList);
456
457       responseData.put("from" , Integer.toString(anOffset+1));
458       responseData.put("count", Integer.toString(count));
459       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
460       responseData.put("offset" , Integer.toString(anOffset));
461       responseData.put("order", anOrderByClause);
462       responseData.put("where" , aWhereClause);
463
464       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
465     }
466     catch (Throwable e) {
467       throw new ServletModuleFailure(e);
468     }
469   }
470
471   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
472   {
473     try {
474       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
475       URLBuilder urlBuilder = new URLBuilder();
476
477       urlBuilder.setValue("module", "Content");
478       urlBuilder.setValue("do", "setparent");
479       urlBuilder.setValue("childid", requestParser.getParameter("id"));
480       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
481
482       returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
483     }
484     catch (Throwable e) {
485       throw new ServletModuleFailure(e);
486     }
487   }
488
489   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
490   {
491     try {
492       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
493       String articleId = requestParser.getParameter("article_id");
494
495       if (articleId == null)
496         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
497
498       returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
499     }
500     catch (Throwable e) {
501       throw new ServletModuleFailure(e);
502     }
503   }
504
505   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
506   {
507     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
508     String articleId = aRequest.getParameter("childid");
509     String parentId  = aRequest.getParameter("id");
510     String returnUrl = aRequest.getParameter("returnurl");
511
512     try {
513       EntityContent article = (EntityContent) mainModule.getById(articleId);
514       article.setValueForProperty("to_content", parentId);
515       article.setProduced(false);
516       article.update();
517     }
518     catch(Throwable e) {
519       logger.error("ServletModuleContent.setparent: " + e.getMessage());
520       throw new ServletModuleFailure(e);
521     }
522
523     redirect(aResponse, returnUrl);
524   }
525
526   public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
527   {
528     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
529     String articleId = requestParser.getParameter("id");
530     String returnUrl = requestParser.getParameter("returnurl");
531
532     try {
533       EntityContent article = (EntityContent) mainModule.getById(articleId);
534       article.setValueForProperty("to_content", "");
535       article.setProduced(false);
536       article.update();
537     }
538     catch(Throwable e) {
539       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
540       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
541
542       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
543     }
544
545     redirect(aResponse, returnUrl);
546   }
547
548   private EntityUsers _getUser(HttpServletRequest req)
549   {
550     HttpSession session=req.getSession(false);
551
552     return (EntityUsers)session.getAttribute("login.uid");
553   }
554 }